@muloka/figma-console-mcp 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +3 -1
  2. package/dist/core/port-discovery.d.ts +9 -0
  3. package/dist/core/port-discovery.d.ts.map +1 -1
  4. package/dist/core/port-discovery.js +40 -14
  5. package/dist/core/port-discovery.js.map +1 -1
  6. package/dist/core/websocket-connector.d.ts +2 -1
  7. package/dist/core/websocket-connector.d.ts.map +1 -1
  8. package/dist/core/websocket-connector.js +17 -2
  9. package/dist/core/websocket-connector.js.map +1 -1
  10. package/dist/core/websocket-server.d.ts +8 -1
  11. package/dist/core/websocket-server.d.ts.map +1 -1
  12. package/dist/core/websocket-server.js +18 -2
  13. package/dist/core/websocket-server.js.map +1 -1
  14. package/dist/core/write-tools.d.ts +3 -1
  15. package/dist/core/write-tools.d.ts.map +1 -1
  16. package/dist/core/write-tools.js +34 -14
  17. package/dist/core/write-tools.js.map +1 -1
  18. package/dist/local.d.ts +2 -1
  19. package/dist/local.d.ts.map +1 -1
  20. package/dist/local.js +10 -14
  21. package/dist/local.js.map +1 -1
  22. package/package.json +1 -1
  23. package/dist/apps/design-system-dashboard/mcp-app.html +0 -521
  24. package/dist/apps/token-browser/mcp-app.html +0 -410
  25. package/dist/cloudflare/apps/design-system-dashboard/scoring/accessibility.js +0 -277
  26. package/dist/cloudflare/apps/design-system-dashboard/scoring/component-metadata.js +0 -357
  27. package/dist/cloudflare/apps/design-system-dashboard/scoring/consistency.js +0 -341
  28. package/dist/cloudflare/apps/design-system-dashboard/scoring/coverage.js +0 -230
  29. package/dist/cloudflare/apps/design-system-dashboard/scoring/engine.js +0 -92
  30. package/dist/cloudflare/apps/design-system-dashboard/scoring/naming-semantics.js +0 -308
  31. package/dist/cloudflare/apps/design-system-dashboard/scoring/token-architecture.js +0 -349
  32. package/dist/cloudflare/apps/design-system-dashboard/scoring/types.js +0 -40
  33. package/dist/cloudflare/apps/design-system-dashboard/server.js +0 -159
  34. package/dist/cloudflare/apps/token-browser/server.js +0 -136
  35. package/dist/cloudflare/browser-manager.js +0 -157
  36. package/dist/cloudflare/core/accessibility-tools.js +0 -361
  37. package/dist/cloudflare/core/annotation-tools.js +0 -230
  38. package/dist/cloudflare/core/cloud-websocket-connector.js +0 -419
  39. package/dist/cloudflare/core/cloud-websocket-relay.js +0 -198
  40. package/dist/cloudflare/core/comment-tools.js +0 -292
  41. package/dist/cloudflare/core/config.js +0 -153
  42. package/dist/cloudflare/core/console-monitor.js +0 -427
  43. package/dist/cloudflare/core/deep-component-tools.js +0 -128
  44. package/dist/cloudflare/core/design-code-tools.js +0 -2793
  45. package/dist/cloudflare/core/design-system-manifest.js +0 -265
  46. package/dist/cloudflare/core/design-system-tools.js +0 -882
  47. package/dist/cloudflare/core/diagnose-tool.js +0 -100
  48. package/dist/cloudflare/core/diff/changelog-formatter.js +0 -275
  49. package/dist/cloudflare/core/diff/diff-engine.js +0 -334
  50. package/dist/cloudflare/core/diff/property-compare.js +0 -36
  51. package/dist/cloudflare/core/diff/version-cache.js +0 -74
  52. package/dist/cloudflare/core/enrichment/enrichment-service.js +0 -374
  53. package/dist/cloudflare/core/enrichment/index.js +0 -7
  54. package/dist/cloudflare/core/enrichment/relationship-mapper.js +0 -351
  55. package/dist/cloudflare/core/enrichment/style-resolver.js +0 -346
  56. package/dist/cloudflare/core/figjam-tools.js +0 -547
  57. package/dist/cloudflare/core/figma-api.js +0 -509
  58. package/dist/cloudflare/core/figma-connector.js +0 -7
  59. package/dist/cloudflare/core/figma-reconstruction-spec.js +0 -402
  60. package/dist/cloudflare/core/figma-style-extractor.js +0 -311
  61. package/dist/cloudflare/core/figma-tools.js +0 -3353
  62. package/dist/cloudflare/core/identity.js +0 -96
  63. package/dist/cloudflare/core/library-tools.js +0 -580
  64. package/dist/cloudflare/core/logger.js +0 -53
  65. package/dist/cloudflare/core/port-discovery.js +0 -935
  66. package/dist/cloudflare/core/resolve-package-root.js +0 -11
  67. package/dist/cloudflare/core/slides-tools.js +0 -714
  68. package/dist/cloudflare/core/slot-tools.js +0 -334
  69. package/dist/cloudflare/core/snippet-injector.js +0 -96
  70. package/dist/cloudflare/core/tokens/alias-resolver.js +0 -205
  71. package/dist/cloudflare/core/tokens/config.js +0 -294
  72. package/dist/cloudflare/core/tokens/dialect.js +0 -232
  73. package/dist/cloudflare/core/tokens/figma-converter.js +0 -323
  74. package/dist/cloudflare/core/tokens/formatters/css-vars.js +0 -338
  75. package/dist/cloudflare/core/tokens/formatters/dtcg.js +0 -376
  76. package/dist/cloudflare/core/tokens/formatters/index.js +0 -45
  77. package/dist/cloudflare/core/tokens/formatters/json.js +0 -205
  78. package/dist/cloudflare/core/tokens/formatters/less.js +0 -4
  79. package/dist/cloudflare/core/tokens/formatters/scss.js +0 -258
  80. package/dist/cloudflare/core/tokens/formatters/stubs.js +0 -13
  81. package/dist/cloudflare/core/tokens/formatters/style-dictionary-v3.js +0 -213
  82. package/dist/cloudflare/core/tokens/formatters/tailwind-v3.js +0 -237
  83. package/dist/cloudflare/core/tokens/formatters/tailwind-v4.js +0 -335
  84. package/dist/cloudflare/core/tokens/formatters/tokens-studio.js +0 -256
  85. package/dist/cloudflare/core/tokens/formatters/ts-module.js +0 -198
  86. package/dist/cloudflare/core/tokens/index.js +0 -16
  87. package/dist/cloudflare/core/tokens/parsers/css-vars.js +0 -4
  88. package/dist/cloudflare/core/tokens/parsers/dtcg.js +0 -280
  89. package/dist/cloudflare/core/tokens/parsers/index.js +0 -138
  90. package/dist/cloudflare/core/tokens/parsers/json.js +0 -7
  91. package/dist/cloudflare/core/tokens/parsers/scss.js +0 -4
  92. package/dist/cloudflare/core/tokens/parsers/stubs.js +0 -20
  93. package/dist/cloudflare/core/tokens/parsers/style-dictionary-v3.js +0 -4
  94. package/dist/cloudflare/core/tokens/parsers/tailwind-v3.js +0 -4
  95. package/dist/cloudflare/core/tokens/parsers/tailwind-v4.js +0 -4
  96. package/dist/cloudflare/core/tokens/parsers/tokens-studio.js +0 -4
  97. package/dist/cloudflare/core/tokens/schemas.js +0 -152
  98. package/dist/cloudflare/core/tokens/transforms/color.js +0 -12
  99. package/dist/cloudflare/core/tokens/transforms/index.js +0 -29
  100. package/dist/cloudflare/core/tokens/transforms/size.js +0 -7
  101. package/dist/cloudflare/core/tokens/types.js +0 -18
  102. package/dist/cloudflare/core/tokens-tools.js +0 -1788
  103. package/dist/cloudflare/core/types/design-code.js +0 -4
  104. package/dist/cloudflare/core/types/enriched.js +0 -5
  105. package/dist/cloudflare/core/types/index.js +0 -4
  106. package/dist/cloudflare/core/variable-resolver.js +0 -85
  107. package/dist/cloudflare/core/version-tools.js +0 -1199
  108. package/dist/cloudflare/core/websocket-connector.js +0 -436
  109. package/dist/cloudflare/core/websocket-server.js +0 -1009
  110. package/dist/cloudflare/core/write-tools.js +0 -2506
  111. package/dist/cloudflare/index.js +0 -3010
@@ -1,1009 +0,0 @@
1
- /**
2
- * WebSocket Bridge Server (Multi-Client)
3
- *
4
- * Creates a WebSocket server that multiple Desktop Bridge plugin instances connect to.
5
- * Each instance represents a different Figma file and is identified by its fileKey
6
- * (sent via FILE_INFO on connection). Per-file state (selection, document changes,
7
- * console logs) is maintained independently.
8
- *
9
- * Active file tracking: The "active" file is automatically switched when the user
10
- * interacts with a file (selection/page changes) or can be set explicitly via
11
- * setActiveFile(). All backward-compatible getters return data from the active file.
12
- *
13
- * Data flow: MCP Server ←WebSocket→ ui.html ←postMessage→ code.js ←figma.*→ Figma
14
- */
15
- import { WebSocketServer as WSServer, WebSocket } from 'ws';
16
- import { EventEmitter } from 'events';
17
- import { createServer as createHttpServer } from 'http';
18
- import { readFileSync } from 'fs';
19
- import { join } from 'path';
20
- import { createChildLogger } from './logger.js';
21
- import { PACKAGE_ROOT } from './resolve-package-root.js';
22
- // Read version from package.json using the resolved package root.
23
- // PACKAGE_ROOT uses import.meta.url in ESM (production) and __dirname in CJS (Jest).
24
- let SERVER_VERSION = '0.0.0';
25
- try {
26
- SERVER_VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf-8')).version;
27
- }
28
- catch {
29
- // Non-critical — version will show as 0.0.0
30
- }
31
- /**
32
- * Extract the PLUGIN_VERSION constant from figma-desktop-bridge/code.js source.
33
- * Returns null when the constant is absent or malformed.
34
- */
35
- export function parseBundledPluginVersion(codeJsSource) {
36
- const match = codeJsSource.match(/var PLUGIN_VERSION\s*=\s*'(\d+\.\d+\.\d+)'/);
37
- return match ? match[1] : null;
38
- }
39
- // The version of the plugin files THIS package ships — i.e. what a manifest
40
- // re-import would install. This is deliberately NOT the package version:
41
- // server-only releases (deps, docs, server code) bump package.json without
42
- // touching figma-desktop-bridge/, and comparing the plugin against
43
- // SERVER_VERSION would falsely nag users to re-import an already-current
44
- // plugin (seen live: plugin 1.33.0 + server 1.33.1 → spurious update banner).
45
- let BUNDLED_PLUGIN_VERSION = SERVER_VERSION;
46
- try {
47
- const parsed = parseBundledPluginVersion(readFileSync(join(PACKAGE_ROOT, 'figma-desktop-bridge', 'code.js'), 'utf-8'));
48
- if (parsed)
49
- BUNDLED_PLUGIN_VERSION = parsed;
50
- }
51
- catch {
52
- // Non-critical — fall back to SERVER_VERSION (pre-v1.33.2 behavior)
53
- }
54
- /** Version of the plugin files bundled with this server (what a re-import installs). */
55
- export function getBundledPluginVersion() {
56
- return BUNDLED_PLUGIN_VERSION;
57
- }
58
- /**
59
- * A plugin needs re-importing when it reports no version (predates version
60
- * reporting) or a version different from the plugin files this server ships.
61
- * The server's own package version is irrelevant here.
62
- */
63
- export function computePluginUpdateAvailable(pluginVersion, bundledPluginVersion) {
64
- return !pluginVersion || pluginVersion !== bundledPluginVersion;
65
- }
66
- const logger = createChildLogger({ component: 'websocket-server' });
67
- export class FigmaWebSocketServer extends EventEmitter {
68
- constructor(options) {
69
- super();
70
- this.wss = null;
71
- this.httpServer = null;
72
- /** Named clients indexed by fileKey — each represents a connected Figma file */
73
- this.clients = new Map();
74
- /** Clients awaiting FILE_INFO identification, mapped to their pending timeout */
75
- this._pendingClients = new Map();
76
- /** The fileKey of the currently active (targeted) file */
77
- this._activeFileKey = null;
78
- /**
79
- * When true, the active file is pinned: new connections, reconnects, and
80
- * user interaction (selection/page changes) will NOT move the active target.
81
- * Lets the agent work in one file while the user works in another without
82
- * commands silently routing to the wrong file. Cleared if the locked file
83
- * disconnects.
84
- */
85
- this._targetLocked = false;
86
- this.pendingRequests = new Map();
87
- this.requestIdCounter = 0;
88
- this._isStarted = false;
89
- this._startedAt = Date.now();
90
- this.consoleBufferSize = 1000;
91
- this.documentChangeBufferSize = 200;
92
- /** Heartbeat interval for detecting dead connections via ping/pong */
93
- this._heartbeatInterval = null;
94
- this.options = options;
95
- this._startedAt = Date.now();
96
- }
97
- /**
98
- * Handle HTTP requests on the same port as WebSocket.
99
- * Serves a JSON `/health` (also at `/`) endpoint with version and connected-file
100
- * info. No plugin-UI route exists — the plugin loads its own `ui.html` from disk
101
- * via the Figma plugin runtime; the legacy `/plugin/ui` bootloader endpoint was
102
- * removed in the Phase 3 cleanup.
103
- */
104
- handleHttpRequest(req, res) {
105
- // CORS headers for Figma plugin iframe (sandboxed, origin: null)
106
- res.setHeader('Access-Control-Allow-Origin', '*');
107
- res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
108
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
109
- if (req.method === 'OPTIONS') {
110
- res.writeHead(204);
111
- res.end();
112
- return;
113
- }
114
- const url = req.url || '/';
115
- // Health/version endpoint
116
- if (url === '/health' || url === '/') {
117
- const now = Date.now();
118
- const connectedClients = Array.from(this.clients.values()).filter(c => c.ws.readyState === WebSocket.OPEN && (now - c.lastPongAt) < 90000).length;
119
- res.writeHead(200, { 'Content-Type': 'application/json' });
120
- res.end(JSON.stringify({
121
- status: 'ok',
122
- version: SERVER_VERSION,
123
- clients: this.clients.size,
124
- connectedClients,
125
- uptime: Math.floor((now - this._startedAt) / 1000),
126
- }));
127
- return;
128
- }
129
- // 404 for anything else
130
- res.writeHead(404, { 'Content-Type': 'text/plain' });
131
- res.end('Not Found');
132
- }
133
- /**
134
- * Start the HTTP + WebSocket server.
135
- * HTTP serves the plugin UI content; WebSocket handles plugin communication.
136
- */
137
- async start() {
138
- if (this._isStarted)
139
- return;
140
- return new Promise((resolve, reject) => {
141
- let rejected = false;
142
- const rejectOnce = (error) => {
143
- if (!rejected) {
144
- rejected = true;
145
- reject(error);
146
- }
147
- };
148
- try {
149
- // Create HTTP server first — handles plugin UI requests
150
- this.httpServer = createHttpServer((req, res) => this.handleHttpRequest(req, res));
151
- // Attach WebSocket server to the HTTP server (shares the same port)
152
- this.wss = new WSServer({
153
- server: this.httpServer,
154
- maxPayload: 100 * 1024 * 1024, // 100MB — screenshots and large component data can be big
155
- verifyClient: (info, callback) => {
156
- // Mitigate Cross-Site WebSocket Hijacking (CSWSH):
157
- // Reject connections from unexpected browser origins.
158
- const origin = info.origin;
159
- // Exact match only — startsWith would let e.g.
160
- // https://www.figma.com.attacker.example through.
161
- const allowed = !origin || // No origin — local process (e.g. Node.js client)
162
- origin === 'null' || // Sandboxed iframe / Figma Desktop plugin UI
163
- origin === 'https://www.figma.com' ||
164
- origin === 'https://figma.com';
165
- if (allowed) {
166
- callback(true);
167
- }
168
- else {
169
- logger.warn({ origin }, 'Rejected WebSocket connection from unauthorized origin');
170
- callback(false, 403, 'Unauthorized Origin');
171
- }
172
- },
173
- });
174
- // Error handler for startup failures (EADDRINUSE, etc.)
175
- // Must be on BOTH httpServer and wss — the WSS re-emits HTTP server errors
176
- // and throws if no listener is attached.
177
- const onStartupError = (error) => {
178
- if (!this._isStarted) {
179
- try {
180
- if (this.wss) {
181
- this.wss.close();
182
- this.wss = null;
183
- }
184
- }
185
- catch { /* ignore */ }
186
- try {
187
- if (this.httpServer) {
188
- this.httpServer.close();
189
- this.httpServer = null;
190
- }
191
- }
192
- catch { /* ignore */ }
193
- rejectOnce(error);
194
- }
195
- else {
196
- logger.error({ error }, 'HTTP/WebSocket server error');
197
- }
198
- };
199
- this.httpServer.on('error', onStartupError);
200
- this.wss.on('error', onStartupError);
201
- // Start listening on the HTTP server (which also handles WS upgrades)
202
- this.httpServer.listen(this.options.port, this.options.host || 'localhost', () => {
203
- this._isStarted = true;
204
- this.startHeartbeat();
205
- logger.info({ port: this.options.port, host: this.options.host || 'localhost' }, 'WebSocket bridge server started (with HTTP plugin UI endpoint)');
206
- resolve();
207
- });
208
- this.wss.on('connection', (ws) => {
209
- // Add to pending until FILE_INFO identifies the file
210
- const pendingTimeout = setTimeout(() => {
211
- if (this._pendingClients.has(ws)) {
212
- this._pendingClients.delete(ws);
213
- logger.warn('Pending WebSocket client timed out without sending FILE_INFO');
214
- ws.close(1000, 'File identification timeout');
215
- }
216
- }, 30000);
217
- this._pendingClients.set(ws, pendingTimeout);
218
- // Send server identity to the client for debugging and logging
219
- try {
220
- ws.send(JSON.stringify({
221
- type: 'SERVER_HELLO',
222
- data: {
223
- port: this.wss.address()?.port,
224
- pid: process.pid,
225
- serverVersion: SERVER_VERSION,
226
- startedAt: this._startedAt,
227
- },
228
- }));
229
- }
230
- catch {
231
- // Non-critical — client will still work without SERVER_HELLO
232
- }
233
- logger.info({ totalClients: this.clients.size, pendingClients: this._pendingClients.size }, 'New WebSocket connection (pending file identification)');
234
- ws.on('message', (data) => {
235
- try {
236
- let text;
237
- if (typeof data === 'string') {
238
- text = data;
239
- }
240
- else if (Buffer.isBuffer(data)) {
241
- text = data.toString();
242
- }
243
- else if (Array.isArray(data)) {
244
- text = Buffer.concat(data).toString();
245
- }
246
- else {
247
- text = Buffer.from(data).toString();
248
- }
249
- const message = JSON.parse(text);
250
- this.handleMessage(message, ws);
251
- }
252
- catch (error) {
253
- logger.error({ error }, 'Failed to parse WebSocket message');
254
- }
255
- });
256
- ws.on('close', (code, reason) => {
257
- this.handleClientDisconnect(ws, code, reason.toString());
258
- });
259
- ws.on('error', (error) => {
260
- logger.error({ error }, 'WebSocket client error');
261
- });
262
- // Track pong responses for heartbeat-based liveness detection.
263
- // Browser WebSocket clients auto-respond to pings per RFC 6455 —
264
- // no plugin-side code changes needed.
265
- ws.isAlive = true;
266
- ws.on('pong', () => {
267
- ws.isAlive = true;
268
- // Update lastPongAt on the named client if identified
269
- const found = this.findClientByWs(ws);
270
- if (found) {
271
- found.client.lastPongAt = Date.now();
272
- }
273
- });
274
- });
275
- }
276
- catch (error) {
277
- rejectOnce(error);
278
- }
279
- });
280
- }
281
- /**
282
- * Find a named client connection by its WebSocket reference
283
- */
284
- findClientByWs(ws) {
285
- for (const [fileKey, client] of this.clients) {
286
- if (client.ws === ws)
287
- return { fileKey, client };
288
- }
289
- return null;
290
- }
291
- /**
292
- * Handle incoming message from a plugin UI WebSocket connection
293
- */
294
- handleMessage(message, ws) {
295
- // Response to a command we sent
296
- if (message.id && this.pendingRequests.has(message.id)) {
297
- const pending = this.pendingRequests.get(message.id);
298
- // Verify the response arrived on the socket belonging to the file the
299
- // command targeted — a matching id alone must not let a different
300
- // client resolve (or spoof) another file's request.
301
- const sender = this.findClientByWs(ws);
302
- const socketVerified = sender
303
- ? sender.fileKey === pending.targetFileKey
304
- // Pre-identification socket (no FILE_INFO yet): only safe when it is
305
- // unambiguous — exactly one socket connected to the server at all.
306
- : (this.wss?.clients.size ?? 0) === 1;
307
- if (!socketVerified) {
308
- logger.warn({
309
- id: message.id,
310
- method: pending.method,
311
- senderFileKey: sender?.fileKey ?? null,
312
- targetFileKey: pending.targetFileKey,
313
- }, 'Ignoring response from unexpected socket (id matched, sender did not) — treating as unsolicited');
314
- // Leave the pending request in place; fall through to unsolicited handling.
315
- }
316
- else {
317
- clearTimeout(pending.timeoutId);
318
- this.pendingRequests.delete(message.id);
319
- if (message.error) {
320
- pending.reject(new Error(message.error));
321
- }
322
- else {
323
- pending.resolve(message.result);
324
- }
325
- return;
326
- }
327
- }
328
- // Unsolicited data from plugin (FILE_INFO, events, forwarded data)
329
- if (message.type) {
330
- // FILE_INFO promotes pending clients to named clients
331
- if (message.type === 'FILE_INFO' && message.data) {
332
- this.handleFileInfo(message.data, ws);
333
- }
334
- // Buffer document changes for the specific file
335
- if (message.type === 'DOCUMENT_CHANGE' && message.data) {
336
- const found = this.findClientByWs(ws);
337
- if (found) {
338
- const entry = {
339
- hasStyleChanges: message.data.hasStyleChanges,
340
- hasNodeChanges: message.data.hasNodeChanges,
341
- changedNodeIds: message.data.changedNodeIds || [],
342
- changeCount: message.data.changeCount || 0,
343
- timestamp: message.data.timestamp || Date.now(),
344
- };
345
- found.client.documentChanges.push(entry);
346
- if (found.client.documentChanges.length > this.documentChangeBufferSize) {
347
- found.client.documentChanges.shift();
348
- }
349
- found.client.lastActivity = Date.now();
350
- }
351
- this.emit('documentChange', { fileKey: found?.fileKey ?? null, ...message.data });
352
- }
353
- // v1.25.0: buffer description/annotation changes for the specific file.
354
- // These are the diff-engine blind spots that Figma REST doesn't expose;
355
- // the diff engine consults this buffer when correlating to a version
356
- // range, so changes made while the plugin was connected become visible.
357
- if (message.type === 'METADATA_CHANGE' && message.data) {
358
- const found = this.findClientByWs(ws);
359
- if (found) {
360
- const changes = Array.isArray(message.data.changes) ? message.data.changes : [];
361
- for (const c of changes) {
362
- if (!c || typeof c.node_id !== 'string' || !c.field)
363
- continue;
364
- const entry = {
365
- node_id: c.node_id,
366
- node_name: c.node_name ?? null,
367
- node_type: c.node_type ?? null,
368
- field: c.field === 'annotations' ? 'annotations' : 'description',
369
- new_value: c.new_value,
370
- timestamp: typeof c.timestamp === 'number' ? c.timestamp : Date.now(),
371
- };
372
- found.client.metadataChanges.push(entry);
373
- if (found.client.metadataChanges.length > this.documentChangeBufferSize) {
374
- found.client.metadataChanges.shift();
375
- }
376
- }
377
- found.client.lastActivity = Date.now();
378
- }
379
- this.emit('metadataChange', { fileKey: found?.fileKey ?? null, changes: message.data.changes });
380
- }
381
- // Track selection changes — user interaction makes this the active file
382
- if (message.type === 'SELECTION_CHANGE' && message.data) {
383
- const found = this.findClientByWs(ws);
384
- if (found) {
385
- found.client.selection = message.data;
386
- found.client.lastActivity = Date.now();
387
- if (!this._targetLocked)
388
- this._activeFileKey = found.fileKey;
389
- }
390
- this.emit('selectionChange', { fileKey: found?.fileKey ?? null, ...message.data });
391
- }
392
- // Track page changes — user interaction makes this the active file
393
- if (message.type === 'PAGE_CHANGE' && message.data) {
394
- const found = this.findClientByWs(ws);
395
- if (found) {
396
- found.client.fileInfo.currentPage = message.data.pageName;
397
- found.client.fileInfo.currentPageId = message.data.pageId || null;
398
- found.client.lastActivity = Date.now();
399
- if (!this._targetLocked)
400
- this._activeFileKey = found.fileKey;
401
- }
402
- this.emit('pageChange', { fileKey: found?.fileKey ?? null, ...message.data });
403
- }
404
- // Capture console logs for the specific file
405
- if (message.type === 'CONSOLE_CAPTURE' && message.data) {
406
- const found = this.findClientByWs(ws);
407
- const data = message.data;
408
- const entry = {
409
- timestamp: data.timestamp || Date.now(),
410
- level: data.level || 'log',
411
- message: typeof data.message === 'string' ? data.message.substring(0, 1000) : String(data.message),
412
- args: Array.isArray(data.args) ? data.args.slice(0, 10) : [],
413
- source: 'plugin',
414
- };
415
- if (found) {
416
- found.client.consoleLogs.push(entry);
417
- if (found.client.consoleLogs.length > this.consoleBufferSize) {
418
- found.client.consoleLogs.shift();
419
- }
420
- found.client.lastActivity = Date.now();
421
- }
422
- this.emit('consoleLog', entry);
423
- }
424
- this.emit('pluginMessage', message);
425
- return;
426
- }
427
- logger.debug({ message }, 'Unhandled WebSocket message');
428
- }
429
- /**
430
- * Handle FILE_INFO message — promotes pending clients to named clients.
431
- * This is the critical multi-client identification step: each plugin reports
432
- * its fileKey on connect, allowing the server to track multiple files.
433
- */
434
- handleFileInfo(data, ws) {
435
- const fileKey = data.fileKey || null;
436
- if (!fileKey) {
437
- logger.warn('FILE_INFO received without fileKey — client remains pending');
438
- return;
439
- }
440
- // Remove from pending clients (cancel identification timeout)
441
- const pendingTimeout = this._pendingClients.get(ws);
442
- if (pendingTimeout) {
443
- clearTimeout(pendingTimeout);
444
- this._pendingClients.delete(ws);
445
- }
446
- // Check if this ws was already registered under a different fileKey
447
- // (shouldn't happen in practice — each plugin instance is per-file)
448
- const previousEntry = this.findClientByWs(ws);
449
- if (previousEntry && previousEntry.fileKey !== fileKey) {
450
- this.clients.delete(previousEntry.fileKey);
451
- if (this._activeFileKey === previousEntry.fileKey) {
452
- this._activeFileKey = null;
453
- // The pinned plugin navigated to a different file — the old pin is
454
- // meaningless, so release it rather than silently re-pinning the new file.
455
- this._targetLocked = false;
456
- }
457
- // In-flight commands to the old file can never receive a response now —
458
- // reject them immediately instead of leaving them to hang until timeout
459
- // (mirrors the same-file replacement path below).
460
- this.rejectPendingRequestsForFile(previousEntry.fileKey, 'Plugin switched files');
461
- logger.info({ oldFileKey: previousEntry.fileKey, newFileKey: fileKey }, 'WebSocket client switched files');
462
- this.emit('fileDisconnected', {
463
- fileKey: previousEntry.fileKey,
464
- fileName: previousEntry.client.fileInfo.fileName,
465
- });
466
- }
467
- // If same fileKey already connected with a DIFFERENT ws, clean up old connection
468
- const existing = this.clients.get(fileKey);
469
- if (existing && existing.ws !== ws) {
470
- logger.info({ fileKey }, 'Replacing existing connection for same file');
471
- if (existing.gracePeriodTimer) {
472
- clearTimeout(existing.gracePeriodTimer);
473
- }
474
- // Reject any in-flight commands before replacing — the old ws close event
475
- // won't find this fileKey in the map after overwrite, so pending requests
476
- // would hang until timeout otherwise.
477
- this.rejectPendingRequestsForFile(fileKey, 'Connection replaced by same file reconnection');
478
- if (existing.ws.readyState === WebSocket.OPEN || existing.ws.readyState === WebSocket.CONNECTING) {
479
- existing.ws.close(1000, 'Replaced by same file reconnection');
480
- }
481
- }
482
- // Version handshake: the plugin reports its code.js version in FILE_INFO.
483
- // Figma caches plugin files at the app level, so a version mismatch means
484
- // the user is running stale plugin code and must re-import manifest.json.
485
- // A missing version means the plugin predates version reporting — also stale.
486
- // Compared against the BUNDLED plugin version (what a re-import would
487
- // install), NOT the server's package version — server-only releases don't
488
- // change the plugin files, so they must not trigger the re-import banner.
489
- const bundledPluginVersion = this.options.bundledPluginVersion ?? BUNDLED_PLUGIN_VERSION;
490
- const pluginVersion = data.pluginVersion || null;
491
- const pluginUpdateAvailable = computePluginUpdateAvailable(pluginVersion, bundledPluginVersion);
492
- if (pluginUpdateAvailable) {
493
- logger.warn({ fileKey, pluginVersion, bundledPluginVersion, serverVersion: SERVER_VERSION }, 'Imported plugin version differs from the plugin files bundled with this server — re-import manifest.json to update');
494
- try {
495
- ws.send(JSON.stringify({
496
- type: 'PLUGIN_UPDATE_AVAILABLE',
497
- serverVersion: SERVER_VERSION,
498
- bundledPluginVersion,
499
- pluginVersion,
500
- }));
501
- }
502
- catch {
503
- // Non-critical notification — never let it disrupt registration
504
- }
505
- }
506
- // Create client connection (preserve per-file state from previous connection of same file)
507
- this.clients.set(fileKey, {
508
- ws,
509
- fileInfo: {
510
- fileName: data.fileName,
511
- fileKey,
512
- currentPage: data.currentPage,
513
- currentPageId: data.currentPageId || null,
514
- editorType: data.editorType || 'figma',
515
- connectedAt: Date.now(),
516
- pluginVersion,
517
- pluginUpdateAvailable,
518
- },
519
- selection: existing?.selection || null,
520
- documentChanges: existing?.documentChanges || [],
521
- metadataChanges: existing?.metadataChanges || [],
522
- consoleLogs: existing?.consoleLogs || [],
523
- lastActivity: Date.now(),
524
- lastPongAt: Date.now(),
525
- gracePeriodTimer: null,
526
- });
527
- // Most recently connected file becomes active (user just opened the plugin there).
528
- // On bulk reconnect the order is non-deterministic, but the first user interaction
529
- // (SELECTION_CHANGE or PAGE_CHANGE) will correct the active file immediately.
530
- // Skip when the target is pinned so a new or reconnecting plugin can't steal it.
531
- // Invariant: a locked target always has an active file — every path that nulls
532
- // _activeFileKey also releases the lock — so there is no "locked but nothing
533
- // active" case to re-adopt here, and a crash-reconnect within the grace window
534
- // keeps its active key (the grace timer is cleared before it can fire).
535
- if (!this._targetLocked) {
536
- this._activeFileKey = fileKey;
537
- }
538
- logger.info({
539
- fileName: data.fileName,
540
- fileKey,
541
- totalClients: this.clients.size,
542
- isActive: this._activeFileKey === fileKey,
543
- }, 'File connected via WebSocket');
544
- // Emit both events for backward compat and new features
545
- this.emit('connected');
546
- this.emit('fileConnected', { fileKey, fileName: data.fileName });
547
- }
548
- /**
549
- * Handle a client WebSocket disconnecting.
550
- * Starts a grace period before removing the client to allow reconnection.
551
- */
552
- handleClientDisconnect(ws, code, reason) {
553
- // Check if it was a pending client (never identified itself)
554
- const pendingTimeout = this._pendingClients.get(ws);
555
- if (pendingTimeout) {
556
- clearTimeout(pendingTimeout);
557
- this._pendingClients.delete(ws);
558
- logger.info('Pending WebSocket client disconnected before file identification');
559
- this.emit('disconnected');
560
- return;
561
- }
562
- // Find which named client this belongs to
563
- const found = this.findClientByWs(ws);
564
- if (!found) {
565
- logger.debug('Unknown WebSocket client disconnected');
566
- this.emit('disconnected');
567
- return;
568
- }
569
- const { fileKey, client } = found;
570
- logger.info({ fileKey, fileName: client.fileInfo.fileName, code, reason }, 'File disconnected from WebSocket');
571
- // Start grace period — keep state but clean up if not reconnected
572
- client.gracePeriodTimer = setTimeout(() => {
573
- client.gracePeriodTimer = null;
574
- // Only remove if the client in the map is still the disconnected one
575
- const current = this.clients.get(fileKey);
576
- if (current && current.ws === ws) {
577
- this.clients.delete(fileKey);
578
- this.rejectPendingRequestsForFile(fileKey, 'WebSocket client disconnected');
579
- // If active file disconnected, switch to another connected file.
580
- // Release any lock — the pinned file is gone, so honoring the lock
581
- // would strand every command against a dead connection.
582
- if (this._activeFileKey === fileKey) {
583
- this._activeFileKey = null;
584
- if (this._targetLocked) {
585
- this._targetLocked = false;
586
- logger.info({ fileKey }, 'Target lock released — locked file disconnected');
587
- }
588
- for (const [fk, c] of this.clients) {
589
- if (c.ws.readyState === WebSocket.OPEN) {
590
- this._activeFileKey = fk;
591
- break;
592
- }
593
- }
594
- }
595
- this.emit('fileDisconnected', { fileKey, fileName: client.fileInfo.fileName });
596
- }
597
- }, 5000);
598
- this.emit('disconnected');
599
- }
600
- /**
601
- * Send a command to a plugin UI and wait for the response.
602
- * By default targets the active file. Pass targetFileKey to target a specific file.
603
- */
604
- sendCommand(method, params = {}, timeoutMs = 15000, targetFileKey) {
605
- return new Promise((resolve, reject) => {
606
- const fileKey = targetFileKey || this._activeFileKey;
607
- if (!fileKey) {
608
- reject(new Error('No active file connected. Make sure the Desktop Bridge plugin is open in Figma.'));
609
- return;
610
- }
611
- const client = this.clients.get(fileKey);
612
- if (!client || client.ws.readyState !== WebSocket.OPEN) {
613
- reject(new Error('No WebSocket client connected. Make sure the Desktop Bridge plugin is open in Figma.'));
614
- return;
615
- }
616
- const id = `ws_${++this.requestIdCounter}_${Date.now()}`;
617
- const timeoutId = setTimeout(() => {
618
- if (this.pendingRequests.has(id)) {
619
- this.pendingRequests.delete(id);
620
- reject(new Error(`WebSocket command ${method} timed out after ${timeoutMs}ms`));
621
- }
622
- }, timeoutMs);
623
- this.pendingRequests.set(id, {
624
- resolve,
625
- reject,
626
- method,
627
- timeoutId,
628
- createdAt: Date.now(),
629
- targetFileKey: fileKey,
630
- });
631
- const message = JSON.stringify({ id, method, params });
632
- try {
633
- client.ws.send(message);
634
- }
635
- catch (sendError) {
636
- this.pendingRequests.delete(id);
637
- clearTimeout(timeoutId);
638
- reject(new Error(`Failed to send WebSocket command ${method}: ${sendError instanceof Error ? sendError.message : String(sendError)}`));
639
- return;
640
- }
641
- client.lastActivity = Date.now();
642
- logger.debug({ id, method, fileKey }, 'Sent WebSocket command');
643
- });
644
- }
645
- /**
646
- * Start the heartbeat interval that pings all connected clients every 30s.
647
- * Detects silently dropped connections (e.g., macOS sleep, network change)
648
- * that the OS TCP keepalive would take 30-120s to catch.
649
- * Browser WebSocket clients auto-respond to pings per RFC 6455.
650
- */
651
- startHeartbeat() {
652
- this._heartbeatInterval = setInterval(() => {
653
- if (!this.wss)
654
- return;
655
- for (const ws of this.wss.clients) {
656
- if (ws.isAlive === false) {
657
- logger.info('Terminating unresponsive WebSocket client (missed heartbeat pong)');
658
- ws.terminate();
659
- continue;
660
- }
661
- ws.isAlive = false;
662
- ws.ping();
663
- }
664
- }, 30000);
665
- }
666
- /**
667
- * Check if any named client is connected (transport availability check).
668
- * Checks both socket readyState and heartbeat pong freshness to avoid
669
- * reporting phantom-connected state on silently dropped connections.
670
- */
671
- isClientConnected() {
672
- const now = Date.now();
673
- for (const [, client] of this.clients) {
674
- if (client.ws.readyState === WebSocket.OPEN && (now - client.lastPongAt) < 90000) {
675
- return true;
676
- }
677
- }
678
- return false;
679
- }
680
- /**
681
- * Whether the server has been started
682
- */
683
- isStarted() {
684
- return this._isStarted;
685
- }
686
- /**
687
- * Get the bound address info (port, host, family).
688
- * Only available after the server has started listening.
689
- * Returns the actual port — critical when using port 0 for OS-assigned ports.
690
- */
691
- address() {
692
- // Use the HTTP server's address (which is the actual listening socket)
693
- if (this.httpServer) {
694
- const addr = this.httpServer.address();
695
- if (typeof addr === 'string' || !addr)
696
- return null;
697
- return addr;
698
- }
699
- // Fallback for backward compat
700
- if (!this.wss)
701
- return null;
702
- const addr = this.wss.address();
703
- if (typeof addr === 'string')
704
- return null;
705
- return addr;
706
- }
707
- // ============================================================================
708
- // Active file getters (backward compatible — return active file's state)
709
- // ============================================================================
710
- /**
711
- * Get info about the currently active Figma file.
712
- * Returns null if no file is active or connected.
713
- */
714
- getConnectedFileInfo() {
715
- if (!this._activeFileKey)
716
- return null;
717
- const client = this.clients.get(this._activeFileKey);
718
- return client?.fileInfo || null;
719
- }
720
- /**
721
- * Get the current user selection in the active Figma file
722
- */
723
- getCurrentSelection() {
724
- if (!this._activeFileKey)
725
- return null;
726
- const client = this.clients.get(this._activeFileKey);
727
- return client?.selection || null;
728
- }
729
- /**
730
- * Get buffered document change events from the active file
731
- */
732
- getDocumentChanges(options) {
733
- if (!this._activeFileKey)
734
- return [];
735
- const client = this.clients.get(this._activeFileKey);
736
- if (!client)
737
- return [];
738
- let filtered = [...client.documentChanges];
739
- if (options?.since !== undefined) {
740
- filtered = filtered.filter((e) => e.timestamp >= options.since);
741
- }
742
- if (options?.count !== undefined && options.count > 0) {
743
- filtered = filtered.slice(-options.count);
744
- }
745
- return filtered;
746
- }
747
- /**
748
- * Clear document change buffer for the active file
749
- */
750
- clearDocumentChanges() {
751
- if (!this._activeFileKey)
752
- return 0;
753
- const client = this.clients.get(this._activeFileKey);
754
- if (!client)
755
- return 0;
756
- const count = client.documentChanges.length;
757
- client.documentChanges = [];
758
- return count;
759
- }
760
- /**
761
- * v1.25.0: Get buffered description/annotation change events for a file.
762
- *
763
- * Used by `figma_diff_versions` to surface changes that Figma REST doesn't
764
- * expose. The diff engine passes a time window (from-version → to-version
765
- * `last_modified` timestamps converted to Unix ms) and optional scoping by
766
- * node IDs.
767
- *
768
- * Defaults to the active file if `fileKey` is omitted.
769
- */
770
- getMetadataChanges(options) {
771
- const fileKey = options?.fileKey ?? this._activeFileKey;
772
- if (!fileKey)
773
- return [];
774
- const client = this.clients.get(fileKey);
775
- if (!client)
776
- return [];
777
- let filtered = [...client.metadataChanges];
778
- if (options?.since !== undefined) {
779
- filtered = filtered.filter((e) => e.timestamp >= options.since);
780
- }
781
- if (options?.until !== undefined) {
782
- filtered = filtered.filter((e) => e.timestamp <= options.until);
783
- }
784
- if (options?.nodeIds && options.nodeIds.length > 0) {
785
- const set = new Set(options.nodeIds);
786
- filtered = filtered.filter((e) => set.has(e.node_id));
787
- }
788
- return filtered;
789
- }
790
- /**
791
- * v1.25.0: Clear metadata-change buffer for the active file.
792
- */
793
- clearMetadataChanges() {
794
- if (!this._activeFileKey)
795
- return 0;
796
- const client = this.clients.get(this._activeFileKey);
797
- if (!client)
798
- return 0;
799
- const count = client.metadataChanges.length;
800
- client.metadataChanges = [];
801
- return count;
802
- }
803
- /**
804
- * Get console logs from the active file with optional filtering
805
- */
806
- getConsoleLogs(options) {
807
- if (!this._activeFileKey)
808
- return [];
809
- const client = this.clients.get(this._activeFileKey);
810
- if (!client)
811
- return [];
812
- let filtered = [...client.consoleLogs];
813
- if (options?.since !== undefined) {
814
- filtered = filtered.filter((log) => log.timestamp >= options.since);
815
- }
816
- if (options?.level && options.level !== 'all') {
817
- filtered = filtered.filter((log) => log.level === options.level);
818
- }
819
- if (options?.count !== undefined && options.count > 0) {
820
- filtered = filtered.slice(-options.count);
821
- }
822
- return filtered;
823
- }
824
- /**
825
- * Clear console log buffer for the active file
826
- */
827
- clearConsoleLogs() {
828
- if (!this._activeFileKey)
829
- return 0;
830
- const client = this.clients.get(this._activeFileKey);
831
- if (!client)
832
- return 0;
833
- const count = client.consoleLogs.length;
834
- client.consoleLogs = [];
835
- return count;
836
- }
837
- /**
838
- * Get console monitoring status for the active file
839
- */
840
- getConsoleStatus() {
841
- const client = this._activeFileKey ? this.clients.get(this._activeFileKey) : null;
842
- const logs = client?.consoleLogs || [];
843
- return {
844
- isMonitoring: !!(client && client.ws.readyState === WebSocket.OPEN),
845
- anyClientConnected: this.isClientConnected(),
846
- logCount: logs.length,
847
- bufferSize: this.consoleBufferSize,
848
- workerCount: 0,
849
- oldestTimestamp: logs[0]?.timestamp,
850
- newestTimestamp: logs[logs.length - 1]?.timestamp,
851
- };
852
- }
853
- // ============================================================================
854
- // Multi-client methods
855
- // ============================================================================
856
- /**
857
- * Get info about all connected Figma files.
858
- * Returns an array of ConnectedFileInfo for each file with an active WebSocket.
859
- */
860
- getConnectedFiles() {
861
- const files = [];
862
- for (const [fileKey, client] of this.clients) {
863
- if (client.ws.readyState === WebSocket.OPEN) {
864
- files.push({
865
- ...client.fileInfo,
866
- isActive: fileKey === this._activeFileKey,
867
- });
868
- }
869
- }
870
- return files;
871
- }
872
- /**
873
- * Get the last pong timestamp for the active client.
874
- * Returns null if no active client or no pong received yet.
875
- */
876
- getActiveClientLastPongAt() {
877
- if (!this._activeFileKey)
878
- return null;
879
- const client = this.clients.get(this._activeFileKey);
880
- return client?.lastPongAt ?? null;
881
- }
882
- /**
883
- * Set the active file by fileKey. Returns true if the file is connected.
884
- *
885
- * Pass `lock: true` to pin the target so subsequent connections, reconnects,
886
- * and user interaction won't move it. Any explicit switch resets the lock to
887
- * the value passed here (default: unlocked), so switching without `lock`
888
- * releases a prior lock.
889
- */
890
- setActiveFile(fileKey, lock = false) {
891
- const client = this.clients.get(fileKey);
892
- if (client && client.ws.readyState === WebSocket.OPEN) {
893
- this._activeFileKey = fileKey;
894
- this._targetLocked = lock;
895
- logger.info({ fileKey, fileName: client.fileInfo.fileName, locked: lock }, 'Active file switched');
896
- this.emit('activeFileChanged', { fileKey, fileName: client.fileInfo.fileName, locked: lock });
897
- return true;
898
- }
899
- return false;
900
- }
901
- /**
902
- * Get the currently active file's key
903
- */
904
- getActiveFileKey() {
905
- return this._activeFileKey;
906
- }
907
- /**
908
- * Pin the current active file so connections, reconnects, and user
909
- * interaction won't move the target. Returns false if no file is active.
910
- */
911
- lockTarget() {
912
- if (!this._activeFileKey)
913
- return false;
914
- this._targetLocked = true;
915
- logger.info({ fileKey: this._activeFileKey }, 'Target locked');
916
- return true;
917
- }
918
- /** Release the target lock; the active file resumes following user activity. */
919
- unlockTarget() {
920
- this._targetLocked = false;
921
- logger.info({ fileKey: this._activeFileKey }, 'Target unlocked');
922
- }
923
- /** Whether the active file is currently pinned. */
924
- isTargetLocked() {
925
- return this._targetLocked;
926
- }
927
- /**
928
- * Get the editor type of the currently active file.
929
- * Returns 'figma' if no file is connected or editorType wasn't reported.
930
- */
931
- getEditorType() {
932
- if (!this._activeFileKey)
933
- return 'figma';
934
- const client = this.clients.get(this._activeFileKey);
935
- return client?.fileInfo?.editorType || 'figma';
936
- }
937
- // ============================================================================
938
- // Cleanup
939
- // ============================================================================
940
- /**
941
- * Reject pending requests that were sent to a specific file
942
- */
943
- rejectPendingRequestsForFile(fileKey, reason) {
944
- for (const [id, pending] of this.pendingRequests) {
945
- if (pending.targetFileKey === fileKey) {
946
- clearTimeout(pending.timeoutId);
947
- pending.reject(new Error(reason));
948
- this.pendingRequests.delete(id);
949
- }
950
- }
951
- }
952
- /**
953
- * Reject all pending requests (used during shutdown)
954
- */
955
- rejectPendingRequests(reason) {
956
- for (const [, pending] of this.pendingRequests) {
957
- clearTimeout(pending.timeoutId);
958
- pending.reject(new Error(reason));
959
- }
960
- this.pendingRequests.clear();
961
- }
962
- /**
963
- * Stop the server and clean up all connections
964
- */
965
- async stop() {
966
- // Clear heartbeat interval
967
- if (this._heartbeatInterval) {
968
- clearInterval(this._heartbeatInterval);
969
- this._heartbeatInterval = null;
970
- }
971
- // Clear all per-client grace period timers
972
- for (const [, client] of this.clients) {
973
- if (client.gracePeriodTimer) {
974
- clearTimeout(client.gracePeriodTimer);
975
- client.gracePeriodTimer = null;
976
- }
977
- }
978
- // Clear pending client identification timeouts
979
- for (const [, timeout] of this._pendingClients) {
980
- clearTimeout(timeout);
981
- }
982
- this._pendingClients.clear();
983
- this.rejectPendingRequests('WebSocket server shutting down');
984
- // Terminate all connected clients so wss.close() resolves promptly
985
- if (this.wss) {
986
- for (const ws of this.wss.clients) {
987
- ws.terminate();
988
- }
989
- }
990
- this.clients.clear();
991
- this._activeFileKey = null;
992
- this._targetLocked = false;
993
- // Close WS server first (handles WebSocket connections)
994
- if (this.wss) {
995
- await new Promise((resolve) => {
996
- this.wss.close(() => resolve());
997
- });
998
- }
999
- // Then close HTTP server (releases the port)
1000
- if (this.httpServer) {
1001
- await new Promise((resolve) => {
1002
- this.httpServer.close(() => resolve());
1003
- });
1004
- this.httpServer = null;
1005
- }
1006
- this._isStarted = false;
1007
- logger.info('WebSocket bridge server stopped');
1008
- }
1009
- }