@player-devtools/client-flipper 0.14.2-next.1 → 0.14.3--canary.24.1132
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/cjs/index.cjs +103 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/index.legacy-esm.js +103 -1
- package/dist/index.mjs +103 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -2
- package/src/transport.ts +149 -1
- package/types/transport.d.ts +57 -0
package/dist/cjs/index.cjs
CHANGED
|
@@ -37,6 +37,7 @@ module.exports = __toCommonJS(src_exports);
|
|
|
37
37
|
// ../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/devtools/client/flipper/src/transport.ts
|
|
38
38
|
var import_flipper_server_client = require("flipper-server-client");
|
|
39
39
|
var import_child_process = require("child_process");
|
|
40
|
+
var import_open = __toESM(require("open"));
|
|
40
41
|
var net = __toESM(require("net"));
|
|
41
42
|
var fs = __toESM(require("fs"));
|
|
42
43
|
var os = __toESM(require("os"));
|
|
@@ -46,6 +47,7 @@ if (typeof globalThis.WebSocket === "undefined") {
|
|
|
46
47
|
globalThis.WebSocket = import_ws.WebSocket;
|
|
47
48
|
}
|
|
48
49
|
var PLUGIN_API = "player-ui-devtools";
|
|
50
|
+
var PLUGIN_NPM_NAME = "flipper-plugin-player-ui-devtools";
|
|
49
51
|
var log = (...args) => {
|
|
50
52
|
console.error(...args);
|
|
51
53
|
};
|
|
@@ -175,6 +177,12 @@ var FlipperServerTransport = class {
|
|
|
175
177
|
* plugin — these are the clients we send outbound messages to.
|
|
176
178
|
*/
|
|
177
179
|
this.activeClientIds = /* @__PURE__ */ new Set();
|
|
180
|
+
/**
|
|
181
|
+
* Client IDs currently connected to flipper-server, regardless of whether
|
|
182
|
+
* the devtools plugin has been activated for them. Used by `enablePlugin`'s
|
|
183
|
+
* "all connected clients" convenience.
|
|
184
|
+
*/
|
|
185
|
+
this.connectedClientIds = /* @__PURE__ */ new Set();
|
|
178
186
|
this.sendMessage = async (message) => {
|
|
179
187
|
if (!this.server) return;
|
|
180
188
|
const payload = {
|
|
@@ -213,7 +221,7 @@ var FlipperServerTransport = class {
|
|
|
213
221
|
if (shouldStart) {
|
|
214
222
|
log("[FlipperServerTransport] Starting flipper-server...");
|
|
215
223
|
const serverScript = require.resolve("flipper-server/server.js");
|
|
216
|
-
const child = (0, import_child_process.spawn)(process.execPath, [serverScript, "--open=
|
|
224
|
+
const child = (0, import_child_process.spawn)(process.execPath, [serverScript, "--open=false"], {
|
|
217
225
|
stdio: ["ignore", "ignore", "inherit"],
|
|
218
226
|
detached: true
|
|
219
227
|
});
|
|
@@ -231,6 +239,15 @@ var FlipperServerTransport = class {
|
|
|
231
239
|
await waitForPort(host, port);
|
|
232
240
|
log("[FlipperServerTransport] Attached to flipper-server.");
|
|
233
241
|
}
|
|
242
|
+
if (this.options.open) {
|
|
243
|
+
const url = this.options.url ?? `http://localhost:${port}`;
|
|
244
|
+
log(`[FlipperServerTransport] Opening ${url}`);
|
|
245
|
+
try {
|
|
246
|
+
await (0, import_open.default)(url);
|
|
247
|
+
} catch (err) {
|
|
248
|
+
console.warn("[FlipperServerTransport] Failed to open UI:", err);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
234
251
|
const { getAuthToken } = (
|
|
235
252
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
236
253
|
require("flipper-server/lib/app-connectivity/certificate-exchange/certificate-utils")
|
|
@@ -254,10 +271,20 @@ var FlipperServerTransport = class {
|
|
|
254
271
|
await this.server.connect();
|
|
255
272
|
this.server.on("client-connected", (info) => {
|
|
256
273
|
log("[FlipperServerTransport] client-connected:", JSON.stringify(info));
|
|
274
|
+
this.connectedClientIds.add(info.id);
|
|
275
|
+
if (this.options.autoEnablePlugin) {
|
|
276
|
+
this.enablePlugin(info.id).catch((err) => {
|
|
277
|
+
console.warn(
|
|
278
|
+
`[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,
|
|
279
|
+
err
|
|
280
|
+
);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
257
283
|
});
|
|
258
284
|
this.server.on("client-disconnected", ({ id }) => {
|
|
259
285
|
log("[FlipperServerTransport] client-disconnected:", id);
|
|
260
286
|
this.activeClientIds.delete(id);
|
|
287
|
+
this.connectedClientIds.delete(id);
|
|
261
288
|
});
|
|
262
289
|
this.server.on("client-message", ({ id, message }) => {
|
|
263
290
|
let parsed;
|
|
@@ -279,9 +306,84 @@ var FlipperServerTransport = class {
|
|
|
279
306
|
}
|
|
280
307
|
});
|
|
281
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
|
|
311
|
+
* flipper-server, installing the published npm package if it's missing.
|
|
312
|
+
*
|
|
313
|
+
* This is Flipper's own documented plugin-install RPC (the same
|
|
314
|
+
* `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
|
|
315
|
+
* not a filesystem workaround. It's opt-in: callers that manage plugin
|
|
316
|
+
* installation themselves (or run against a flipper-server that already
|
|
317
|
+
* has it) can skip calling this.
|
|
318
|
+
*/
|
|
319
|
+
async ensurePluginInstalled() {
|
|
320
|
+
if (!this.server) {
|
|
321
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
322
|
+
}
|
|
323
|
+
const installed = await this.server.exec("plugins-get-installed-plugins");
|
|
324
|
+
const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);
|
|
325
|
+
if (existing) {
|
|
326
|
+
log(
|
|
327
|
+
`[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`
|
|
328
|
+
);
|
|
329
|
+
return existing;
|
|
330
|
+
}
|
|
331
|
+
log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);
|
|
332
|
+
const details = await this.server.exec(
|
|
333
|
+
"plugins-install-from-npm",
|
|
334
|
+
PLUGIN_NPM_NAME
|
|
335
|
+
);
|
|
336
|
+
log(
|
|
337
|
+
`[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`
|
|
338
|
+
);
|
|
339
|
+
return details;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Activates the devtools plugin for a connected client by sending the
|
|
343
|
+
* `init` handshake `js-flipper`'s device SDK requires before it will open
|
|
344
|
+
* a live plugin connection (`onConnect`/`FlipperConnection`) and start
|
|
345
|
+
* relaying `client-message`s for our api. Nothing in flipper-server itself
|
|
346
|
+
* sends this automatically for a non-background plugin like ours unless a
|
|
347
|
+
* full Flipper desktop app is attached and its tab is selected — this
|
|
348
|
+
* method lets a caller trigger the same handshake directly, without
|
|
349
|
+
* needing a desktop UI at all.
|
|
350
|
+
*
|
|
351
|
+
* Pass a specific `clientId`, or omit it to enable for every client
|
|
352
|
+
* currently connected to flipper-server.
|
|
353
|
+
*/
|
|
354
|
+
async enablePlugin(clientId) {
|
|
355
|
+
await this.sendLifecycleMessage("init", clientId);
|
|
356
|
+
}
|
|
357
|
+
/** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
|
|
358
|
+
async disablePlugin(clientId) {
|
|
359
|
+
await this.sendLifecycleMessage("deinit", clientId);
|
|
360
|
+
}
|
|
361
|
+
async sendLifecycleMessage(method, clientId) {
|
|
362
|
+
if (!this.server) {
|
|
363
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
364
|
+
}
|
|
365
|
+
const targets = clientId ? [clientId] : [...this.connectedClientIds];
|
|
366
|
+
const payload = {
|
|
367
|
+
method,
|
|
368
|
+
params: { plugin: PLUGIN_API }
|
|
369
|
+
};
|
|
370
|
+
await Promise.all(
|
|
371
|
+
targets.map(
|
|
372
|
+
(id) => this.server.exec("client-request-response", id, payload).catch(
|
|
373
|
+
(err) => {
|
|
374
|
+
console.warn(
|
|
375
|
+
`[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,
|
|
376
|
+
err
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
)
|
|
380
|
+
)
|
|
381
|
+
);
|
|
382
|
+
}
|
|
282
383
|
async close() {
|
|
283
384
|
this.listeners.clear();
|
|
284
385
|
this.activeClientIds.clear();
|
|
386
|
+
this.connectedClientIds.clear();
|
|
285
387
|
this.server?.close();
|
|
286
388
|
this.server = null;
|
|
287
389
|
const pidToKill = this.refcount.release();
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -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 { 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 {\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UAAU,IAAI,CAAC;AAAA,IACxE,CAAC;AACD,SAAK,OAAO,GAAG,uBAAuB,CAAC,EAAE,GAAG,MAAM;AAChD,UAAI,iDAAiD,EAAE;AACvD,WAAK,gBAAgB,OAAO,EAAE;AAAA,IAChC,CAAC;AAGD,SAAK,OAAO,GAAG,kBAAkB,CAAC,EAAE,IAAI,QAAQ,MAAM;AACpD,UAAI;AACJ,UAAI;AACF,iBAAS,KAAK,MAAM,OAAO;AAAA,MAC7B,QAAQ;AACN;AAAA,MACF;AAEA;AAAA,QACE,gDAAgD,EAAE,YAAY,OAAO,MAAM,QAAS,OAAO,QAA6B,GAAG,iBAAkB,OAAO,QAAgC,MAAM;AAAA,MAC5L;AAEA,UACE,OAAO,WAAW,aAClB,OAAO,QAAQ,QAAQ,cACvB,OAAO,QAAQ,WAAW,mBAC1B;AACA;AAAA,MACF;AAGA,WAAK,gBAAgB,IAAI,EAAE;AAE3B,YAAM,UAAU,OAAO,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":["WsWebSocket"]}
|
|
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(process.execPath, [serverScript, \"--open=false\"], {\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 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 * Pass a specific `clientId`, or omit it to enable for every client\n * currently connected to flipper-server.\n */\n async enablePlugin(clientId?: string): Promise<void> {\n await this.sendLifecycleMessage(\"init\", clientId);\n }\n\n /** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */\n async disablePlugin(clientId?: string): Promise<void> {\n await this.sendLifecycleMessage(\"deinit\", clientId);\n }\n\n private async sendLifecycleMessage(\n method: \"init\" | \"deinit\",\n clientId?: string,\n ): Promise<void> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const targets = clientId ? [clientId] : [...this.connectedClientIds];\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;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AAmB,MAAM;AAC9B,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":["WsWebSocket","open"]}
|
package/dist/index.legacy-esm.js
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
FlipperServerState
|
|
12
12
|
} from "flipper-server-client";
|
|
13
13
|
import { spawn } from "child_process";
|
|
14
|
+
import open from "open";
|
|
14
15
|
import * as net from "net";
|
|
15
16
|
import * as fs from "fs";
|
|
16
17
|
import * as os from "os";
|
|
@@ -20,6 +21,7 @@ if (typeof globalThis.WebSocket === "undefined") {
|
|
|
20
21
|
globalThis.WebSocket = WsWebSocket;
|
|
21
22
|
}
|
|
22
23
|
var PLUGIN_API = "player-ui-devtools";
|
|
24
|
+
var PLUGIN_NPM_NAME = "flipper-plugin-player-ui-devtools";
|
|
23
25
|
var log = (...args) => {
|
|
24
26
|
console.error(...args);
|
|
25
27
|
};
|
|
@@ -149,6 +151,12 @@ var FlipperServerTransport = class {
|
|
|
149
151
|
* plugin — these are the clients we send outbound messages to.
|
|
150
152
|
*/
|
|
151
153
|
this.activeClientIds = /* @__PURE__ */ new Set();
|
|
154
|
+
/**
|
|
155
|
+
* Client IDs currently connected to flipper-server, regardless of whether
|
|
156
|
+
* the devtools plugin has been activated for them. Used by `enablePlugin`'s
|
|
157
|
+
* "all connected clients" convenience.
|
|
158
|
+
*/
|
|
159
|
+
this.connectedClientIds = /* @__PURE__ */ new Set();
|
|
152
160
|
this.sendMessage = async (message) => {
|
|
153
161
|
if (!this.server) return;
|
|
154
162
|
const payload = {
|
|
@@ -187,7 +195,7 @@ var FlipperServerTransport = class {
|
|
|
187
195
|
if (shouldStart) {
|
|
188
196
|
log("[FlipperServerTransport] Starting flipper-server...");
|
|
189
197
|
const serverScript = __require.resolve("flipper-server/server.js");
|
|
190
|
-
const child = spawn(process.execPath, [serverScript, "--open=
|
|
198
|
+
const child = spawn(process.execPath, [serverScript, "--open=false"], {
|
|
191
199
|
stdio: ["ignore", "ignore", "inherit"],
|
|
192
200
|
detached: true
|
|
193
201
|
});
|
|
@@ -205,6 +213,15 @@ var FlipperServerTransport = class {
|
|
|
205
213
|
await waitForPort(host, port);
|
|
206
214
|
log("[FlipperServerTransport] Attached to flipper-server.");
|
|
207
215
|
}
|
|
216
|
+
if (this.options.open) {
|
|
217
|
+
const url = this.options.url ?? `http://localhost:${port}`;
|
|
218
|
+
log(`[FlipperServerTransport] Opening ${url}`);
|
|
219
|
+
try {
|
|
220
|
+
await open(url);
|
|
221
|
+
} catch (err) {
|
|
222
|
+
console.warn("[FlipperServerTransport] Failed to open UI:", err);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
208
225
|
const { getAuthToken } = (
|
|
209
226
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
210
227
|
__require("flipper-server/lib/app-connectivity/certificate-exchange/certificate-utils")
|
|
@@ -228,10 +245,20 @@ var FlipperServerTransport = class {
|
|
|
228
245
|
await this.server.connect();
|
|
229
246
|
this.server.on("client-connected", (info) => {
|
|
230
247
|
log("[FlipperServerTransport] client-connected:", JSON.stringify(info));
|
|
248
|
+
this.connectedClientIds.add(info.id);
|
|
249
|
+
if (this.options.autoEnablePlugin) {
|
|
250
|
+
this.enablePlugin(info.id).catch((err) => {
|
|
251
|
+
console.warn(
|
|
252
|
+
`[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,
|
|
253
|
+
err
|
|
254
|
+
);
|
|
255
|
+
});
|
|
256
|
+
}
|
|
231
257
|
});
|
|
232
258
|
this.server.on("client-disconnected", ({ id }) => {
|
|
233
259
|
log("[FlipperServerTransport] client-disconnected:", id);
|
|
234
260
|
this.activeClientIds.delete(id);
|
|
261
|
+
this.connectedClientIds.delete(id);
|
|
235
262
|
});
|
|
236
263
|
this.server.on("client-message", ({ id, message }) => {
|
|
237
264
|
let parsed;
|
|
@@ -253,9 +280,84 @@ var FlipperServerTransport = class {
|
|
|
253
280
|
}
|
|
254
281
|
});
|
|
255
282
|
}
|
|
283
|
+
/**
|
|
284
|
+
* Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
|
|
285
|
+
* flipper-server, installing the published npm package if it's missing.
|
|
286
|
+
*
|
|
287
|
+
* This is Flipper's own documented plugin-install RPC (the same
|
|
288
|
+
* `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
|
|
289
|
+
* not a filesystem workaround. It's opt-in: callers that manage plugin
|
|
290
|
+
* installation themselves (or run against a flipper-server that already
|
|
291
|
+
* has it) can skip calling this.
|
|
292
|
+
*/
|
|
293
|
+
async ensurePluginInstalled() {
|
|
294
|
+
if (!this.server) {
|
|
295
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
296
|
+
}
|
|
297
|
+
const installed = await this.server.exec("plugins-get-installed-plugins");
|
|
298
|
+
const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);
|
|
299
|
+
if (existing) {
|
|
300
|
+
log(
|
|
301
|
+
`[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`
|
|
302
|
+
);
|
|
303
|
+
return existing;
|
|
304
|
+
}
|
|
305
|
+
log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);
|
|
306
|
+
const details = await this.server.exec(
|
|
307
|
+
"plugins-install-from-npm",
|
|
308
|
+
PLUGIN_NPM_NAME
|
|
309
|
+
);
|
|
310
|
+
log(
|
|
311
|
+
`[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`
|
|
312
|
+
);
|
|
313
|
+
return details;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Activates the devtools plugin for a connected client by sending the
|
|
317
|
+
* `init` handshake `js-flipper`'s device SDK requires before it will open
|
|
318
|
+
* a live plugin connection (`onConnect`/`FlipperConnection`) and start
|
|
319
|
+
* relaying `client-message`s for our api. Nothing in flipper-server itself
|
|
320
|
+
* sends this automatically for a non-background plugin like ours unless a
|
|
321
|
+
* full Flipper desktop app is attached and its tab is selected — this
|
|
322
|
+
* method lets a caller trigger the same handshake directly, without
|
|
323
|
+
* needing a desktop UI at all.
|
|
324
|
+
*
|
|
325
|
+
* Pass a specific `clientId`, or omit it to enable for every client
|
|
326
|
+
* currently connected to flipper-server.
|
|
327
|
+
*/
|
|
328
|
+
async enablePlugin(clientId) {
|
|
329
|
+
await this.sendLifecycleMessage("init", clientId);
|
|
330
|
+
}
|
|
331
|
+
/** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
|
|
332
|
+
async disablePlugin(clientId) {
|
|
333
|
+
await this.sendLifecycleMessage("deinit", clientId);
|
|
334
|
+
}
|
|
335
|
+
async sendLifecycleMessage(method, clientId) {
|
|
336
|
+
if (!this.server) {
|
|
337
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
338
|
+
}
|
|
339
|
+
const targets = clientId ? [clientId] : [...this.connectedClientIds];
|
|
340
|
+
const payload = {
|
|
341
|
+
method,
|
|
342
|
+
params: { plugin: PLUGIN_API }
|
|
343
|
+
};
|
|
344
|
+
await Promise.all(
|
|
345
|
+
targets.map(
|
|
346
|
+
(id) => this.server.exec("client-request-response", id, payload).catch(
|
|
347
|
+
(err) => {
|
|
348
|
+
console.warn(
|
|
349
|
+
`[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,
|
|
350
|
+
err
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
);
|
|
356
|
+
}
|
|
256
357
|
async close() {
|
|
257
358
|
this.listeners.clear();
|
|
258
359
|
this.activeClientIds.clear();
|
|
360
|
+
this.connectedClientIds.clear();
|
|
259
361
|
this.server?.close();
|
|
260
362
|
this.server = null;
|
|
261
363
|
const pidToKill = this.refcount.release();
|
package/dist/index.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
FlipperServerState
|
|
12
12
|
} from "flipper-server-client";
|
|
13
13
|
import { spawn } from "child_process";
|
|
14
|
+
import open from "open";
|
|
14
15
|
import * as net from "net";
|
|
15
16
|
import * as fs from "fs";
|
|
16
17
|
import * as os from "os";
|
|
@@ -20,6 +21,7 @@ if (typeof globalThis.WebSocket === "undefined") {
|
|
|
20
21
|
globalThis.WebSocket = WsWebSocket;
|
|
21
22
|
}
|
|
22
23
|
var PLUGIN_API = "player-ui-devtools";
|
|
24
|
+
var PLUGIN_NPM_NAME = "flipper-plugin-player-ui-devtools";
|
|
23
25
|
var log = (...args) => {
|
|
24
26
|
console.error(...args);
|
|
25
27
|
};
|
|
@@ -149,6 +151,12 @@ var FlipperServerTransport = class {
|
|
|
149
151
|
* plugin — these are the clients we send outbound messages to.
|
|
150
152
|
*/
|
|
151
153
|
this.activeClientIds = /* @__PURE__ */ new Set();
|
|
154
|
+
/**
|
|
155
|
+
* Client IDs currently connected to flipper-server, regardless of whether
|
|
156
|
+
* the devtools plugin has been activated for them. Used by `enablePlugin`'s
|
|
157
|
+
* "all connected clients" convenience.
|
|
158
|
+
*/
|
|
159
|
+
this.connectedClientIds = /* @__PURE__ */ new Set();
|
|
152
160
|
this.sendMessage = async (message) => {
|
|
153
161
|
if (!this.server) return;
|
|
154
162
|
const payload = {
|
|
@@ -187,7 +195,7 @@ var FlipperServerTransport = class {
|
|
|
187
195
|
if (shouldStart) {
|
|
188
196
|
log("[FlipperServerTransport] Starting flipper-server...");
|
|
189
197
|
const serverScript = __require.resolve("flipper-server/server.js");
|
|
190
|
-
const child = spawn(process.execPath, [serverScript, "--open=
|
|
198
|
+
const child = spawn(process.execPath, [serverScript, "--open=false"], {
|
|
191
199
|
stdio: ["ignore", "ignore", "inherit"],
|
|
192
200
|
detached: true
|
|
193
201
|
});
|
|
@@ -205,6 +213,15 @@ var FlipperServerTransport = class {
|
|
|
205
213
|
await waitForPort(host, port);
|
|
206
214
|
log("[FlipperServerTransport] Attached to flipper-server.");
|
|
207
215
|
}
|
|
216
|
+
if (this.options.open) {
|
|
217
|
+
const url = this.options.url ?? `http://localhost:${port}`;
|
|
218
|
+
log(`[FlipperServerTransport] Opening ${url}`);
|
|
219
|
+
try {
|
|
220
|
+
await open(url);
|
|
221
|
+
} catch (err) {
|
|
222
|
+
console.warn("[FlipperServerTransport] Failed to open UI:", err);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
208
225
|
const { getAuthToken } = (
|
|
209
226
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
210
227
|
__require("flipper-server/lib/app-connectivity/certificate-exchange/certificate-utils")
|
|
@@ -228,10 +245,20 @@ var FlipperServerTransport = class {
|
|
|
228
245
|
await this.server.connect();
|
|
229
246
|
this.server.on("client-connected", (info) => {
|
|
230
247
|
log("[FlipperServerTransport] client-connected:", JSON.stringify(info));
|
|
248
|
+
this.connectedClientIds.add(info.id);
|
|
249
|
+
if (this.options.autoEnablePlugin) {
|
|
250
|
+
this.enablePlugin(info.id).catch((err) => {
|
|
251
|
+
console.warn(
|
|
252
|
+
`[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,
|
|
253
|
+
err
|
|
254
|
+
);
|
|
255
|
+
});
|
|
256
|
+
}
|
|
231
257
|
});
|
|
232
258
|
this.server.on("client-disconnected", ({ id }) => {
|
|
233
259
|
log("[FlipperServerTransport] client-disconnected:", id);
|
|
234
260
|
this.activeClientIds.delete(id);
|
|
261
|
+
this.connectedClientIds.delete(id);
|
|
235
262
|
});
|
|
236
263
|
this.server.on("client-message", ({ id, message }) => {
|
|
237
264
|
let parsed;
|
|
@@ -253,9 +280,84 @@ var FlipperServerTransport = class {
|
|
|
253
280
|
}
|
|
254
281
|
});
|
|
255
282
|
}
|
|
283
|
+
/**
|
|
284
|
+
* Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
|
|
285
|
+
* flipper-server, installing the published npm package if it's missing.
|
|
286
|
+
*
|
|
287
|
+
* This is Flipper's own documented plugin-install RPC (the same
|
|
288
|
+
* `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
|
|
289
|
+
* not a filesystem workaround. It's opt-in: callers that manage plugin
|
|
290
|
+
* installation themselves (or run against a flipper-server that already
|
|
291
|
+
* has it) can skip calling this.
|
|
292
|
+
*/
|
|
293
|
+
async ensurePluginInstalled() {
|
|
294
|
+
if (!this.server) {
|
|
295
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
296
|
+
}
|
|
297
|
+
const installed = await this.server.exec("plugins-get-installed-plugins");
|
|
298
|
+
const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);
|
|
299
|
+
if (existing) {
|
|
300
|
+
log(
|
|
301
|
+
`[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`
|
|
302
|
+
);
|
|
303
|
+
return existing;
|
|
304
|
+
}
|
|
305
|
+
log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);
|
|
306
|
+
const details = await this.server.exec(
|
|
307
|
+
"plugins-install-from-npm",
|
|
308
|
+
PLUGIN_NPM_NAME
|
|
309
|
+
);
|
|
310
|
+
log(
|
|
311
|
+
`[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`
|
|
312
|
+
);
|
|
313
|
+
return details;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Activates the devtools plugin for a connected client by sending the
|
|
317
|
+
* `init` handshake `js-flipper`'s device SDK requires before it will open
|
|
318
|
+
* a live plugin connection (`onConnect`/`FlipperConnection`) and start
|
|
319
|
+
* relaying `client-message`s for our api. Nothing in flipper-server itself
|
|
320
|
+
* sends this automatically for a non-background plugin like ours unless a
|
|
321
|
+
* full Flipper desktop app is attached and its tab is selected — this
|
|
322
|
+
* method lets a caller trigger the same handshake directly, without
|
|
323
|
+
* needing a desktop UI at all.
|
|
324
|
+
*
|
|
325
|
+
* Pass a specific `clientId`, or omit it to enable for every client
|
|
326
|
+
* currently connected to flipper-server.
|
|
327
|
+
*/
|
|
328
|
+
async enablePlugin(clientId) {
|
|
329
|
+
await this.sendLifecycleMessage("init", clientId);
|
|
330
|
+
}
|
|
331
|
+
/** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
|
|
332
|
+
async disablePlugin(clientId) {
|
|
333
|
+
await this.sendLifecycleMessage("deinit", clientId);
|
|
334
|
+
}
|
|
335
|
+
async sendLifecycleMessage(method, clientId) {
|
|
336
|
+
if (!this.server) {
|
|
337
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
338
|
+
}
|
|
339
|
+
const targets = clientId ? [clientId] : [...this.connectedClientIds];
|
|
340
|
+
const payload = {
|
|
341
|
+
method,
|
|
342
|
+
params: { plugin: PLUGIN_API }
|
|
343
|
+
};
|
|
344
|
+
await Promise.all(
|
|
345
|
+
targets.map(
|
|
346
|
+
(id) => this.server.exec("client-request-response", id, payload).catch(
|
|
347
|
+
(err) => {
|
|
348
|
+
console.warn(
|
|
349
|
+
`[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,
|
|
350
|
+
err
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
);
|
|
356
|
+
}
|
|
256
357
|
async close() {
|
|
257
358
|
this.listeners.clear();
|
|
258
359
|
this.activeClientIds.clear();
|
|
360
|
+
this.connectedClientIds.clear();
|
|
259
361
|
this.server?.close();
|
|
260
362
|
this.server = null;
|
|
261
363
|
const pidToKill = this.refcount.release();
|
package/dist/index.mjs.map
CHANGED
|
@@ -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 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,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AE;AAE3B,YAAM,UAAU,OAAO,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":[]}
|
|
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 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(process.execPath, [serverScript, \"--open=false\"], {\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 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 * Pass a specific `clientId`, or omit it to enable for every client\n * currently connected to flipper-server.\n */\n async enablePlugin(clientId?: string): Promise<void> {\n await this.sendLifecycleMessage(\"init\", clientId);\n }\n\n /** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */\n async disablePlugin(clientId?: string): Promise<void> {\n await this.sendLifecycleMessage(\"deinit\", clientId);\n }\n\n private async sendLifecycleMessage(\n method: \"init\" | \"deinit\",\n clientId?: string,\n ): Promise<void> {\n if (!this.server) {\n throw new Error(\"FlipperServerTransport is not connected\");\n }\n\n const targets = clientId ? [clientId] : [...this.connectedClientIds];\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,EACE;AAAA,EACA;AAAA,OAEK;AAEP,SAAS,aAAa;AACtB,OAAO,UAAU;AACjB,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;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,OAAO;AACL,qBAAW,SAAS,GAAG;AAAA,QACzB;AAAA,MACF,CAAC;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AAQ;AAChB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,UAAU,WAAW,CAAC,QAAQ,IAAI,CAAC,GAAG,KAAK,kBAAkB;AACnE,UAAM,UAAyC;AAAA,MAC7C;AAAA,MACA,QAAQ,EAAE,QAAQ,WAAW;AAAA,IAC/B;AAEA,UAAM,QAAQ;AAAA,MACZ,QAAQ;AAAA,QAAI,CAAC,OACX,KAAK,OAAQ,KAAK,2BAA2B,IAAI,OAAO,EAAE;AAAA,UACxD,CAAC,QAAQ;AACP,oBAAQ;AAAA,cACN,sCAAsC,MAAM,sBAAsB,EAAE;AAAA,cACpE;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAUA,MAAM,QAAuB;AAC3B,SAAK,UAAU,MAAM;AACrB,SAAK,gBAAgB,MAAM;AAC3B,SAAK,mBAAmB,MAAM;AAC9B,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,13 +6,15 @@
|
|
|
6
6
|
"types"
|
|
7
7
|
],
|
|
8
8
|
"name": "@player-devtools/client-flipper",
|
|
9
|
-
"version": "0.14.
|
|
9
|
+
"version": "0.14.3--canary.24.1132",
|
|
10
10
|
"main": "dist/cjs/index.cjs",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@player-devtools/types": "0.14.
|
|
12
|
+
"@player-devtools/types": "0.14.3--canary.24.1132",
|
|
13
13
|
"@types/ws": "^8.0.0",
|
|
14
|
+
"flipper-common": "^0.273.0",
|
|
14
15
|
"flipper-server": "^0.273.0",
|
|
15
16
|
"flipper-server-client": "^0.273.0",
|
|
17
|
+
"open": "^8.4.2",
|
|
16
18
|
"ws": "^8.0.0",
|
|
17
19
|
"tslib": "^2.6.2"
|
|
18
20
|
},
|
package/src/transport.ts
CHANGED
|
@@ -3,7 +3,9 @@ import {
|
|
|
3
3
|
FlipperServerState,
|
|
4
4
|
type FlipperServer,
|
|
5
5
|
} from "flipper-server-client";
|
|
6
|
+
import type { InstalledPluginDetails } from "flipper-common";
|
|
6
7
|
import { spawn } from "child_process";
|
|
8
|
+
import open from "open";
|
|
7
9
|
import * as net from "net";
|
|
8
10
|
import * as fs from "fs";
|
|
9
11
|
import * as os from "os";
|
|
@@ -28,6 +30,7 @@ type MessageCallback = (
|
|
|
28
30
|
) => void;
|
|
29
31
|
|
|
30
32
|
const PLUGIN_API = "player-ui-devtools";
|
|
33
|
+
const PLUGIN_NPM_NAME = "flipper-plugin-player-ui-devtools";
|
|
31
34
|
|
|
32
35
|
/**
|
|
33
36
|
* All diagnostics go to stderr.
|
|
@@ -51,6 +54,12 @@ type FlipperExecuteMessage = {
|
|
|
51
54
|
};
|
|
52
55
|
};
|
|
53
56
|
|
|
57
|
+
/** Wire shape of the `init`/`deinit` plugin-activation handshake (`js-flipper`'s `FlipperClient.onMessageReceived`) */
|
|
58
|
+
type FlipperPluginLifecycleMessage = {
|
|
59
|
+
method: "init" | "deinit";
|
|
60
|
+
params: { plugin: string };
|
|
61
|
+
};
|
|
62
|
+
|
|
54
63
|
/**
|
|
55
64
|
* Flipper headless transport
|
|
56
65
|
*
|
|
@@ -218,12 +227,41 @@ export class FlipperServerTransport implements Transport {
|
|
|
218
227
|
*/
|
|
219
228
|
private activeClientIds = new Set<string>();
|
|
220
229
|
|
|
230
|
+
/**
|
|
231
|
+
* Client IDs currently connected to flipper-server, regardless of whether
|
|
232
|
+
* the devtools plugin has been activated for them. Used by `enablePlugin`'s
|
|
233
|
+
* "all connected clients" convenience.
|
|
234
|
+
*/
|
|
235
|
+
private connectedClientIds = new Set<string>();
|
|
236
|
+
|
|
221
237
|
constructor(
|
|
222
238
|
private options: {
|
|
223
239
|
/** Flipper server host; defaults to "localhost" */
|
|
224
240
|
host?: string;
|
|
225
241
|
/** Flipper server WebSocket port; defaults to 52342 */
|
|
226
242
|
port?: number;
|
|
243
|
+
/**
|
|
244
|
+
* Whether to open a browser/PWA UI once the server is up. Defaults to
|
|
245
|
+
* `false` — an agent driving this transport has no use for a browser
|
|
246
|
+
* tab, unlike a human running `flipper-server` directly.
|
|
247
|
+
*/
|
|
248
|
+
open?: boolean;
|
|
249
|
+
/**
|
|
250
|
+
* URL to open in the browser when `open` is true. Defaults to
|
|
251
|
+
* `http://localhost:{port}`. `flipper-server` itself always binds to
|
|
252
|
+
* localhost regardless of this value — this only controls what URL
|
|
253
|
+
* gets opened, so a custom host (e.g. a branded domain) must already
|
|
254
|
+
* resolve to this machine (e.g. via `/etc/hosts`) for it to work.
|
|
255
|
+
*/
|
|
256
|
+
url?: string;
|
|
257
|
+
/**
|
|
258
|
+
* Activate the devtools plugin automatically for every client that
|
|
259
|
+
* connects, instead of requiring an explicit `enablePlugin()` call per
|
|
260
|
+
* client. Off by default so a caller can choose when/whether to
|
|
261
|
+
* activate a given device; turn this on for a fully hands-off session
|
|
262
|
+
* where every connecting device should be watched immediately.
|
|
263
|
+
*/
|
|
264
|
+
autoEnablePlugin?: boolean;
|
|
227
265
|
} = {},
|
|
228
266
|
) {}
|
|
229
267
|
|
|
@@ -239,6 +277,10 @@ export class FlipperServerTransport implements Transport {
|
|
|
239
277
|
if (shouldStart) {
|
|
240
278
|
log("[FlipperServerTransport] Starting flipper-server...");
|
|
241
279
|
const serverScript = require.resolve("flipper-server/server.js");
|
|
280
|
+
// We always pass --open=false and drive any browser-open ourselves
|
|
281
|
+
// (below) so we control both whether it happens and what URL is used —
|
|
282
|
+
// flipper-server's own --open only ever opens http://localhost:{port}.
|
|
283
|
+
//
|
|
242
284
|
// Detached + unref'd: the daemon must survive this process exiting so
|
|
243
285
|
// other instances keep their connections. We never kill it directly —
|
|
244
286
|
// shutdown is driven by the refcount in close().
|
|
@@ -246,7 +288,7 @@ export class FlipperServerTransport implements Transport {
|
|
|
246
288
|
// The daemon must never inherit our fd 1: it outlives this process and
|
|
247
289
|
// would write into a later session's JSON-RPC stream. Its stderr stays
|
|
248
290
|
// inherited so daemon diagnostics remain visible.
|
|
249
|
-
const child = spawn(process.execPath, [serverScript, "--open=
|
|
291
|
+
const child = spawn(process.execPath, [serverScript, "--open=false"], {
|
|
250
292
|
stdio: ["ignore", "ignore", "inherit"],
|
|
251
293
|
detached: true,
|
|
252
294
|
});
|
|
@@ -267,6 +309,16 @@ export class FlipperServerTransport implements Transport {
|
|
|
267
309
|
log("[FlipperServerTransport] Attached to flipper-server.");
|
|
268
310
|
}
|
|
269
311
|
|
|
312
|
+
if (this.options.open) {
|
|
313
|
+
const url = this.options.url ?? `http://localhost:${port}`;
|
|
314
|
+
log(`[FlipperServerTransport] Opening ${url}`);
|
|
315
|
+
try {
|
|
316
|
+
await open(url);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
console.warn("[FlipperServerTransport] Failed to open UI:", err);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
270
322
|
// Read the auth token the flipper-server wrote during startup
|
|
271
323
|
const { getAuthToken } =
|
|
272
324
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
@@ -297,10 +349,20 @@ export class FlipperServerTransport implements Transport {
|
|
|
297
349
|
// Track client connects/disconnects
|
|
298
350
|
this.server.on("client-connected", (info) => {
|
|
299
351
|
log("[FlipperServerTransport] client-connected:", JSON.stringify(info));
|
|
352
|
+
this.connectedClientIds.add(info.id);
|
|
353
|
+
if (this.options.autoEnablePlugin) {
|
|
354
|
+
this.enablePlugin(info.id).catch((err) => {
|
|
355
|
+
console.warn(
|
|
356
|
+
`[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,
|
|
357
|
+
err,
|
|
358
|
+
);
|
|
359
|
+
});
|
|
360
|
+
}
|
|
300
361
|
});
|
|
301
362
|
this.server.on("client-disconnected", ({ id }) => {
|
|
302
363
|
log("[FlipperServerTransport] client-disconnected:", id);
|
|
303
364
|
this.activeClientIds.delete(id);
|
|
365
|
+
this.connectedClientIds.delete(id);
|
|
304
366
|
});
|
|
305
367
|
|
|
306
368
|
// Route inbound device messages to our Messenger listeners
|
|
@@ -364,6 +426,91 @@ export class FlipperServerTransport implements Transport {
|
|
|
364
426
|
);
|
|
365
427
|
};
|
|
366
428
|
|
|
429
|
+
/**
|
|
430
|
+
* Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
|
|
431
|
+
* flipper-server, installing the published npm package if it's missing.
|
|
432
|
+
*
|
|
433
|
+
* This is Flipper's own documented plugin-install RPC (the same
|
|
434
|
+
* `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
|
|
435
|
+
* not a filesystem workaround. It's opt-in: callers that manage plugin
|
|
436
|
+
* installation themselves (or run against a flipper-server that already
|
|
437
|
+
* has it) can skip calling this.
|
|
438
|
+
*/
|
|
439
|
+
async ensurePluginInstalled(): Promise<InstalledPluginDetails> {
|
|
440
|
+
if (!this.server) {
|
|
441
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const installed = await this.server.exec("plugins-get-installed-plugins");
|
|
445
|
+
const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);
|
|
446
|
+
if (existing) {
|
|
447
|
+
log(
|
|
448
|
+
`[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`,
|
|
449
|
+
);
|
|
450
|
+
return existing;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);
|
|
454
|
+
const details = await this.server.exec(
|
|
455
|
+
"plugins-install-from-npm",
|
|
456
|
+
PLUGIN_NPM_NAME,
|
|
457
|
+
);
|
|
458
|
+
log(
|
|
459
|
+
`[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`,
|
|
460
|
+
);
|
|
461
|
+
return details;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Activates the devtools plugin for a connected client by sending the
|
|
466
|
+
* `init` handshake `js-flipper`'s device SDK requires before it will open
|
|
467
|
+
* a live plugin connection (`onConnect`/`FlipperConnection`) and start
|
|
468
|
+
* relaying `client-message`s for our api. Nothing in flipper-server itself
|
|
469
|
+
* sends this automatically for a non-background plugin like ours unless a
|
|
470
|
+
* full Flipper desktop app is attached and its tab is selected — this
|
|
471
|
+
* method lets a caller trigger the same handshake directly, without
|
|
472
|
+
* needing a desktop UI at all.
|
|
473
|
+
*
|
|
474
|
+
* Pass a specific `clientId`, or omit it to enable for every client
|
|
475
|
+
* currently connected to flipper-server.
|
|
476
|
+
*/
|
|
477
|
+
async enablePlugin(clientId?: string): Promise<void> {
|
|
478
|
+
await this.sendLifecycleMessage("init", clientId);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
|
|
482
|
+
async disablePlugin(clientId?: string): Promise<void> {
|
|
483
|
+
await this.sendLifecycleMessage("deinit", clientId);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
private async sendLifecycleMessage(
|
|
487
|
+
method: "init" | "deinit",
|
|
488
|
+
clientId?: string,
|
|
489
|
+
): Promise<void> {
|
|
490
|
+
if (!this.server) {
|
|
491
|
+
throw new Error("FlipperServerTransport is not connected");
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const targets = clientId ? [clientId] : [...this.connectedClientIds];
|
|
495
|
+
const payload: FlipperPluginLifecycleMessage = {
|
|
496
|
+
method,
|
|
497
|
+
params: { plugin: PLUGIN_API },
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
await Promise.all(
|
|
501
|
+
targets.map((id) =>
|
|
502
|
+
this.server!.exec("client-request-response", id, payload).catch(
|
|
503
|
+
(err) => {
|
|
504
|
+
console.warn(
|
|
505
|
+
`[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,
|
|
506
|
+
err,
|
|
507
|
+
);
|
|
508
|
+
},
|
|
509
|
+
),
|
|
510
|
+
),
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
|
|
367
514
|
addListener: CommunicationLayerMethods["addListener"] = (callback) => {
|
|
368
515
|
this.listeners.add(callback);
|
|
369
516
|
};
|
|
@@ -375,6 +522,7 @@ export class FlipperServerTransport implements Transport {
|
|
|
375
522
|
async close(): Promise<void> {
|
|
376
523
|
this.listeners.clear();
|
|
377
524
|
this.activeClientIds.clear();
|
|
525
|
+
this.connectedClientIds.clear();
|
|
378
526
|
this.server?.close();
|
|
379
527
|
this.server = null;
|
|
380
528
|
|
package/types/transport.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InstalledPluginDetails } from "flipper-common";
|
|
1
2
|
import type { CommunicationLayerMethods, Transport } from "@player-devtools/types";
|
|
2
3
|
export declare class FlipperServerTransport implements Transport {
|
|
3
4
|
private options;
|
|
@@ -9,14 +10,70 @@ export declare class FlipperServerTransport implements Transport {
|
|
|
9
10
|
* plugin — these are the clients we send outbound messages to.
|
|
10
11
|
*/
|
|
11
12
|
private activeClientIds;
|
|
13
|
+
/**
|
|
14
|
+
* Client IDs currently connected to flipper-server, regardless of whether
|
|
15
|
+
* the devtools plugin has been activated for them. Used by `enablePlugin`'s
|
|
16
|
+
* "all connected clients" convenience.
|
|
17
|
+
*/
|
|
18
|
+
private connectedClientIds;
|
|
12
19
|
constructor(options?: {
|
|
13
20
|
/** Flipper server host; defaults to "localhost" */
|
|
14
21
|
host?: string;
|
|
15
22
|
/** Flipper server WebSocket port; defaults to 52342 */
|
|
16
23
|
port?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Whether to open a browser/PWA UI once the server is up. Defaults to
|
|
26
|
+
* `false` — an agent driving this transport has no use for a browser
|
|
27
|
+
* tab, unlike a human running `flipper-server` directly.
|
|
28
|
+
*/
|
|
29
|
+
open?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* URL to open in the browser when `open` is true. Defaults to
|
|
32
|
+
* `http://localhost:{port}`. `flipper-server` itself always binds to
|
|
33
|
+
* localhost regardless of this value — this only controls what URL
|
|
34
|
+
* gets opened, so a custom host (e.g. a branded domain) must already
|
|
35
|
+
* resolve to this machine (e.g. via `/etc/hosts`) for it to work.
|
|
36
|
+
*/
|
|
37
|
+
url?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Activate the devtools plugin automatically for every client that
|
|
40
|
+
* connects, instead of requiring an explicit `enablePlugin()` call per
|
|
41
|
+
* client. Off by default so a caller can choose when/whether to
|
|
42
|
+
* activate a given device; turn this on for a fully hands-off session
|
|
43
|
+
* where every connecting device should be watched immediately.
|
|
44
|
+
*/
|
|
45
|
+
autoEnablePlugin?: boolean;
|
|
17
46
|
});
|
|
18
47
|
connect(): Promise<void>;
|
|
19
48
|
sendMessage: CommunicationLayerMethods["sendMessage"];
|
|
49
|
+
/**
|
|
50
|
+
* Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
|
|
51
|
+
* flipper-server, installing the published npm package if it's missing.
|
|
52
|
+
*
|
|
53
|
+
* This is Flipper's own documented plugin-install RPC (the same
|
|
54
|
+
* `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
|
|
55
|
+
* not a filesystem workaround. It's opt-in: callers that manage plugin
|
|
56
|
+
* installation themselves (or run against a flipper-server that already
|
|
57
|
+
* has it) can skip calling this.
|
|
58
|
+
*/
|
|
59
|
+
ensurePluginInstalled(): Promise<InstalledPluginDetails>;
|
|
60
|
+
/**
|
|
61
|
+
* Activates the devtools plugin for a connected client by sending the
|
|
62
|
+
* `init` handshake `js-flipper`'s device SDK requires before it will open
|
|
63
|
+
* a live plugin connection (`onConnect`/`FlipperConnection`) and start
|
|
64
|
+
* relaying `client-message`s for our api. Nothing in flipper-server itself
|
|
65
|
+
* sends this automatically for a non-background plugin like ours unless a
|
|
66
|
+
* full Flipper desktop app is attached and its tab is selected — this
|
|
67
|
+
* method lets a caller trigger the same handshake directly, without
|
|
68
|
+
* needing a desktop UI at all.
|
|
69
|
+
*
|
|
70
|
+
* Pass a specific `clientId`, or omit it to enable for every client
|
|
71
|
+
* currently connected to flipper-server.
|
|
72
|
+
*/
|
|
73
|
+
enablePlugin(clientId?: string): Promise<void>;
|
|
74
|
+
/** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
|
|
75
|
+
disablePlugin(clientId?: string): Promise<void>;
|
|
76
|
+
private sendLifecycleMessage;
|
|
20
77
|
addListener: CommunicationLayerMethods["addListener"];
|
|
21
78
|
removeListener: CommunicationLayerMethods["removeListener"];
|
|
22
79
|
close(): Promise<void>;
|