@player-devtools/client-flipper 0.15.2 → 0.16.1-next.0

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.
@@ -112,6 +112,13 @@ var FlipperRefcount = class {
112
112
  return null;
113
113
  }
114
114
  }
115
+ /**
116
+ * Read the current refcount state without mutating it. Still goes through
117
+ * `withLock` so a concurrent acquire/release can't be observed mid-write.
118
+ */
119
+ peek() {
120
+ return this.withLock(() => this.read());
121
+ }
115
122
  write(state) {
116
123
  fs.writeFileSync(this.file, JSON.stringify(state));
117
124
  }
@@ -183,6 +190,11 @@ var FlipperServerTransport = class {
183
190
  * "all connected clients" convenience.
184
191
  */
185
192
  this.connectedClientIds = /* @__PURE__ */ new Set();
193
+ /**
194
+ * Whether this instance started the shared daemon (vs. attaching to one
195
+ * another instance started). Only an owner may consider restarting it.
196
+ */
197
+ this.owns = false;
186
198
  this.sendMessage = async (message) => {
187
199
  if (!this.server) return;
188
200
  const payload = {
@@ -213,11 +225,21 @@ var FlipperServerTransport = class {
213
225
  this.removeListener = (callback) => {
214
226
  this.listeners.delete(callback);
215
227
  };
228
+ /**
229
+ * In-flight `close()` promise, if one is currently running on this
230
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
231
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
232
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
233
+ */
234
+ this.closing = null;
235
+ this.host = this.options.host ?? "localhost";
236
+ this.port = this.options.port ?? 52342;
216
237
  }
217
238
  async connect() {
218
- const host = this.options.host ?? "localhost";
219
- const port = this.options.port ?? 52342;
239
+ const host = this.host;
240
+ const port = this.port;
220
241
  const { shouldStart, commit } = this.refcount.acquire();
242
+ this.owns = shouldStart;
221
243
  if (shouldStart) {
222
244
  log("[FlipperServerTransport] Starting flipper-server...");
223
245
  const serverScript = require.resolve("flipper-server/server.js");
@@ -236,7 +258,12 @@ var FlipperServerTransport = class {
236
258
  );
237
259
  });
238
260
  child.unref();
239
- await waitForPort(host, port);
261
+ try {
262
+ await waitForPort(host, port);
263
+ } catch (err) {
264
+ await this.killAndWait(child.pid);
265
+ throw err;
266
+ }
240
267
  commit(child.pid);
241
268
  log("[FlipperServerTransport] flipper-server ready.");
242
269
  } else {
@@ -403,6 +430,13 @@ var FlipperServerTransport = class {
403
430
  );
404
431
  }
405
432
  async close() {
433
+ if (this.closing) return this.closing;
434
+ this.closing = this.doClose().finally(() => {
435
+ this.closing = null;
436
+ });
437
+ return this.closing;
438
+ }
439
+ async doClose() {
406
440
  this.listeners.clear();
407
441
  this.activeClientIds.clear();
408
442
  this.connectedClientIds.clear();
@@ -410,11 +444,119 @@ var FlipperServerTransport = class {
410
444
  this.server = null;
411
445
  const pidToKill = this.refcount.release();
412
446
  if (pidToKill !== null) {
447
+ await this.killAndWait(pidToKill);
448
+ }
449
+ }
450
+ /**
451
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
452
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
453
+ * the port being free once `close()` returns instead of racing a new child
454
+ * for it.
455
+ */
456
+ killAndWait(pid, timeoutMs = 5e3) {
457
+ return new Promise((resolve) => {
413
458
  try {
414
- process.kill(pidToKill);
415
- log("[FlipperServerTransport] Shut down flipper-server.");
459
+ process.kill(pid);
416
460
  } catch {
461
+ resolve();
462
+ return;
417
463
  }
464
+ const deadline = Date.now() + timeoutMs;
465
+ const poll = () => {
466
+ if (!this.isPidAlive(pid)) {
467
+ log("[FlipperServerTransport] Shut down flipper-server.");
468
+ resolve();
469
+ return;
470
+ }
471
+ if (Date.now() >= deadline) {
472
+ log(
473
+ "[FlipperServerTransport] Timed out waiting for flipper-server to exit."
474
+ );
475
+ resolve();
476
+ return;
477
+ }
478
+ setTimeout(poll, 100);
479
+ };
480
+ poll();
481
+ });
482
+ }
483
+ isPidAlive(pid) {
484
+ try {
485
+ process.kill(pid, 0);
486
+ return true;
487
+ } catch {
488
+ return false;
489
+ }
490
+ }
491
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
492
+ getDiagnostics() {
493
+ const state = this.refcount.peek();
494
+ return {
495
+ connected: this.server !== null,
496
+ host: this.host,
497
+ port: this.port,
498
+ owns: this.owns,
499
+ refs: state?.refs ?? null,
500
+ activeClientIds: [...this.activeClientIds],
501
+ connectedClientIds: [...this.connectedClientIds]
502
+ };
503
+ }
504
+ /**
505
+ * Restart the shared daemon. Only ever acts when this instance both owns
506
+ * the daemon (started it) and is its sole remaining consumer — otherwise
507
+ * this soft-errors without touching the daemon, since killing it out from
508
+ * under other attached instances would break their connections.
509
+ */
510
+ async restart() {
511
+ if (!this.owns) {
512
+ return {
513
+ ok: false,
514
+ reason: "this instance does not own the flipper-server daemon"
515
+ };
516
+ }
517
+ const state = this.refcount.peek();
518
+ if (state?.refs !== 1) {
519
+ return {
520
+ ok: false,
521
+ reason: "other consumers are attached to this daemon"
522
+ };
523
+ }
524
+ const recheck = this.refcount.peek();
525
+ if (recheck?.refs !== 1) {
526
+ return {
527
+ ok: false,
528
+ reason: "other consumers attached to this daemon just before restart"
529
+ };
530
+ }
531
+ try {
532
+ await this.close();
533
+ await this.connect();
534
+ } catch (err) {
535
+ this.owns = false;
536
+ return {
537
+ ok: false,
538
+ reason: err instanceof Error ? err.message : String(err)
539
+ };
540
+ }
541
+ return { ok: true, host: this.host, port: this.port };
542
+ }
543
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
544
+ async getPluginInstallStatus() {
545
+ if (!this.server) return { installed: false, reason: "not connected" };
546
+ try {
547
+ const plugins = await this.server.exec(
548
+ "plugins-get-installed-plugins"
549
+ );
550
+ const plugin = plugins.find(
551
+ (candidate) => candidate.id === PLUGIN_API || candidate.name === PLUGIN_API
552
+ );
553
+ if (!plugin) return { installed: false };
554
+ return plugin.version ? { installed: true, version: plugin.version } : { installed: true };
555
+ } catch (err) {
556
+ return {
557
+ installed: false,
558
+ reason: err instanceof Error ? err.message : String(err)
559
+ };
418
560
  }
419
561
  }
420
562
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/index.ts","../../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/transport.ts"],"sourcesContent":["export { FlipperServerTransport } from \"./transport\";\n","import {\n createFlipperServer,\n FlipperServerState,\n type FlipperServer,\n} from \"flipper-server-client\";\nimport type { InstalledPluginDetails } from \"flipper-common\";\nimport { spawn } from \"child_process\";\nimport open from \"open\";\nimport * as net from \"net\";\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { WebSocket as WsWebSocket } from \"ws\";\nimport type {\n CommunicationLayerMethods,\n ExtensionSupportedEvents,\n MessengerEvent,\n TransactionMetadata,\n Transport,\n} from \"@player-devtools/types\";\n\n// polyfill WebSocket for Node < 22\nif (typeof (globalThis as { WebSocket?: unknown }).WebSocket === \"undefined\") {\n (globalThis as { WebSocket?: unknown }).WebSocket =\n WsWebSocket as unknown as typeof WebSocket;\n}\n\ntype MessageCallback = (\n message: TransactionMetadata & MessengerEvent<ExtensionSupportedEvents>,\n) => void;\n\nconst PLUGIN_API = \"player-ui-devtools\";\nconst PLUGIN_NPM_NAME = \"flipper-plugin-player-ui-devtools\";\n\n/**\n * All diagnostics go to stderr.\n *\n * This transport runs inside the MCP server process, where stdout is the\n * JSON-RPC channel — every byte written there must be a newline-delimited\n * JSON-RPC message. `console.log` and `console.debug` both write to stdout in\n * Node, so they would corrupt the protocol stream.\n */\nconst log = (...args: Array<unknown>): void => {\n console.error(...args);\n};\n\n/** Shape of a Flipper `client-message` payload after JSON.parse */\ntype FlipperExecuteMessage = {\n method: \"execute\";\n params: {\n api: string;\n method: string;\n params?: unknown;\n };\n};\n\n/** Wire shape of the `init`/`deinit` plugin-activation handshake (`js-flipper`'s `FlipperClient.onMessageReceived`) */\ntype FlipperPluginLifecycleMessage = {\n method: \"init\" | \"deinit\";\n params: { plugin: string };\n};\n\n/**\n * Flipper headless transport\n *\n * Connects to a running `flipper-server` process and routes messages for the\n * \"flipper-plugin-player-ui-devtools\" plugin through to the Messenger layer.\n */\n/** Wait until a TCP port is accepting connections, polling every 500ms */\nfunction waitForPort(\n host: string,\n port: number,\n timeoutMs = 30_000,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const deadline = Date.now() + timeoutMs;\n const attempt = () => {\n const socket = net.connect(port, host);\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve();\n });\n socket.once(\"error\", () => {\n socket.destroy();\n if (Date.now() >= deadline) {\n reject(new Error(`Timed out waiting for ${host}:${port}`));\n } else {\n setTimeout(attempt, 500);\n }\n });\n };\n attempt();\n });\n}\n\n/**\n * Cross-process refcount for the shared `flipper-server` daemon.\n *\n * Many MCP server processes (one per project/user registration) attach to a\n * single `flipper-server` on a fixed port. No in-process variable can\n * coordinate their lifecycles, so we track liveness in a small file guarded by\n * an atomic lock directory:\n *\n * - The first attach starts the daemon and records its PID with `refs: 1`.\n * - Each subsequent attach increments `refs`.\n * - Each detach decrements `refs`; the last one out shuts the daemon down.\n *\n * The lock directory (`mkdir` is atomic across processes) serializes the\n * read-modify-write so concurrently-starting instances don't race.\n */\ntype RefcountFile = { pid: number; refs: number };\n\nclass FlipperRefcount {\n private readonly dir = path.join(os.tmpdir(), \"player-devtools-mcp\");\n private readonly file = path.join(this.dir, \"flipper-server.refcount\");\n private readonly lock = path.join(this.dir, \"flipper-server.lock\");\n\n /** Acquire the cross-process lock, run `fn`, then release — even on throw. */\n private withLock<T>(fn: () => T): T {\n fs.mkdirSync(this.dir, { recursive: true });\n const deadline = Date.now() + 5_000;\n // Spin on an atomic mkdir until we own the lock or time out.\n for (;;) {\n try {\n fs.mkdirSync(this.lock);\n break;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n if (Date.now() >= deadline) {\n // Stale lock from a crashed process — reclaim it.\n try {\n fs.rmdirSync(this.lock);\n } catch {\n /* another instance won the reclaim; retry */\n }\n }\n }\n }\n try {\n return fn();\n } finally {\n try {\n fs.rmdirSync(this.lock);\n } catch {\n /* already gone */\n }\n }\n }\n\n private read(): RefcountFile | null {\n try {\n return JSON.parse(fs.readFileSync(this.file, \"utf8\")) as RefcountFile;\n } catch {\n return null;\n }\n }\n\n private write(state: RefcountFile): void {\n fs.writeFileSync(this.file, JSON.stringify(state));\n }\n\n private clear(): void {\n try {\n fs.unlinkSync(this.file);\n } catch {\n /* already gone */\n }\n }\n\n /** Is the recorded daemon PID still alive? */\n private isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Register interest in the daemon. Returns whether this caller is the one\n * responsible for starting it (because no live daemon was recorded).\n * `recordPid` is called with the started PID once the daemon is up.\n */\n acquire(): { shouldStart: boolean; commit: (pid: number) => void } {\n return this.withLock(() => {\n const state = this.read();\n if (state && this.isAlive(state.pid)) {\n this.write({ pid: state.pid, refs: state.refs + 1 });\n return { shouldStart: false, commit: () => {} };\n }\n // No live daemon — this caller will start one and record its PID.\n return {\n shouldStart: true,\n commit: (pid: number) =>\n this.withLock(() => this.write({ pid, refs: 1 })),\n };\n });\n }\n\n /**\n * Drop this caller's interest. Returns the PID to kill if this was the last\n * reference, otherwise null.\n */\n release(): number | null {\n return this.withLock(() => {\n const state = this.read();\n if (!state) return null;\n if (state.refs <= 1) {\n this.clear();\n return state.pid;\n }\n this.write({ pid: state.pid, refs: state.refs - 1 });\n return null;\n });\n }\n}\n\nexport class FlipperServerTransport implements Transport {\n private server: FlipperServer | null = null;\n private refcount = new FlipperRefcount();\n private listeners = new Set<MessageCallback>();\n\n /**\n * Client IDs that have sent at least one message through the devtools\n * plugin — these are the clients we send outbound messages to.\n */\n private activeClientIds = new Set<string>();\n\n /**\n * Client IDs currently connected to flipper-server, regardless of whether\n * the devtools plugin has been activated for them. Used by `enablePlugin`'s\n * \"all connected clients\" convenience.\n */\n private connectedClientIds = new Set<string>();\n\n constructor(\n private options: {\n /** Flipper server host; defaults to \"localhost\" */\n host?: string;\n /** Flipper server WebSocket port; defaults to 52342 */\n port?: number;\n /**\n * Whether to open a browser/PWA UI once the server is up. Defaults to\n * `false` — an agent driving this transport has no use for a browser\n * tab, unlike a human running `flipper-server` directly.\n */\n open?: boolean;\n /**\n * URL to open in the browser when `open` is true. Defaults to\n * `http://localhost:{port}`. `flipper-server` itself always binds to\n * localhost regardless of this value — this only controls what URL\n * gets opened, so a custom host (e.g. a branded domain) must already\n * resolve to this machine (e.g. via `/etc/hosts`) for it to work.\n */\n url?: string;\n /**\n * Activate the devtools plugin automatically for every client that\n * connects, instead of requiring an explicit `enablePlugin()` call per\n * client. Off by default so a caller can choose when/whether to\n * activate a given device; turn this on for a fully hands-off session\n * where every connecting device should be watched immediately.\n */\n autoEnablePlugin?: boolean;\n } = {},\n ) {}\n\n async connect(): Promise<void> {\n const host = this.options.host ?? \"localhost\";\n const port = this.options.port ?? 52342;\n\n // Register interest in the shared daemon. The first instance to do so is\n // told to start it; the rest just attach. The daemon outlives any single\n // MCP process and is only torn down when the last instance detaches.\n const { shouldStart, commit } = this.refcount.acquire();\n\n if (shouldStart) {\n log(\"[FlipperServerTransport] Starting flipper-server...\");\n const serverScript = require.resolve(\"flipper-server/server.js\");\n // We always pass --open=false and drive any browser-open ourselves\n // (below) so we control both whether it happens and what URL is used —\n // flipper-server's own --open only ever opens http://localhost:{port}.\n\n // Detached + unref'd: the daemon must survive this process exiting so\n // other instances keep their connections. We never kill it directly —\n // shutdown is driven by the refcount in close().\n //\n // The daemon must never inherit our fd 1: it outlives this process and\n // would write into a later session's JSON-RPC stream. Its stderr stays\n // inherited so daemon diagnostics remain visible.\n const child = spawn(\n process.execPath,\n [serverScript, \"--open=false\", `--port=${port}`],\n {\n stdio: [\"ignore\", \"ignore\", \"inherit\"],\n detached: true,\n },\n );\n child.on(\"error\", (err: Error) => {\n console.error(\n \"[FlipperServerTransport] flipper-server process error:\",\n err,\n );\n });\n child.unref();\n await waitForPort(host, port);\n commit(child.pid!);\n log(\"[FlipperServerTransport] flipper-server ready.\");\n } else {\n // Daemon already running (started by another instance) — wait for it to\n // accept connections in case it's still coming up, then attach.\n await waitForPort(host, port);\n log(\"[FlipperServerTransport] Attached to flipper-server.\");\n }\n\n if (this.options.open) {\n const url = this.options.url ?? `http://localhost:${port}`;\n log(`[FlipperServerTransport] Opening ${url}`);\n try {\n await open(url);\n } catch (err) {\n console.warn(\"[FlipperServerTransport] Failed to open UI:\", err);\n }\n }\n\n // Read the auth token the flipper-server wrote during startup\n const { getAuthToken } =\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(\"flipper-server/lib/app-connectivity/certificate-exchange/certificate-utils\") as {\n getAuthToken: () => Promise<string>;\n };\n\n let cachedToken: string | null = null;\n try {\n cachedToken = await getAuthToken();\n } catch (err) {\n console.warn(\"[FlipperServerTransport] Could not read auth token:\", err);\n }\n\n this.server = await createFlipperServer(\n host,\n port,\n () => cachedToken,\n (state) => {\n if (state === FlipperServerState.DISCONNECTED) {\n console.warn(\"[FlipperServerTransport] Disconnected from server\");\n }\n },\n );\n\n await this.server.connect();\n\n // Track client connects/disconnects\n this.server.on(\"client-connected\", (info) => {\n log(\"[FlipperServerTransport] client-connected:\", JSON.stringify(info));\n this.connectedClientIds.add(info.id);\n if (this.options.autoEnablePlugin) {\n this.enablePlugin(info.id).catch((err) => {\n console.warn(\n `[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,\n err,\n );\n });\n }\n });\n this.server.on(\"client-disconnected\", ({ id }) => {\n log(\"[FlipperServerTransport] client-disconnected:\", id);\n this.activeClientIds.delete(id);\n this.connectedClientIds.delete(id);\n });\n\n // Route inbound device messages to our Messenger listeners\n this.server.on(\"client-message\", ({ id, message }) => {\n let parsed: FlipperExecuteMessage;\n try {\n parsed = JSON.parse(message) as FlipperExecuteMessage;\n } catch {\n return;\n }\n\n log(\n `[FlipperServerTransport] client-message from ${id}: method=${parsed.method} api=${(parsed.params as { api?: string })?.api} pluginMethod=${(parsed.params as { method?: string })?.method}`,\n );\n\n if (\n parsed.method !== \"execute\" ||\n parsed.params?.api !== PLUGIN_API ||\n parsed.params?.method !== \"message::plugin\"\n ) {\n return;\n }\n\n // This client is talking through the devtools plugin — remember it\n this.activeClientIds.add(id);\n\n const payload = parsed.params.params as TransactionMetadata &\n MessengerEvent<ExtensionSupportedEvents>;\n\n for (const listener of this.listeners) {\n listener(payload);\n }\n });\n }\n\n sendMessage: CommunicationLayerMethods[\"sendMessage\"] = async (message) => {\n if (!this.server) return;\n\n const payload: FlipperExecuteMessage = {\n method: \"execute\",\n params: {\n api: PLUGIN_API,\n method: \"message::flipper\",\n params: message,\n },\n };\n\n await Promise.all(\n [...this.activeClientIds].map((clientId) =>\n this.server!.exec(\"client-request-response\", clientId, payload).catch(\n (err) => {\n console.warn(\n `[FlipperServerTransport] Failed to send to client ${clientId}:`,\n err,\n );\n // Remove dead client so we stop trying\n this.activeClientIds.delete(clientId);\n },\n ),\n ),\n );\n };\n\n /**\n * Ensures `flipper-plugin-player-ui-devtools` is installed on the attached\n * flipper-server, installing the published npm package if it's missing.\n *\n * This is Flipper's own documented plugin-install RPC (the same\n * `exec(...)` commands the desktop UI's \"Install Plugin\" button calls) —\n * not a filesystem workaround. It's opt-in: callers that manage plugin\n * installation themselves (or run against a flipper-server that already\n * has it) can skip calling this.\n */\n async ensurePluginInstalled(): Promise<InstalledPluginDetails> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const installed = await this.server.exec(\"plugins-get-installed-plugins\");\n const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);\n if (existing) {\n log(\n `[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`,\n );\n return existing;\n }\n\n log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);\n const details = await this.server.exec(\n \"plugins-install-from-npm\",\n PLUGIN_NPM_NAME,\n );\n log(\n `[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`,\n );\n return details;\n }\n\n /**\n * Activates the devtools plugin for a connected client by sending the\n * `init` handshake `js-flipper`'s device SDK requires before it will open\n * a live plugin connection (`onConnect`/`FlipperConnection`) and start\n * relaying `client-message`s for our api. Nothing in flipper-server itself\n * sends this automatically for a non-background plugin like ours unless a\n * full Flipper desktop app is attached and its tab is selected — this\n * method lets a caller trigger the same handshake directly, without\n * needing a desktop UI at all.\n *\n * Calls `ensurePluginInstalled()` first, every time — the plugin can be\n * installed/removed on the attached flipper-server independently of this\n * transport (e.g. a human using the desktop UI concurrently), so there's\n * no snapshot of \"already installed\" we can trust across calls.\n *\n * Pass a specific `clientId`, or omit it to enable for every client\n * currently connected to flipper-server that we don't already believe is\n * active (see `activeClientIds`) — `init` is otherwise harmless to repeat,\n * but there's no reason to re-send it to a client already talking to us.\n */\n async enablePlugin(clientId?: string): Promise<void> {\n await this.ensurePluginInstalled();\n const targets = clientId\n ? [clientId]\n : [...this.connectedClientIds].filter(\n (id) => !this.activeClientIds.has(id),\n );\n await this.sendLifecycleMessage(\"init\", targets);\n }\n\n /**\n * Symmetric counterpart to `enablePlugin` — releases the plugin connection\n * without disconnecting the client from flipper-server.\n *\n * Pass a specific `clientId`, or omit it to disable for every client we\n * currently believe is active (see `activeClientIds`) — there's nothing to\n * release for a client that was never activated.\n */\n async disablePlugin(clientId?: string): Promise<void> {\n const targets = clientId ? [clientId] : [...this.activeClientIds];\n await this.sendLifecycleMessage(\"deinit\", targets);\n }\n\n private async sendLifecycleMessage(\n method: \"init\" | \"deinit\",\n targets: Array<string>,\n ): Promise<void> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const payload: FlipperPluginLifecycleMessage = {\n method,\n params: { plugin: PLUGIN_API },\n };\n\n await Promise.all(\n targets.map((id) =>\n this.server!.exec(\"client-request-response\", id, payload).catch(\n (err) => {\n console.warn(\n `[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,\n err,\n );\n },\n ),\n ),\n );\n }\n\n addListener: CommunicationLayerMethods[\"addListener\"] = (callback) => {\n this.listeners.add(callback);\n };\n\n removeListener: CommunicationLayerMethods[\"removeListener\"] = (callback) => {\n this.listeners.delete(callback);\n };\n\n async close(): Promise<void> {\n this.listeners.clear();\n this.activeClientIds.clear();\n this.connectedClientIds.clear();\n this.server?.close();\n this.server = null;\n\n // Drop our reference to the shared daemon. If we were the last user, the\n // refcount hands back its PID and we shut it down; otherwise it keeps\n // running for the remaining instances.\n const pidToKill = this.refcount.release();\n if (pidToKill !== null) {\n try {\n process.kill(pidToKill);\n log(\"[FlipperServerTransport] Shut down flipper-server.\");\n } catch {\n /* already gone */\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mCAIO;AAEP,2BAAsB;AACtB,kBAAiB;AACjB,UAAqB;AACrB,SAAoB;AACpB,SAAoB;AACpB,WAAsB;AACtB,gBAAyC;AAUzC,IAAI,OAAQ,WAAuC,cAAc,aAAa;AAC5E,EAAC,WAAuC,YACtC,UAAAA;AACJ;AAMA,IAAM,aAAa;AACnB,IAAM,kBAAkB;AAUxB,IAAM,MAAM,IAAI,SAA+B;AAC7C,UAAQ,MAAM,GAAG,IAAI;AACvB;AAyBA,SAAS,YACP,MACA,MACA,YAAY,KACG;AACf,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,UAAM,UAAU,MAAM;AACpB,YAAM,SAAa,YAAQ,MAAM,IAAI;AACrC,aAAO,KAAK,WAAW,MAAM;AAC3B,eAAO,QAAQ;AACf,gBAAQ;AAAA,MACV,CAAC;AACD,aAAO,KAAK,SAAS,MAAM;AACzB,eAAO,QAAQ;AACf,YAAI,KAAK,IAAI,KAAK,UAAU;AAC1B,iBAAO,IAAI,MAAM,yBAAyB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,QAC3D,O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tools/client/flipper/src/index.ts","../../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/transport.ts"],"sourcesContent":["export { FlipperServerTransport } from \"./transport\";\n","import {\n createFlipperServer,\n FlipperServerState,\n type FlipperServer,\n} from \"flipper-server-client\";\nimport type { InstalledPluginDetails } from \"flipper-common\";\nimport { spawn } from \"child_process\";\nimport open from \"open\";\nimport * as net from \"net\";\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { WebSocket as WsWebSocket } from \"ws\";\nimport type {\n CommunicationLayerMethods,\n ExtensionSupportedEvents,\n MessengerEvent,\n TransactionMetadata,\n Transport,\n} from \"@player-devtools/types\";\n\n// polyfill WebSocket for Node < 22\nif (typeof (globalThis as { WebSocket?: unknown }).WebSocket === \"undefined\") {\n (globalThis as { WebSocket?: unknown }).WebSocket =\n WsWebSocket as unknown as typeof WebSocket;\n}\n\ntype MessageCallback = (\n message: TransactionMetadata & MessengerEvent<ExtensionSupportedEvents>,\n) => void;\n\nconst PLUGIN_API = \"player-ui-devtools\";\nconst PLUGIN_NPM_NAME = \"flipper-plugin-player-ui-devtools\";\n\n/**\n * All diagnostics go to stderr.\n *\n * This transport runs inside the MCP server process, where stdout is the\n * JSON-RPC channel — every byte written there must be a newline-delimited\n * JSON-RPC message. `console.log` and `console.debug` both write to stdout in\n * Node, so they would corrupt the protocol stream.\n */\nconst log = (...args: Array<unknown>): void => {\n console.error(...args);\n};\n\n/** Shape of a Flipper `client-message` payload after JSON.parse */\ntype FlipperExecuteMessage = {\n method: \"execute\";\n params: {\n api: string;\n method: string;\n params?: unknown;\n };\n};\n\n/** Wire shape of the `init`/`deinit` plugin-activation handshake (`js-flipper`'s `FlipperClient.onMessageReceived`) */\ntype FlipperPluginLifecycleMessage = {\n method: \"init\" | \"deinit\";\n params: { plugin: string };\n};\n\n/**\n * Flipper headless transport\n *\n * Connects to a running `flipper-server` process and routes messages for the\n * \"flipper-plugin-player-ui-devtools\" plugin through to the Messenger layer.\n */\n/** Wait until a TCP port is accepting connections, polling every 500ms */\nfunction waitForPort(\n host: string,\n port: number,\n timeoutMs = 30_000,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const deadline = Date.now() + timeoutMs;\n const attempt = () => {\n const socket = net.connect(port, host);\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve();\n });\n socket.once(\"error\", () => {\n socket.destroy();\n if (Date.now() >= deadline) {\n reject(new Error(`Timed out waiting for ${host}:${port}`));\n } else {\n setTimeout(attempt, 500);\n }\n });\n };\n attempt();\n });\n}\n\n/**\n * Cross-process refcount for the shared `flipper-server` daemon.\n *\n * Many MCP server processes (one per project/user registration) attach to a\n * single `flipper-server` on a fixed port. No in-process variable can\n * coordinate their lifecycles, so we track liveness in a small file guarded by\n * an atomic lock directory:\n *\n * - The first attach starts the daemon and records its PID with `refs: 1`.\n * - Each subsequent attach increments `refs`.\n * - Each detach decrements `refs`; the last one out shuts the daemon down.\n *\n * The lock directory (`mkdir` is atomic across processes) serializes the\n * read-modify-write so concurrently-starting instances don't race.\n */\ntype RefcountFile = { pid: number; refs: number };\n\nclass FlipperRefcount {\n private readonly dir = path.join(os.tmpdir(), \"player-devtools-mcp\");\n private readonly file = path.join(this.dir, \"flipper-server.refcount\");\n private readonly lock = path.join(this.dir, \"flipper-server.lock\");\n\n /** Acquire the cross-process lock, run `fn`, then release — even on throw. */\n private withLock<T>(fn: () => T): T {\n fs.mkdirSync(this.dir, { recursive: true });\n const deadline = Date.now() + 5_000;\n // Spin on an atomic mkdir until we own the lock or time out.\n for (;;) {\n try {\n fs.mkdirSync(this.lock);\n break;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n if (Date.now() >= deadline) {\n // Stale lock from a crashed process — reclaim it.\n try {\n fs.rmdirSync(this.lock);\n } catch {\n /* another instance won the reclaim; retry */\n }\n }\n }\n }\n try {\n return fn();\n } finally {\n try {\n fs.rmdirSync(this.lock);\n } catch {\n /* already gone */\n }\n }\n }\n\n private read(): RefcountFile | null {\n try {\n return JSON.parse(fs.readFileSync(this.file, \"utf8\")) as RefcountFile;\n } catch {\n return null;\n }\n }\n\n /**\n * Read the current refcount state without mutating it. Still goes through\n * `withLock` so a concurrent acquire/release can't be observed mid-write.\n */\n peek(): RefcountFile | null {\n return this.withLock(() => this.read());\n }\n\n private write(state: RefcountFile): void {\n fs.writeFileSync(this.file, JSON.stringify(state));\n }\n\n private clear(): void {\n try {\n fs.unlinkSync(this.file);\n } catch {\n /* already gone */\n }\n }\n\n /** Is the recorded daemon PID still alive? */\n private isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Register interest in the daemon. Returns whether this caller is the one\n * responsible for starting it (because no live daemon was recorded).\n * `recordPid` is called with the started PID once the daemon is up.\n */\n acquire(): { shouldStart: boolean; commit: (pid: number) => void } {\n return this.withLock(() => {\n const state = this.read();\n if (state && this.isAlive(state.pid)) {\n this.write({ pid: state.pid, refs: state.refs + 1 });\n return { shouldStart: false, commit: () => {} };\n }\n // No live daemon — this caller will start one and record its PID.\n return {\n shouldStart: true,\n commit: (pid: number) =>\n this.withLock(() => this.write({ pid, refs: 1 })),\n };\n });\n }\n\n /**\n * Drop this caller's interest. Returns the PID to kill if this was the last\n * reference, otherwise null.\n */\n release(): number | null {\n return this.withLock(() => {\n const state = this.read();\n if (!state) return null;\n if (state.refs <= 1) {\n this.clear();\n return state.pid;\n }\n this.write({ pid: state.pid, refs: state.refs - 1 });\n return null;\n });\n }\n}\n\nexport class FlipperServerTransport implements Transport {\n private server: FlipperServer | null = null;\n private refcount = new FlipperRefcount();\n private listeners = new Set<MessageCallback>();\n\n /**\n * Client IDs that have sent at least one message through the devtools\n * plugin — these are the clients we send outbound messages to.\n */\n private activeClientIds = new Set<string>();\n\n /**\n * Client IDs currently connected to flipper-server, regardless of whether\n * the devtools plugin has been activated for them. Used by `enablePlugin`'s\n * \"all connected clients\" convenience.\n */\n private connectedClientIds = new Set<string>();\n\n /** Resolved connection target, fixed at construction from `options`. */\n private readonly host: string;\n private readonly port: number;\n\n /**\n * Whether this instance started the shared daemon (vs. attaching to one\n * another instance started). Only an owner may consider restarting it.\n */\n private owns = false;\n\n constructor(\n private options: {\n /** Flipper server host; defaults to \"localhost\" */\n host?: string;\n /** Flipper server WebSocket port; defaults to 52342 */\n port?: number;\n /**\n * Whether to open a browser/PWA UI once the server is up. Defaults to\n * `false` — an agent driving this transport has no use for a browser\n * tab, unlike a human running `flipper-server` directly.\n */\n open?: boolean;\n /**\n * URL to open in the browser when `open` is true. Defaults to\n * `http://localhost:{port}`. `flipper-server` itself always binds to\n * localhost regardless of this value — this only controls what URL\n * gets opened, so a custom host (e.g. a branded domain) must already\n * resolve to this machine (e.g. via `/etc/hosts`) for it to work.\n */\n url?: string;\n /**\n * Activate the devtools plugin automatically for every client that\n * connects, instead of requiring an explicit `enablePlugin()` call per\n * client. Off by default so a caller can choose when/whether to\n * activate a given device; turn this on for a fully hands-off session\n * where every connecting device should be watched immediately.\n */\n autoEnablePlugin?: boolean;\n } = {},\n ) {\n this.host = this.options.host ?? \"localhost\";\n this.port = this.options.port ?? 52342;\n }\n\n async connect(): Promise<void> {\n const host = this.host;\n const port = this.port;\n\n // Register interest in the shared daemon. The first instance to do so is\n // told to start it; the rest just attach. The daemon outlives any single\n // MCP process and is only torn down when the last instance detaches.\n const { shouldStart, commit } = this.refcount.acquire();\n this.owns = shouldStart;\n\n if (shouldStart) {\n log(\"[FlipperServerTransport] Starting flipper-server...\");\n const serverScript = require.resolve(\"flipper-server/server.js\");\n // We always pass --open=false and drive any browser-open ourselves\n // (below) so we control both whether it happens and what URL is used —\n // flipper-server's own --open only ever opens http://localhost:{port}.\n\n // Detached + unref'd: the daemon must survive this process exiting so\n // other instances keep their connections. We never kill it directly —\n // shutdown is driven by the refcount in close().\n //\n // The daemon must never inherit our fd 1: it outlives this process and\n // would write into a later session's JSON-RPC stream. Its stderr stays\n // inherited so daemon diagnostics remain visible.\n const child = spawn(\n process.execPath,\n [serverScript, \"--open=false\", `--port=${port}`],\n {\n stdio: [\"ignore\", \"ignore\", \"inherit\"],\n detached: true,\n },\n );\n child.on(\"error\", (err: Error) => {\n console.error(\n \"[FlipperServerTransport] flipper-server process error:\",\n err,\n );\n });\n child.unref();\n try {\n await waitForPort(host, port);\n } catch (err) {\n // Nothing has recorded this PID in the refcount file yet, so nobody\n // else can track or kill it — if we leave it running here it becomes\n // an orphan daemon that a later connect() would compete with on the\n // same port instead of detecting. Wait for it to actually exit (via\n // the same bounded kill-and-confirm mechanism used everywhere else in\n // this file) before rethrowing, so a caller that retries connect()\n // right away doesn't spawn a second daemon racing this one for the\n // port during teardown.\n await this.killAndWait(child.pid!);\n throw err;\n }\n commit(child.pid!);\n log(\"[FlipperServerTransport] flipper-server ready.\");\n } else {\n // Daemon already running (started by another instance) — wait for it to\n // accept connections in case it's still coming up, then attach.\n await waitForPort(host, port);\n log(\"[FlipperServerTransport] Attached to flipper-server.\");\n }\n\n if (this.options.open) {\n const url = this.options.url ?? `http://localhost:${port}`;\n log(`[FlipperServerTransport] Opening ${url}`);\n try {\n await open(url);\n } catch (err) {\n console.warn(\"[FlipperServerTransport] Failed to open UI:\", err);\n }\n }\n\n // Read the auth token the flipper-server wrote during startup\n const { getAuthToken } =\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(\"flipper-server/lib/app-connectivity/certificate-exchange/certificate-utils\") as {\n getAuthToken: () => Promise<string>;\n };\n\n let cachedToken: string | null = null;\n try {\n cachedToken = await getAuthToken();\n } catch (err) {\n console.warn(\"[FlipperServerTransport] Could not read auth token:\", err);\n }\n\n this.server = await createFlipperServer(\n host,\n port,\n () => cachedToken,\n (state) => {\n if (state === FlipperServerState.DISCONNECTED) {\n console.warn(\"[FlipperServerTransport] Disconnected from server\");\n }\n },\n );\n\n await this.server.connect();\n\n // Track client connects/disconnects\n this.server.on(\"client-connected\", (info) => {\n log(\"[FlipperServerTransport] client-connected:\", JSON.stringify(info));\n this.connectedClientIds.add(info.id);\n if (this.options.autoEnablePlugin) {\n this.enablePlugin(info.id).catch((err) => {\n console.warn(\n `[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,\n err,\n );\n });\n }\n });\n this.server.on(\"client-disconnected\", ({ id }) => {\n log(\"[FlipperServerTransport] client-disconnected:\", id);\n this.activeClientIds.delete(id);\n this.connectedClientIds.delete(id);\n });\n\n // Route inbound device messages to our Messenger listeners\n this.server.on(\"client-message\", ({ id, message }) => {\n let parsed: FlipperExecuteMessage;\n try {\n parsed = JSON.parse(message) as FlipperExecuteMessage;\n } catch {\n return;\n }\n\n log(\n `[FlipperServerTransport] client-message from ${id}: method=${parsed.method} api=${(parsed.params as { api?: string })?.api} pluginMethod=${(parsed.params as { method?: string })?.method}`,\n );\n\n if (\n parsed.method !== \"execute\" ||\n parsed.params?.api !== PLUGIN_API ||\n parsed.params?.method !== \"message::plugin\"\n ) {\n return;\n }\n\n // This client is talking through the devtools plugin — remember it\n this.activeClientIds.add(id);\n\n const payload = parsed.params.params as TransactionMetadata &\n MessengerEvent<ExtensionSupportedEvents>;\n\n for (const listener of this.listeners) {\n listener(payload);\n }\n });\n }\n\n sendMessage: CommunicationLayerMethods[\"sendMessage\"] = async (message) => {\n if (!this.server) return;\n\n const payload: FlipperExecuteMessage = {\n method: \"execute\",\n params: {\n api: PLUGIN_API,\n method: \"message::flipper\",\n params: message,\n },\n };\n\n await Promise.all(\n [...this.activeClientIds].map((clientId) =>\n this.server!.exec(\"client-request-response\", clientId, payload).catch(\n (err) => {\n console.warn(\n `[FlipperServerTransport] Failed to send to client ${clientId}:`,\n err,\n );\n // Remove dead client so we stop trying\n this.activeClientIds.delete(clientId);\n },\n ),\n ),\n );\n };\n\n /**\n * Ensures `flipper-plugin-player-ui-devtools` is installed on the attached\n * flipper-server, installing the published npm package if it's missing.\n *\n * This is Flipper's own documented plugin-install RPC (the same\n * `exec(...)` commands the desktop UI's \"Install Plugin\" button calls) —\n * not a filesystem workaround. It's opt-in: callers that manage plugin\n * installation themselves (or run against a flipper-server that already\n * has it) can skip calling this.\n */\n async ensurePluginInstalled(): Promise<InstalledPluginDetails> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const installed = await this.server.exec(\"plugins-get-installed-plugins\");\n const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);\n if (existing) {\n log(\n `[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`,\n );\n return existing;\n }\n\n log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);\n const details = await this.server.exec(\n \"plugins-install-from-npm\",\n PLUGIN_NPM_NAME,\n );\n log(\n `[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`,\n );\n return details;\n }\n\n /**\n * Activates the devtools plugin for a connected client by sending the\n * `init` handshake `js-flipper`'s device SDK requires before it will open\n * a live plugin connection (`onConnect`/`FlipperConnection`) and start\n * relaying `client-message`s for our api. Nothing in flipper-server itself\n * sends this automatically for a non-background plugin like ours unless a\n * full Flipper desktop app is attached and its tab is selected — this\n * method lets a caller trigger the same handshake directly, without\n * needing a desktop UI at all.\n *\n * Calls `ensurePluginInstalled()` first, every time — the plugin can be\n * installed/removed on the attached flipper-server independently of this\n * transport (e.g. a human using the desktop UI concurrently), so there's\n * no snapshot of \"already installed\" we can trust across calls.\n *\n * Pass a specific `clientId`, or omit it to enable for every client\n * currently connected to flipper-server that we don't already believe is\n * active (see `activeClientIds`) — `init` is otherwise harmless to repeat,\n * but there's no reason to re-send it to a client already talking to us.\n */\n async enablePlugin(clientId?: string): Promise<void> {\n await this.ensurePluginInstalled();\n const targets = clientId\n ? [clientId]\n : [...this.connectedClientIds].filter(\n (id) => !this.activeClientIds.has(id),\n );\n await this.sendLifecycleMessage(\"init\", targets);\n }\n\n /**\n * Symmetric counterpart to `enablePlugin` — releases the plugin connection\n * without disconnecting the client from flipper-server.\n *\n * Pass a specific `clientId`, or omit it to disable for every client we\n * currently believe is active (see `activeClientIds`) — there's nothing to\n * release for a client that was never activated.\n */\n async disablePlugin(clientId?: string): Promise<void> {\n const targets = clientId ? [clientId] : [...this.activeClientIds];\n await this.sendLifecycleMessage(\"deinit\", targets);\n }\n\n private async sendLifecycleMessage(\n method: \"init\" | \"deinit\",\n targets: Array<string>,\n ): Promise<void> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const payload: FlipperPluginLifecycleMessage = {\n method,\n params: { plugin: PLUGIN_API },\n };\n\n await Promise.all(\n targets.map((id) =>\n this.server!.exec(\"client-request-response\", id, payload).catch(\n (err) => {\n console.warn(\n `[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,\n err,\n );\n },\n ),\n ),\n );\n }\n\n addListener: CommunicationLayerMethods[\"addListener\"] = (callback) => {\n this.listeners.add(callback);\n };\n\n removeListener: CommunicationLayerMethods[\"removeListener\"] = (callback) => {\n this.listeners.delete(callback);\n };\n\n /**\n * In-flight `close()` promise, if one is currently running on this\n * instance. Guards `refcount.release()` and `killAndWait()` against being\n * invoked twice for a single logical close — e.g. `restart()`'s internal\n * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.\n */\n private closing: Promise<void> | null = null;\n\n async close(): Promise<void> {\n if (this.closing) return this.closing;\n\n this.closing = this.doClose().finally(() => {\n this.closing = null;\n });\n return this.closing;\n }\n\n private async doClose(): Promise<void> {\n this.listeners.clear();\n this.activeClientIds.clear();\n this.connectedClientIds.clear();\n this.server?.close();\n this.server = null;\n\n // Drop our reference to the shared daemon. If we were the last user, the\n // refcount hands back its PID and we shut it down; otherwise it keeps\n // running for the remaining instances.\n const pidToKill = this.refcount.release();\n if (pidToKill !== null) {\n await this.killAndWait(pidToKill);\n }\n }\n\n /**\n * Send SIGTERM and wait for the process to actually exit (or a bounded\n * timeout) before resolving, so callers — notably `restart()` — can rely on\n * the port being free once `close()` returns instead of racing a new child\n * for it.\n */\n private killAndWait(pid: number, timeoutMs = 5_000): Promise<void> {\n return new Promise((resolve) => {\n try {\n process.kill(pid);\n } catch {\n // Already gone.\n resolve();\n return;\n }\n\n const deadline = Date.now() + timeoutMs;\n const poll = () => {\n if (!this.isPidAlive(pid)) {\n log(\"[FlipperServerTransport] Shut down flipper-server.\");\n resolve();\n return;\n }\n if (Date.now() >= deadline) {\n log(\n \"[FlipperServerTransport] Timed out waiting for flipper-server to exit.\",\n );\n resolve();\n return;\n }\n setTimeout(poll, 100);\n };\n poll();\n });\n }\n\n private isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n }\n\n /** Read-only snapshot of this transport's connection to the shared daemon. */\n getDiagnostics(): {\n connected: boolean;\n host: string;\n port: number;\n owns: boolean;\n refs: number | null;\n activeClientIds: string[];\n connectedClientIds: string[];\n } {\n const state = this.refcount.peek();\n return {\n connected: this.server !== null,\n host: this.host,\n port: this.port,\n owns: this.owns,\n refs: state?.refs ?? null,\n activeClientIds: [...this.activeClientIds],\n connectedClientIds: [...this.connectedClientIds],\n };\n }\n\n /**\n * Restart the shared daemon. Only ever acts when this instance both owns\n * the daemon (started it) and is its sole remaining consumer — otherwise\n * this soft-errors without touching the daemon, since killing it out from\n * under other attached instances would break their connections.\n */\n async restart(): Promise<\n { ok: true; host: string; port: number } | { ok: false; reason: string }\n > {\n if (!this.owns) {\n return {\n ok: false,\n reason: \"this instance does not own the flipper-server daemon\",\n };\n }\n\n const state = this.refcount.peek();\n if (state?.refs !== 1) {\n return {\n ok: false,\n reason: \"other consumers are attached to this daemon\",\n };\n }\n\n // Re-verify immediately before the destructive close(): another instance\n // could have called connect()/acquire() between the check above and here,\n // bumping refs to 2+. This narrows but does not eliminate the race — a\n // consumer could still slip in between this re-check and close() itself;\n // a fully atomic fix would need close()+connect() to run inside\n // refcount.withLock(), which isn't reentrant-safe with connect()'s own\n // internal use of the lock, so we accept this narrow residual window.\n const recheck = this.refcount.peek();\n if (recheck?.refs !== 1) {\n return {\n ok: false,\n reason: \"other consumers attached to this daemon just before restart\",\n };\n }\n\n try {\n await this.close();\n await this.connect();\n } catch (err) {\n // The daemon this instance owned/attempted to own is now in an unknown\n // or dead state — don't leave `owns` set, or a later restart() call\n // will misreport \"other consumers are attached\" against a stale\n // refcount for a daemon that no longer exists.\n this.owns = false;\n return {\n ok: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n return { ok: true, host: this.host, port: this.port };\n }\n\n /** Whether the devtools Flipper plugin is installed, per the live daemon. */\n async getPluginInstallStatus(): Promise<{\n installed: boolean;\n version?: string;\n reason?: string;\n }> {\n if (!this.server) return { installed: false, reason: \"not connected\" };\n\n try {\n const plugins = (await this.server.exec(\n \"plugins-get-installed-plugins\",\n )) as Array<{ id?: string; name?: string; version?: string }>;\n\n const plugin = plugins.find(\n (candidate) =>\n candidate.id === PLUGIN_API || candidate.name === PLUGIN_API,\n );\n\n if (!plugin) return { installed: false };\n return plugin.version\n ? { installed: true, version: plugin.version }\n : { installed: true };\n } catch (err) {\n return {\n installed: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mCAIO;AAEP,2BAAsB;AACtB,kBAAiB;AACjB,UAAqB;AACrB,SAAoB;AACpB,SAAoB;AACpB,WAAsB;AACtB,gBAAyC;AAUzC,IAAI,OAAQ,WAAuC,cAAc,aAAa;AAC5E,EAAC,WAAuC,YACtC,UAAAA;AACJ;AAMA,IAAM,aAAa;AACnB,IAAM,kBAAkB;AAUxB,IAAM,MAAM,IAAI,SAA+B;AAC7C,UAAQ,MAAM,GAAG,IAAI;AACvB;AAyBA,SAAS,YACP,MACA,MACA,YAAY,KACG;AACf,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,UAAM,UAAU,MAAM;AACpB,YAAM,SAAa,YAAQ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M,UAAW,MAAM,KAAK,OAAO;AAAA,QACjC;AAAA,MACF;AAEA,YAAM,SAAS,QAAQ;AAAA,QACrB,CAAC,cACC,UAAU,OAAO,cAAc,UAAU,SAAS;AAAA,MACtD;AAEA,UAAI,CAAC,OAAQ,QAAO,EAAE,WAAW,MAAM;AACvC,aAAO,OAAO,UACV,EAAE,WAAW,MAAM,SAAS,OAAO,QAAQ,IAC3C,EAAE,WAAW,KAAK;AAAA,IACxB,SAAS,KAAK;AACZ,aAAO;AAAA,QACL,WAAW;AAAA,QACX,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACF;","names":["WsWebSocket","open"]}
@@ -86,6 +86,13 @@ var FlipperRefcount = class {
86
86
  return null;
87
87
  }
88
88
  }
89
+ /**
90
+ * Read the current refcount state without mutating it. Still goes through
91
+ * `withLock` so a concurrent acquire/release can't be observed mid-write.
92
+ */
93
+ peek() {
94
+ return this.withLock(() => this.read());
95
+ }
89
96
  write(state) {
90
97
  fs.writeFileSync(this.file, JSON.stringify(state));
91
98
  }
@@ -157,6 +164,11 @@ var FlipperServerTransport = class {
157
164
  * "all connected clients" convenience.
158
165
  */
159
166
  this.connectedClientIds = /* @__PURE__ */ new Set();
167
+ /**
168
+ * Whether this instance started the shared daemon (vs. attaching to one
169
+ * another instance started). Only an owner may consider restarting it.
170
+ */
171
+ this.owns = false;
160
172
  this.sendMessage = async (message) => {
161
173
  if (!this.server) return;
162
174
  const payload = {
@@ -187,11 +199,21 @@ var FlipperServerTransport = class {
187
199
  this.removeListener = (callback) => {
188
200
  this.listeners.delete(callback);
189
201
  };
202
+ /**
203
+ * In-flight `close()` promise, if one is currently running on this
204
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
205
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
206
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
207
+ */
208
+ this.closing = null;
209
+ this.host = this.options.host ?? "localhost";
210
+ this.port = this.options.port ?? 52342;
190
211
  }
191
212
  async connect() {
192
- const host = this.options.host ?? "localhost";
193
- const port = this.options.port ?? 52342;
213
+ const host = this.host;
214
+ const port = this.port;
194
215
  const { shouldStart, commit } = this.refcount.acquire();
216
+ this.owns = shouldStart;
195
217
  if (shouldStart) {
196
218
  log("[FlipperServerTransport] Starting flipper-server...");
197
219
  const serverScript = __require.resolve("flipper-server/server.js");
@@ -210,7 +232,12 @@ var FlipperServerTransport = class {
210
232
  );
211
233
  });
212
234
  child.unref();
213
- await waitForPort(host, port);
235
+ try {
236
+ await waitForPort(host, port);
237
+ } catch (err) {
238
+ await this.killAndWait(child.pid);
239
+ throw err;
240
+ }
214
241
  commit(child.pid);
215
242
  log("[FlipperServerTransport] flipper-server ready.");
216
243
  } else {
@@ -377,6 +404,13 @@ var FlipperServerTransport = class {
377
404
  );
378
405
  }
379
406
  async close() {
407
+ if (this.closing) return this.closing;
408
+ this.closing = this.doClose().finally(() => {
409
+ this.closing = null;
410
+ });
411
+ return this.closing;
412
+ }
413
+ async doClose() {
380
414
  this.listeners.clear();
381
415
  this.activeClientIds.clear();
382
416
  this.connectedClientIds.clear();
@@ -384,11 +418,119 @@ var FlipperServerTransport = class {
384
418
  this.server = null;
385
419
  const pidToKill = this.refcount.release();
386
420
  if (pidToKill !== null) {
421
+ await this.killAndWait(pidToKill);
422
+ }
423
+ }
424
+ /**
425
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
426
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
427
+ * the port being free once `close()` returns instead of racing a new child
428
+ * for it.
429
+ */
430
+ killAndWait(pid, timeoutMs = 5e3) {
431
+ return new Promise((resolve) => {
387
432
  try {
388
- process.kill(pidToKill);
389
- log("[FlipperServerTransport] Shut down flipper-server.");
433
+ process.kill(pid);
390
434
  } catch {
435
+ resolve();
436
+ return;
391
437
  }
438
+ const deadline = Date.now() + timeoutMs;
439
+ const poll = () => {
440
+ if (!this.isPidAlive(pid)) {
441
+ log("[FlipperServerTransport] Shut down flipper-server.");
442
+ resolve();
443
+ return;
444
+ }
445
+ if (Date.now() >= deadline) {
446
+ log(
447
+ "[FlipperServerTransport] Timed out waiting for flipper-server to exit."
448
+ );
449
+ resolve();
450
+ return;
451
+ }
452
+ setTimeout(poll, 100);
453
+ };
454
+ poll();
455
+ });
456
+ }
457
+ isPidAlive(pid) {
458
+ try {
459
+ process.kill(pid, 0);
460
+ return true;
461
+ } catch {
462
+ return false;
463
+ }
464
+ }
465
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
466
+ getDiagnostics() {
467
+ const state = this.refcount.peek();
468
+ return {
469
+ connected: this.server !== null,
470
+ host: this.host,
471
+ port: this.port,
472
+ owns: this.owns,
473
+ refs: state?.refs ?? null,
474
+ activeClientIds: [...this.activeClientIds],
475
+ connectedClientIds: [...this.connectedClientIds]
476
+ };
477
+ }
478
+ /**
479
+ * Restart the shared daemon. Only ever acts when this instance both owns
480
+ * the daemon (started it) and is its sole remaining consumer — otherwise
481
+ * this soft-errors without touching the daemon, since killing it out from
482
+ * under other attached instances would break their connections.
483
+ */
484
+ async restart() {
485
+ if (!this.owns) {
486
+ return {
487
+ ok: false,
488
+ reason: "this instance does not own the flipper-server daemon"
489
+ };
490
+ }
491
+ const state = this.refcount.peek();
492
+ if (state?.refs !== 1) {
493
+ return {
494
+ ok: false,
495
+ reason: "other consumers are attached to this daemon"
496
+ };
497
+ }
498
+ const recheck = this.refcount.peek();
499
+ if (recheck?.refs !== 1) {
500
+ return {
501
+ ok: false,
502
+ reason: "other consumers attached to this daemon just before restart"
503
+ };
504
+ }
505
+ try {
506
+ await this.close();
507
+ await this.connect();
508
+ } catch (err) {
509
+ this.owns = false;
510
+ return {
511
+ ok: false,
512
+ reason: err instanceof Error ? err.message : String(err)
513
+ };
514
+ }
515
+ return { ok: true, host: this.host, port: this.port };
516
+ }
517
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
518
+ async getPluginInstallStatus() {
519
+ if (!this.server) return { installed: false, reason: "not connected" };
520
+ try {
521
+ const plugins = await this.server.exec(
522
+ "plugins-get-installed-plugins"
523
+ );
524
+ const plugin = plugins.find(
525
+ (candidate) => candidate.id === PLUGIN_API || candidate.name === PLUGIN_API
526
+ );
527
+ if (!plugin) return { installed: false };
528
+ return plugin.version ? { installed: true, version: plugin.version } : { installed: true };
529
+ } catch (err) {
530
+ return {
531
+ installed: false,
532
+ reason: err instanceof Error ? err.message : String(err)
533
+ };
392
534
  }
393
535
  }
394
536
  };