@player-devtools/client-flipper 0.15.1--canary.29.1254 → 0.15.1--canary.28.1296

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.
package/dist/index.mjs CHANGED
@@ -84,13 +84,6 @@ var FlipperRefcount = class {
84
84
  return null;
85
85
  }
86
86
  }
87
- /**
88
- * Read the current refcount state without mutating it. Still goes through
89
- * `withLock` so a concurrent acquire/release can't be observed mid-write.
90
- */
91
- peek() {
92
- return this.withLock(() => this.read());
93
- }
94
87
  write(state) {
95
88
  fs.writeFileSync(this.file, JSON.stringify(state));
96
89
  }
@@ -156,14 +149,6 @@ var FlipperServerTransport = class {
156
149
  * plugin — these are the clients we send outbound messages to.
157
150
  */
158
151
  this.activeClientIds = /* @__PURE__ */ new Set();
159
- /** Resolved connection target, set at the top of `connect()`. */
160
- this.host = "localhost";
161
- this.port = 52342;
162
- /**
163
- * Whether this instance started the shared daemon (vs. attaching to one
164
- * another instance started). Only an owner may consider restarting it.
165
- */
166
- this.owns = false;
167
152
  this.sendMessage = async (message) => {
168
153
  if (!this.server) return;
169
154
  const payload = {
@@ -194,19 +179,11 @@ var FlipperServerTransport = class {
194
179
  this.removeListener = (callback) => {
195
180
  this.listeners.delete(callback);
196
181
  };
197
- /**
198
- * In-flight `close()` promise, if one is currently running on this
199
- * instance. Guards `refcount.release()` and `killAndWait()` against being
200
- * invoked twice for a single logical close — e.g. `restart()`'s internal
201
- * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
202
- */
203
- this.closing = null;
204
182
  }
205
183
  async connect() {
206
- const host = this.host = this.options.host ?? "localhost";
207
- const port = this.port = this.options.port ?? 52342;
184
+ const host = this.options.host ?? "localhost";
185
+ const port = this.options.port ?? 52342;
208
186
  const { shouldStart, commit } = this.refcount.acquire();
209
- this.owns = shouldStart;
210
187
  if (shouldStart) {
211
188
  log("[FlipperServerTransport] Starting flipper-server...");
212
189
  const serverScript = __require.resolve("flipper-server/server.js");
@@ -221,12 +198,7 @@ var FlipperServerTransport = class {
221
198
  );
222
199
  });
223
200
  child.unref();
224
- try {
225
- await waitForPort(host, port);
226
- } catch (err) {
227
- await this.killAndWait(child.pid);
228
- throw err;
229
- }
201
+ await waitForPort(host, port);
230
202
  commit(child.pid);
231
203
  log("[FlipperServerTransport] flipper-server ready.");
232
204
  } else {
@@ -282,131 +254,17 @@ var FlipperServerTransport = class {
282
254
  });
283
255
  }
284
256
  async close() {
285
- if (this.closing) return this.closing;
286
- this.closing = this.doClose().finally(() => {
287
- this.closing = null;
288
- });
289
- return this.closing;
290
- }
291
- async doClose() {
292
257
  this.listeners.clear();
293
258
  this.activeClientIds.clear();
294
259
  this.server?.close();
295
260
  this.server = null;
296
261
  const pidToKill = this.refcount.release();
297
262
  if (pidToKill !== null) {
298
- await this.killAndWait(pidToKill);
299
- }
300
- }
301
- /**
302
- * Send SIGTERM and wait for the process to actually exit (or a bounded
303
- * timeout) before resolving, so callers — notably `restart()` — can rely on
304
- * the port being free once `close()` returns instead of racing a new child
305
- * for it.
306
- */
307
- killAndWait(pid, timeoutMs = 5e3) {
308
- return new Promise((resolve) => {
309
263
  try {
310
- process.kill(pid);
264
+ process.kill(pidToKill);
265
+ log("[FlipperServerTransport] Shut down flipper-server.");
311
266
  } catch {
312
- resolve();
313
- return;
314
267
  }
315
- const deadline = Date.now() + timeoutMs;
316
- const poll = () => {
317
- if (!this.isPidAlive(pid)) {
318
- log("[FlipperServerTransport] Shut down flipper-server.");
319
- resolve();
320
- return;
321
- }
322
- if (Date.now() >= deadline) {
323
- log(
324
- "[FlipperServerTransport] Timed out waiting for flipper-server to exit."
325
- );
326
- resolve();
327
- return;
328
- }
329
- setTimeout(poll, 100);
330
- };
331
- poll();
332
- });
333
- }
334
- isPidAlive(pid) {
335
- try {
336
- process.kill(pid, 0);
337
- return true;
338
- } catch {
339
- return false;
340
- }
341
- }
342
- /** Read-only snapshot of this transport's connection to the shared daemon. */
343
- getDiagnostics() {
344
- const state = this.refcount.peek();
345
- return {
346
- connected: this.server !== null,
347
- host: this.host,
348
- port: this.port,
349
- owns: this.owns,
350
- refs: state?.refs ?? null,
351
- activeClientIds: [...this.activeClientIds]
352
- };
353
- }
354
- /**
355
- * Restart the shared daemon. Only ever acts when this instance both owns
356
- * the daemon (started it) and is its sole remaining consumer — otherwise
357
- * this soft-errors without touching the daemon, since killing it out from
358
- * under other attached instances would break their connections.
359
- */
360
- async restart() {
361
- if (!this.owns) {
362
- return {
363
- ok: false,
364
- reason: "this instance does not own the flipper-server daemon"
365
- };
366
- }
367
- const state = this.refcount.peek();
368
- if (state?.refs !== 1) {
369
- return {
370
- ok: false,
371
- reason: "other consumers are attached to this daemon"
372
- };
373
- }
374
- const recheck = this.refcount.peek();
375
- if (recheck?.refs !== 1) {
376
- return {
377
- ok: false,
378
- reason: "other consumers attached to this daemon just before restart"
379
- };
380
- }
381
- try {
382
- await this.close();
383
- await this.connect();
384
- } catch (err) {
385
- this.owns = false;
386
- return {
387
- ok: false,
388
- reason: err instanceof Error ? err.message : String(err)
389
- };
390
- }
391
- return { ok: true, host: this.host, port: this.port };
392
- }
393
- /** Whether the devtools Flipper plugin is installed, per the live daemon. */
394
- async getPluginInstallStatus() {
395
- if (!this.server) return { installed: false, reason: "not connected" };
396
- try {
397
- const plugins = await this.server.exec(
398
- "plugins-get-installed-plugins"
399
- );
400
- const plugin = plugins.find(
401
- (candidate) => candidate.id === PLUGIN_API || candidate.name === PLUGIN_API
402
- );
403
- if (!plugin) return { installed: false };
404
- return plugin.version ? { installed: true, version: plugin.version } : { installed: true };
405
- } catch (err) {
406
- return {
407
- installed: false,
408
- reason: err instanceof Error ? err.message : String(err)
409
- };
410
268
  }
411
269
  }
412
270
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/transport.ts"],"sourcesContent":["import {\n createFlipperServer,\n FlipperServerState,\n type FlipperServer,\n} from \"flipper-server-client\";\nimport { spawn } from \"child_process\";\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\";\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/**\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 /** Resolved connection target, set at the top of `connect()`. */\n private host = \"localhost\";\n private port = 52342;\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 ) {}\n\n async connect(): Promise<void> {\n const host = (this.host = this.options.host ?? \"localhost\");\n const port = (this.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 this.owns = shouldStart;\n\n if (shouldStart) {\n log(\"[FlipperServerTransport] Starting flipper-server...\");\n const serverScript = require.resolve(\"flipper-server/server.js\");\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(process.execPath, [serverScript, \"--open=true\"], {\n stdio: [\"ignore\", \"ignore\", \"inherit\"],\n detached: true,\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 // 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 });\n this.server.on(\"client-disconnected\", ({ id }) => {\n log(\"[FlipperServerTransport] client-disconnected:\", id);\n this.activeClientIds.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 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.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 } {\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 };\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,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,aAAa;AACtB,YAAY,SAAS;AACrB,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB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,MACV;AAAA,IACF;AASA,UAAM,UAAU,KAAK,SAAS,KAAK;AACnC,QAAI,SAAS,SAAS,GAAG;AACvB,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ;AAAA,MACV;AAAA,IACF;AAEA,QAAI;AACF,YAAM,KAAK,MAAM;AACjB,YAAM,KAAK,QAAQ;AAAA,IACrB,SAAS,KAAK;AAKZ,WAAK,OAAO;AACZ,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACzD;AAAA,IACF;AACA,WAAO,EAAE,IAAI,MAAM,MAAM,KAAK,MAAM,MAAM,KAAK,KAAK;AAAA,EACtD;AAAA;AAAA,EAGA,MAAM,yBAIH;AACD,QAAI,CAAC,KAAK,OAAQ,QAAO,EAAE,WAAW,OAAO,QAAQ,gBAAgB;AAErE,QAAI;AACF,YAAM,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":[]}
1
+ {"version":3,"sources":["../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/transport.ts"],"sourcesContent":["import {\n createFlipperServer,\n FlipperServerState,\n type FlipperServer,\n} from \"flipper-server-client\";\nimport { spawn } from \"child_process\";\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\";\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/**\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 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 ) {}\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 // 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(process.execPath, [serverScript, \"--open=true\"], {\n stdio: [\"ignore\", \"ignore\", \"inherit\"],\n detached: true,\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 // 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 });\n this.server.on(\"client-disconnected\", ({ id }) => {\n log(\"[FlipperServerTransport] client-disconnected:\", id);\n this.activeClientIds.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 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.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,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,aAAa;AACtB,YAAY,SAAS;AACrB,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,aAAa,mBAAmB;AAUzC,IAAI,OAAQ,WAAuC,cAAc,aAAa;AAC5E,EAAC,WAAuC,YACtC;AACJ;AAMA,IAAM,aAAa;AAUnB,IAAM,MAAM,IAAI,SAA+B;AAC7C,UAAQ,MAAM,GAAG,IAAI;AACvB;AAmBA,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,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AO,OAAO;AAG9B,iBAAW,YAAY,KAAK,WAAW;AACrC,iBAAS,OAAO;AAAA,MAClB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAsCA,MAAM,QAAuB;AAC3B,SAAK,UAAU,MAAM;AACrB,SAAK,gBAAgB,MAAM;AAC3B,SAAK,QAAQ,MAAM;AACnB,SAAK,SAAS;AAKd,UAAM,YAAY,KAAK,SAAS,QAAQ;AACxC,QAAI,cAAc,MAAM;AACtB,UAAI;AACF,gBAAQ,KAAK,SAAS;AACtB,YAAI,oDAAoD;AAAA,MAC1D,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -6,10 +6,10 @@
6
6
  "types"
7
7
  ],
8
8
  "name": "@player-devtools/client-flipper",
9
- "version": "0.15.1--canary.29.1254",
9
+ "version": "0.15.1--canary.28.1296",
10
10
  "main": "dist/cjs/index.cjs",
11
11
  "dependencies": {
12
- "@player-devtools/types": "0.15.1--canary.29.1254",
12
+ "@player-devtools/types": "0.15.1--canary.28.1296",
13
13
  "@types/ws": "^8.0.0",
14
14
  "flipper-server": "^0.273.0",
15
15
  "flipper-server-client": "^0.273.0",
package/src/transport.ts CHANGED
@@ -146,14 +146,6 @@ class FlipperRefcount {
146
146
  }
147
147
  }
148
148
 
149
- /**
150
- * Read the current refcount state without mutating it. Still goes through
151
- * `withLock` so a concurrent acquire/release can't be observed mid-write.
152
- */
153
- peek(): RefcountFile | null {
154
- return this.withLock(() => this.read());
155
- }
156
-
157
149
  private write(state: RefcountFile): void {
158
150
  fs.writeFileSync(this.file, JSON.stringify(state));
159
151
  }
@@ -226,16 +218,6 @@ export class FlipperServerTransport implements Transport {
226
218
  */
227
219
  private activeClientIds = new Set<string>();
228
220
 
229
- /** Resolved connection target, set at the top of `connect()`. */
230
- private host = "localhost";
231
- private port = 52342;
232
-
233
- /**
234
- * Whether this instance started the shared daemon (vs. attaching to one
235
- * another instance started). Only an owner may consider restarting it.
236
- */
237
- private owns = false;
238
-
239
221
  constructor(
240
222
  private options: {
241
223
  /** Flipper server host; defaults to "localhost" */
@@ -246,14 +228,13 @@ export class FlipperServerTransport implements Transport {
246
228
  ) {}
247
229
 
248
230
  async connect(): Promise<void> {
249
- const host = (this.host = this.options.host ?? "localhost");
250
- const port = (this.port = this.options.port ?? 52342);
231
+ const host = this.options.host ?? "localhost";
232
+ const port = this.options.port ?? 52342;
251
233
 
252
234
  // Register interest in the shared daemon. The first instance to do so is
253
235
  // told to start it; the rest just attach. The daemon outlives any single
254
236
  // MCP process and is only torn down when the last instance detaches.
255
237
  const { shouldStart, commit } = this.refcount.acquire();
256
- this.owns = shouldStart;
257
238
 
258
239
  if (shouldStart) {
259
240
  log("[FlipperServerTransport] Starting flipper-server...");
@@ -276,20 +257,7 @@ export class FlipperServerTransport implements Transport {
276
257
  );
277
258
  });
278
259
  child.unref();
279
- try {
280
- await waitForPort(host, port);
281
- } catch (err) {
282
- // Nothing has recorded this PID in the refcount file yet, so nobody
283
- // else can track or kill it — if we leave it running here it becomes
284
- // an orphan daemon that a later connect() would compete with on the
285
- // same port instead of detecting. Wait for it to actually exit (via
286
- // the same bounded kill-and-confirm mechanism used everywhere else in
287
- // this file) before rethrowing, so a caller that retries connect()
288
- // right away doesn't spawn a second daemon racing this one for the
289
- // port during teardown.
290
- await this.killAndWait(child.pid!);
291
- throw err;
292
- }
260
+ await waitForPort(host, port);
293
261
  commit(child.pid!);
294
262
  log("[FlipperServerTransport] flipper-server ready.");
295
263
  } else {
@@ -404,24 +372,7 @@ export class FlipperServerTransport implements Transport {
404
372
  this.listeners.delete(callback);
405
373
  };
406
374
 
407
- /**
408
- * In-flight `close()` promise, if one is currently running on this
409
- * instance. Guards `refcount.release()` and `killAndWait()` against being
410
- * invoked twice for a single logical close — e.g. `restart()`'s internal
411
- * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
412
- */
413
- private closing: Promise<void> | null = null;
414
-
415
375
  async close(): Promise<void> {
416
- if (this.closing) return this.closing;
417
-
418
- this.closing = this.doClose().finally(() => {
419
- this.closing = null;
420
- });
421
- return this.closing;
422
- }
423
-
424
- private async doClose(): Promise<void> {
425
376
  this.listeners.clear();
426
377
  this.activeClientIds.clear();
427
378
  this.server?.close();
@@ -432,158 +383,12 @@ export class FlipperServerTransport implements Transport {
432
383
  // running for the remaining instances.
433
384
  const pidToKill = this.refcount.release();
434
385
  if (pidToKill !== null) {
435
- await this.killAndWait(pidToKill);
436
- }
437
- }
438
-
439
- /**
440
- * Send SIGTERM and wait for the process to actually exit (or a bounded
441
- * timeout) before resolving, so callers — notably `restart()` — can rely on
442
- * the port being free once `close()` returns instead of racing a new child
443
- * for it.
444
- */
445
- private killAndWait(pid: number, timeoutMs = 5_000): Promise<void> {
446
- return new Promise((resolve) => {
447
386
  try {
448
- process.kill(pid);
387
+ process.kill(pidToKill);
388
+ log("[FlipperServerTransport] Shut down flipper-server.");
449
389
  } catch {
450
- // Already gone.
451
- resolve();
452
- return;
390
+ /* already gone */
453
391
  }
454
-
455
- const deadline = Date.now() + timeoutMs;
456
- const poll = () => {
457
- if (!this.isPidAlive(pid)) {
458
- log("[FlipperServerTransport] Shut down flipper-server.");
459
- resolve();
460
- return;
461
- }
462
- if (Date.now() >= deadline) {
463
- log(
464
- "[FlipperServerTransport] Timed out waiting for flipper-server to exit.",
465
- );
466
- resolve();
467
- return;
468
- }
469
- setTimeout(poll, 100);
470
- };
471
- poll();
472
- });
473
- }
474
-
475
- private isPidAlive(pid: number): boolean {
476
- try {
477
- process.kill(pid, 0);
478
- return true;
479
- } catch {
480
- return false;
481
- }
482
- }
483
-
484
- /** Read-only snapshot of this transport's connection to the shared daemon. */
485
- getDiagnostics(): {
486
- connected: boolean;
487
- host: string;
488
- port: number;
489
- owns: boolean;
490
- refs: number | null;
491
- activeClientIds: string[];
492
- } {
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
- };
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(): Promise<
511
- { ok: true; host: string; port: number } | { ok: false; reason: string }
512
- > {
513
- if (!this.owns) {
514
- return {
515
- ok: false,
516
- reason: "this instance does not own the flipper-server daemon",
517
- };
518
- }
519
-
520
- const state = this.refcount.peek();
521
- if (state?.refs !== 1) {
522
- return {
523
- ok: false,
524
- reason: "other consumers are attached to this daemon",
525
- };
526
- }
527
-
528
- // Re-verify immediately before the destructive close(): another instance
529
- // could have called connect()/acquire() between the check above and here,
530
- // bumping refs to 2+. This narrows but does not eliminate the race — a
531
- // consumer could still slip in between this re-check and close() itself;
532
- // a fully atomic fix would need close()+connect() to run inside
533
- // refcount.withLock(), which isn't reentrant-safe with connect()'s own
534
- // internal use of the lock, so we accept this narrow residual window.
535
- const recheck = this.refcount.peek();
536
- if (recheck?.refs !== 1) {
537
- return {
538
- ok: false,
539
- reason: "other consumers attached to this daemon just before restart",
540
- };
541
- }
542
-
543
- try {
544
- await this.close();
545
- await this.connect();
546
- } catch (err) {
547
- // The daemon this instance owned/attempted to own is now in an unknown
548
- // or dead state — don't leave `owns` set, or a later restart() call
549
- // will misreport "other consumers are attached" against a stale
550
- // refcount for a daemon that no longer exists.
551
- this.owns = false;
552
- return {
553
- ok: false,
554
- reason: err instanceof Error ? err.message : String(err),
555
- };
556
- }
557
- return { ok: true, host: this.host, port: this.port };
558
- }
559
-
560
- /** Whether the devtools Flipper plugin is installed, per the live daemon. */
561
- async getPluginInstallStatus(): Promise<{
562
- installed: boolean;
563
- version?: string;
564
- reason?: string;
565
- }> {
566
- if (!this.server) return { installed: false, reason: "not connected" };
567
-
568
- try {
569
- const plugins = (await this.server.exec(
570
- "plugins-get-installed-plugins",
571
- )) as Array<{ id?: string; name?: string; version?: string }>;
572
-
573
- const plugin = plugins.find(
574
- (candidate) =>
575
- candidate.id === PLUGIN_API || candidate.name === PLUGIN_API,
576
- );
577
-
578
- if (!plugin) return { installed: false };
579
- return plugin.version
580
- ? { installed: true, version: plugin.version }
581
- : { installed: true };
582
- } catch (err) {
583
- return {
584
- installed: false,
585
- reason: err instanceof Error ? err.message : String(err),
586
- };
587
392
  }
588
393
  }
589
394
  }
@@ -9,14 +9,6 @@ export declare class FlipperServerTransport implements Transport {
9
9
  * plugin — these are the clients we send outbound messages to.
10
10
  */
11
11
  private activeClientIds;
12
- /** Resolved connection target, set at the top of `connect()`. */
13
- private host;
14
- private port;
15
- /**
16
- * Whether this instance started the shared daemon (vs. attaching to one
17
- * another instance started). Only an owner may consider restarting it.
18
- */
19
- private owns;
20
12
  constructor(options?: {
21
13
  /** Flipper server host; defaults to "localhost" */
22
14
  host?: string;
@@ -27,51 +19,6 @@ export declare class FlipperServerTransport implements Transport {
27
19
  sendMessage: CommunicationLayerMethods["sendMessage"];
28
20
  addListener: CommunicationLayerMethods["addListener"];
29
21
  removeListener: CommunicationLayerMethods["removeListener"];
30
- /**
31
- * In-flight `close()` promise, if one is currently running on this
32
- * instance. Guards `refcount.release()` and `killAndWait()` against being
33
- * invoked twice for a single logical close — e.g. `restart()`'s internal
34
- * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
35
- */
36
- private closing;
37
22
  close(): Promise<void>;
38
- private doClose;
39
- /**
40
- * Send SIGTERM and wait for the process to actually exit (or a bounded
41
- * timeout) before resolving, so callers — notably `restart()` — can rely on
42
- * the port being free once `close()` returns instead of racing a new child
43
- * for it.
44
- */
45
- private killAndWait;
46
- private isPidAlive;
47
- /** Read-only snapshot of this transport's connection to the shared daemon. */
48
- getDiagnostics(): {
49
- connected: boolean;
50
- host: string;
51
- port: number;
52
- owns: boolean;
53
- refs: number | null;
54
- activeClientIds: string[];
55
- };
56
- /**
57
- * Restart the shared daemon. Only ever acts when this instance both owns
58
- * the daemon (started it) and is its sole remaining consumer — otherwise
59
- * this soft-errors without touching the daemon, since killing it out from
60
- * under other attached instances would break their connections.
61
- */
62
- restart(): Promise<{
63
- ok: true;
64
- host: string;
65
- port: number;
66
- } | {
67
- ok: false;
68
- reason: string;
69
- }>;
70
- /** Whether the devtools Flipper plugin is installed, per the live daemon. */
71
- getPluginInstallStatus(): Promise<{
72
- installed: boolean;
73
- version?: string;
74
- reason?: string;
75
- }>;
76
23
  }
77
24
  //# sourceMappingURL=transport.d.ts.map