VS Code Extension - Development Guide
Note: This guide is for developers who want to understand, extend, or contribute to the VS Code extension component of n8n-as-code.
๐ฏ Purposeโ
The VS Code extension (@n8n-as-code/vscode-extension) provides a visual interface for managing n8n workflows directly within VS Code. It integrates with the Core library to offer:
- Workflow Tree View: Browse workflows organized by n8n instance
- Visual Editing: Webview-based n8n canvas for workflow editing
- Real-time Sync: Automatic synchronization with n8n instances
- Proxy Service: Secure communication between VS Code and n8n
๐๏ธ Architectureโ
Extension Structureโ
packages/vscode-extension/
โโโ src/
โ โโโ extension.ts # Main extension entry point
โ โโโ services/
โ โ โโโ proxy-service.ts # Proxy between VS Code and n8n
โ โโโ ui/
โ โโโ status-bar.ts # Status bar integration
โ โโโ workflow-tree-provider.ts # Tree view provider
โ โโโ workflow-webview.ts # Webview for workflow editing
โโโ package.json # Extension manifest
โโโ tsconfig.json # TypeScript configuration
Component Relationshipsโ
graph TD
A[Extension Activation] --> B[WorkflowTreeProvider]
A --> C[WorkflowWebview]
A --> D[ProxyService]
A --> E[StatusBar]
B --> F[Core Library]
C --> D
D --> G[n8n API]
E --> H[VS Code API]
style A fill:#ff6b35
style B fill:#3498db
style C fill:#2ecc71
style D fill:#9b59b6
๐งฉ Core Componentsโ
1. Extension Entry Point (extension.ts)โ
The main entry point that activates the extension.
Key Responsibilities:
- Register all extension components
- Manage extension lifecycle (activate/deactivate)
- Handle configuration changes
- Initialize Core library integration
Activation Flow:
export function activate(context: vscode.ExtensionContext) {
// Initialize services
const proxyService = new ProxyService(context);
const treeProvider = new WorkflowTreeProvider(context, proxyService);
const statusBar = new StatusBar(context);
// Register providers
vscode.window.registerTreeDataProvider('n8n-workflows', treeProvider);
vscode.commands.registerCommand('n8n.refresh', () => treeProvider.refresh());
// Register webview
vscode.commands.registerCommand('n8n.openWorkflow', (workflow) => {
WorkflowWebview.createOrShow(context, workflow, proxyService);
});
}
2. Workflow Tree Provider (workflow-tree-provider.ts)โ
Provides the tree view for browsing workflows.
Key Responsibilities:
- Fetch workflows from Core library
- Organize workflows by instance
- Handle tree item interactions
- Refresh on changes
Tree Item Structure:
interface WorkflowTreeItem extends vscode.TreeItem {
type: 'instance' | 'workflow' | 'category';
instanceId?: string;
workflowId?: string;
children?: WorkflowTreeItem[];
}
3. Workflow Webview (workflow-webview.ts)โ
Renders the n8n canvas in a webview for visual editing.
Key Responsibilities:
- Create and manage webview panel
- Load n8n editor interface
- Handle messages between webview and extension
- Save workflow changes
Webview Communication:
// Extension to webview
webview.postMessage({
type: 'workflow:load',
workflow: workflowData
});
// Webview to extension
webview.onDidReceiveMessage(async (message) => {
switch (message.type) {
case 'workflow:save':
await proxyService.updateWorkflow(message.workflow);
break;
}
});
4. Proxy Service (proxy-service.ts)โ
Acts as a secure proxy between VS Code and n8n API.
Key Responsibilities:
- Forward API requests from webview to n8n
- Handle authentication and CORS
- Cache responses for performance
- Provide error handling
Proxy Implementation:
class ProxyService {
async forwardRequest(endpoint: string, method: string, data?: any) {
// Add authentication headers
// Forward to n8n API
// Return response to webview
}
}
5. Status Bar (status-bar.ts)โ
Shows sync status and quick actions in VS Code status bar.
Key Responsibilities:
- Display sync status (syncing, error, success)
- Provide quick access to common commands
- Update based on sync events
๐ Integration with Core Libraryโ
Dependency Injectionโ
The extension uses the Core library through dependency injection:
import { SyncManager, StateManager } from '@n8n-as-code/core';
class ExtensionServices {
private syncManager: SyncManager;
private stateManager: StateManager;
constructor() {
this.syncManager = new SyncManager(config);
this.stateManager = new StateManager(config);
}
}
Sync Eventsโ
The extension listens to sync events from Core:
syncManager.on('sync:start', () => {
statusBar.showSyncing();
});
syncManager.on('sync:complete', (result) => {
statusBar.showSynced();
treeProvider.refresh();
});
syncManager.on('sync:error', (error) => {
vscode.window.showErrorMessage(`Sync failed: ${error.message}`);
});
๐ ๏ธ Development Setupโ
Prerequisitesโ
- VS Code Extension Development environment
- Node.js 18+
- n8n instance for testing
Local Developmentโ
# Install dependencies
cd packages/vscode-extension
npm install
# Build extension
npm run compile
# Run in development mode
npm run watch
# Open VS Code with extension
code .
Debuggingโ
- F5: Launch extension in debug mode
- Webview DevTools: Right-click in webview โ "Inspect"
- Extension Host Logs: View output in "Debug Console"
๐ง Extension Pointsโ
Custom Commandsโ
Add new commands by registering them in extension.ts:
vscode.commands.registerCommand('n8n.customCommand', async () => {
// Implement custom functionality
});
Custom Tree Itemsโ
Extend the tree view by adding new item types:
class CustomTreeItem extends WorkflowTreeItem {
constructor(label: string) {
super(label, vscode.TreeItemCollapsibleState.None);
this.contextValue = 'customItem';
}
}
Webview Customizationโ
Extend the webview with additional functionality:
class CustomWebview extends WorkflowWebview {
protected getAdditionalHtml(): string {
return '<button id="custom-action">Custom Action</button>';
}
protected handleCustomMessage(message: any): boolean {
if (message.type === 'custom:action') {
this.handleCustomAction();
return true;
}
return false;
}
}
๐งช Testingโ
Test Structureโ
packages/vscode-extension/
โโโ tests/
โโโ unit/
โ โโโ proxy-service.test.ts
โ โโโ workflow-tree-provider.test.ts
โโโ integration/
โโโ webview.test.ts
Running Testsโ
cd packages/vscode-extension
npm test
Mocking VS Code APIโ
Use vscode-test library for testing:
import * as vscode from 'vscode-test';
const mockExtensionContext: vscode.ExtensionContext = {
subscriptions: [],
workspaceState: mockWorkspaceState,
globalState: mockGlobalState,
extensionPath: '/mock/path'
};
๐ฆ Packaging and Distributionโ
Building for Productionโ
npm run package
VS Code Marketplaceโ
- Update
package.jsonversion - Run
vsce package - Publish to Marketplace
Manual Installationโ
Package can be installed from .vsix file:
code --install-extension n8n-as-code-*.vsix
๐ Security Considerationsโ
Webview Securityโ
- Content Security Policy: Restrict resources
- Message Validation: Validate all webview messages
- Input Sanitization: Sanitize user inputs
Proxy Securityโ
- Authentication: Never expose API keys to webview
- Request Validation: Validate all proxied requests
- Rate Limiting: Prevent abuse
๐ Performance Optimizationโ
Webview Performanceโ
- Lazy Loading: Load resources on demand
- Caching: Cache workflow data
- Virtualization: Virtualize tree view for large datasets
Extension Startupโ
- Deferred Activation: Activate on command, not startup
- Background Initialization: Initialize services in background
- Resource Cleanup: Properly dispose resources
๐ Troubleshootingโ
Common Issuesโ
Webview Not Loadingโ
- Check CSP in webview HTML
- Verify resource paths are correct
- Check console errors in webview DevTools
Proxy Connection Failedโ
- Verify n8n instance is accessible
- Check API key permissions
- Verify CORS settings on n8n
Tree View Not Refreshingโ
- Check event subscriptions
- Verify Core library connection
- Check for errors in extension host
Debugging Tipsโ
- Use
Developer: Toggle Developer Toolsin VS Code - Check Output panel for extension logs
- Enable verbose logging in extension settings
๐ Related Documentationโ
- Core Package: Core library details
- Architecture Overview: Overall system architecture
- Contribution Guide: How to contribute
The VS Code extension provides a seamless visual interface for n8n workflow management, bridging the gap between code-based workflow management and visual editing.