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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/transport.ts CHANGED
@@ -155,6 +155,14 @@ class FlipperRefcount {
155
155
  }
156
156
  }
157
157
 
158
+ /**
159
+ * Read the current refcount state without mutating it. Still goes through
160
+ * `withLock` so a concurrent acquire/release can't be observed mid-write.
161
+ */
162
+ peek(): RefcountFile | null {
163
+ return this.withLock(() => this.read());
164
+ }
165
+
158
166
  private write(state: RefcountFile): void {
159
167
  fs.writeFileSync(this.file, JSON.stringify(state));
160
168
  }
@@ -234,6 +242,16 @@ export class FlipperServerTransport implements Transport {
234
242
  */
235
243
  private connectedClientIds = new Set<string>();
236
244
 
245
+ /** Resolved connection target, fixed at construction from `options`. */
246
+ private readonly host: string;
247
+ private readonly port: number;
248
+
249
+ /**
250
+ * Whether this instance started the shared daemon (vs. attaching to one
251
+ * another instance started). Only an owner may consider restarting it.
252
+ */
253
+ private owns = false;
254
+
237
255
  constructor(
238
256
  private options: {
239
257
  /** Flipper server host; defaults to "localhost" */
@@ -263,16 +281,20 @@ export class FlipperServerTransport implements Transport {
263
281
  */
264
282
  autoEnablePlugin?: boolean;
265
283
  } = {},
266
- ) {}
284
+ ) {
285
+ this.host = this.options.host ?? "localhost";
286
+ this.port = this.options.port ?? 52342;
287
+ }
267
288
 
268
289
  async connect(): Promise<void> {
269
- const host = this.options.host ?? "localhost";
270
- const port = this.options.port ?? 52342;
290
+ const host = this.host;
291
+ const port = this.port;
271
292
 
272
293
  // Register interest in the shared daemon. The first instance to do so is
273
294
  // told to start it; the rest just attach. The daemon outlives any single
274
295
  // MCP process and is only torn down when the last instance detaches.
275
296
  const { shouldStart, commit } = this.refcount.acquire();
297
+ this.owns = shouldStart;
276
298
 
277
299
  if (shouldStart) {
278
300
  log("[FlipperServerTransport] Starting flipper-server...");
@@ -303,7 +325,20 @@ export class FlipperServerTransport implements Transport {
303
325
  );
304
326
  });
305
327
  child.unref();
306
- await waitForPort(host, port);
328
+ try {
329
+ await waitForPort(host, port);
330
+ } catch (err) {
331
+ // Nothing has recorded this PID in the refcount file yet, so nobody
332
+ // else can track or kill it — if we leave it running here it becomes
333
+ // an orphan daemon that a later connect() would compete with on the
334
+ // same port instead of detecting. Wait for it to actually exit (via
335
+ // the same bounded kill-and-confirm mechanism used everywhere else in
336
+ // this file) before rethrowing, so a caller that retries connect()
337
+ // right away doesn't spawn a second daemon racing this one for the
338
+ // port during teardown.
339
+ await this.killAndWait(child.pid!);
340
+ throw err;
341
+ }
307
342
  commit(child.pid!);
308
343
  log("[FlipperServerTransport] flipper-server ready.");
309
344
  } else {
@@ -543,7 +578,24 @@ export class FlipperServerTransport implements Transport {
543
578
  this.listeners.delete(callback);
544
579
  };
545
580
 
581
+ /**
582
+ * In-flight `close()` promise, if one is currently running on this
583
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
584
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
585
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
586
+ */
587
+ private closing: Promise<void> | null = null;
588
+
546
589
  async close(): Promise<void> {
590
+ if (this.closing) return this.closing;
591
+
592
+ this.closing = this.doClose().finally(() => {
593
+ this.closing = null;
594
+ });
595
+ return this.closing;
596
+ }
597
+
598
+ private async doClose(): Promise<void> {
547
599
  this.listeners.clear();
548
600
  this.activeClientIds.clear();
549
601
  this.connectedClientIds.clear();
@@ -555,12 +607,160 @@ export class FlipperServerTransport implements Transport {
555
607
  // running for the remaining instances.
556
608
  const pidToKill = this.refcount.release();
557
609
  if (pidToKill !== null) {
610
+ await this.killAndWait(pidToKill);
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
616
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
617
+ * the port being free once `close()` returns instead of racing a new child
618
+ * for it.
619
+ */
620
+ private killAndWait(pid: number, timeoutMs = 5_000): Promise<void> {
621
+ return new Promise((resolve) => {
558
622
  try {
559
- process.kill(pidToKill);
560
- log("[FlipperServerTransport] Shut down flipper-server.");
623
+ process.kill(pid);
561
624
  } catch {
562
- /* already gone */
625
+ // Already gone.
626
+ resolve();
627
+ return;
563
628
  }
629
+
630
+ const deadline = Date.now() + timeoutMs;
631
+ const poll = () => {
632
+ if (!this.isPidAlive(pid)) {
633
+ log("[FlipperServerTransport] Shut down flipper-server.");
634
+ resolve();
635
+ return;
636
+ }
637
+ if (Date.now() >= deadline) {
638
+ log(
639
+ "[FlipperServerTransport] Timed out waiting for flipper-server to exit.",
640
+ );
641
+ resolve();
642
+ return;
643
+ }
644
+ setTimeout(poll, 100);
645
+ };
646
+ poll();
647
+ });
648
+ }
649
+
650
+ private isPidAlive(pid: number): boolean {
651
+ try {
652
+ process.kill(pid, 0);
653
+ return true;
654
+ } catch {
655
+ return false;
656
+ }
657
+ }
658
+
659
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
660
+ getDiagnostics(): {
661
+ connected: boolean;
662
+ host: string;
663
+ port: number;
664
+ owns: boolean;
665
+ refs: number | null;
666
+ activeClientIds: string[];
667
+ connectedClientIds: string[];
668
+ } {
669
+ const state = this.refcount.peek();
670
+ return {
671
+ connected: this.server !== null,
672
+ host: this.host,
673
+ port: this.port,
674
+ owns: this.owns,
675
+ refs: state?.refs ?? null,
676
+ activeClientIds: [...this.activeClientIds],
677
+ connectedClientIds: [...this.connectedClientIds],
678
+ };
679
+ }
680
+
681
+ /**
682
+ * Restart the shared daemon. Only ever acts when this instance both owns
683
+ * the daemon (started it) and is its sole remaining consumer — otherwise
684
+ * this soft-errors without touching the daemon, since killing it out from
685
+ * under other attached instances would break their connections.
686
+ */
687
+ async restart(): Promise<
688
+ { ok: true; host: string; port: number } | { ok: false; reason: string }
689
+ > {
690
+ if (!this.owns) {
691
+ return {
692
+ ok: false,
693
+ reason: "this instance does not own the flipper-server daemon",
694
+ };
695
+ }
696
+
697
+ const state = this.refcount.peek();
698
+ if (state?.refs !== 1) {
699
+ return {
700
+ ok: false,
701
+ reason: "other consumers are attached to this daemon",
702
+ };
703
+ }
704
+
705
+ // Re-verify immediately before the destructive close(): another instance
706
+ // could have called connect()/acquire() between the check above and here,
707
+ // bumping refs to 2+. This narrows but does not eliminate the race — a
708
+ // consumer could still slip in between this re-check and close() itself;
709
+ // a fully atomic fix would need close()+connect() to run inside
710
+ // refcount.withLock(), which isn't reentrant-safe with connect()'s own
711
+ // internal use of the lock, so we accept this narrow residual window.
712
+ const recheck = this.refcount.peek();
713
+ if (recheck?.refs !== 1) {
714
+ return {
715
+ ok: false,
716
+ reason: "other consumers attached to this daemon just before restart",
717
+ };
718
+ }
719
+
720
+ try {
721
+ await this.close();
722
+ await this.connect();
723
+ } catch (err) {
724
+ // The daemon this instance owned/attempted to own is now in an unknown
725
+ // or dead state — don't leave `owns` set, or a later restart() call
726
+ // will misreport "other consumers are attached" against a stale
727
+ // refcount for a daemon that no longer exists.
728
+ this.owns = false;
729
+ return {
730
+ ok: false,
731
+ reason: err instanceof Error ? err.message : String(err),
732
+ };
733
+ }
734
+ return { ok: true, host: this.host, port: this.port };
735
+ }
736
+
737
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
738
+ async getPluginInstallStatus(): Promise<{
739
+ installed: boolean;
740
+ version?: string;
741
+ reason?: string;
742
+ }> {
743
+ if (!this.server) return { installed: false, reason: "not connected" };
744
+
745
+ try {
746
+ const plugins = (await this.server.exec(
747
+ "plugins-get-installed-plugins",
748
+ )) as Array<{ id?: string; name?: string; version?: string }>;
749
+
750
+ const plugin = plugins.find(
751
+ (candidate) =>
752
+ candidate.id === PLUGIN_API || candidate.name === PLUGIN_API,
753
+ );
754
+
755
+ if (!plugin) return { installed: false };
756
+ return plugin.version
757
+ ? { installed: true, version: plugin.version }
758
+ : { installed: true };
759
+ } catch (err) {
760
+ return {
761
+ installed: false,
762
+ reason: err instanceof Error ? err.message : String(err),
763
+ };
564
764
  }
565
765
  }
566
766
  }
@@ -16,6 +16,14 @@ export declare class FlipperServerTransport implements Transport {
16
16
  * "all connected clients" convenience.
17
17
  */
18
18
  private connectedClientIds;
19
+ /** Resolved connection target, fixed at construction from `options`. */
20
+ private readonly host;
21
+ private readonly port;
22
+ /**
23
+ * Whether this instance started the shared daemon (vs. attaching to one
24
+ * another instance started). Only an owner may consider restarting it.
25
+ */
26
+ private owns;
19
27
  constructor(options?: {
20
28
  /** Flipper server host; defaults to "localhost" */
21
29
  host?: string;
@@ -90,6 +98,52 @@ export declare class FlipperServerTransport implements Transport {
90
98
  private sendLifecycleMessage;
91
99
  addListener: CommunicationLayerMethods["addListener"];
92
100
  removeListener: CommunicationLayerMethods["removeListener"];
101
+ /**
102
+ * In-flight `close()` promise, if one is currently running on this
103
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
104
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
105
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
106
+ */
107
+ private closing;
93
108
  close(): Promise<void>;
109
+ private doClose;
110
+ /**
111
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
112
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
113
+ * the port being free once `close()` returns instead of racing a new child
114
+ * for it.
115
+ */
116
+ private killAndWait;
117
+ private isPidAlive;
118
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
119
+ getDiagnostics(): {
120
+ connected: boolean;
121
+ host: string;
122
+ port: number;
123
+ owns: boolean;
124
+ refs: number | null;
125
+ activeClientIds: string[];
126
+ connectedClientIds: string[];
127
+ };
128
+ /**
129
+ * Restart the shared daemon. Only ever acts when this instance both owns
130
+ * the daemon (started it) and is its sole remaining consumer — otherwise
131
+ * this soft-errors without touching the daemon, since killing it out from
132
+ * under other attached instances would break their connections.
133
+ */
134
+ restart(): Promise<{
135
+ ok: true;
136
+ host: string;
137
+ port: number;
138
+ } | {
139
+ ok: false;
140
+ reason: string;
141
+ }>;
142
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
143
+ getPluginInstallStatus(): Promise<{
144
+ installed: boolean;
145
+ version?: string;
146
+ reason?: string;
147
+ }>;
94
148
  }
95
149
  //# sourceMappingURL=transport.d.ts.map