@jxsuite/server 9.2.1 → 9.3.1

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.
@@ -0,0 +1,622 @@
1
+ /**
2
+ * The dev server's project state service (`specs/project-state.md` §10.2): the host of the active
3
+ * project (`createProjectStateHost`, the module the desktop session runs, §10.1), served as §3.2's
4
+ * Server-Sent Events binding at `GET /__studio/project/events`, the conditional writes and deletes
5
+ * of §5 on `PUT` and `DELETE /__studio/file`, and the rename cascade of §9 on `POST
6
+ * /__studio/project/rename`.
7
+ *
8
+ * The host starts on the first request that needs it (a subscription, a conditional write, a
9
+ * collaboration room), so a Studio that never subscribes pays for none of it. Activating another
10
+ * project closes the host, which ends every subscription; the next request starts a host over the
11
+ * new root, in a new epoch. A stream that names its project (`?root=`) is refused while another is
12
+ * served, because no frame says which project it describes. The live preview overlay is keyed by
13
+ * document and client beside the host (§11.3): a rename moves it, a removal drops it, and a
14
+ * client's overlays outlive its last stream by the grace period. The reload stream of `server.md`
15
+ * §3.1 is untouched: it keeps its `fs` frames and its single-reload answer to a reconnect.
16
+ *
17
+ * @docs extending/embedding/dev-server
18
+ */
19
+
20
+ import { isAbsolute, relative, resolve } from "node:path";
21
+ import {
22
+ decodeRenameOperation,
23
+ encodeSseEvents,
24
+ encodeSseSubscribe,
25
+ entityTag,
26
+ parseDeletePrecondition,
27
+ parseLastEventId,
28
+ parseWriteIdentity,
29
+ parseWritePrecondition,
30
+ PROJECT_CLIENT_PARAM,
31
+ PROJECT_ROOT_PARAM,
32
+ } from "@jxsuite/protocol/project-state-frames";
33
+ import type {
34
+ ProjectEvent,
35
+ ProjectSnapshot,
36
+ RenameOperation,
37
+ WriteConflict,
38
+ } from "@jxsuite/protocol/project-state";
39
+ import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
40
+ import { toError } from "@jxsuite/schema/parse";
41
+ import type { JsonValue } from "@jxsuite/schema/types";
42
+ import { collectionLoaderResolver } from "./project-state/collections.ts";
43
+ import { createProjectStateHost } from "./project-state/host.ts";
44
+ import { createOverlayRegistry } from "./project-state/overlays.ts";
45
+ import type { OverlayOwner, OverlayRegistry } from "./project-state/overlays.ts";
46
+ import type { ProjectStateHost, ProjectStateHostOptions } from "./project-state/host.ts";
47
+ import type { GraphReferences } from "./refactor/index.ts";
48
+ import { settledReferences } from "./project-state/settle.ts";
49
+ import { problem } from "./problem.ts";
50
+ import { HEARTBEAT_MS } from "./sse.ts";
51
+
52
+ /**
53
+ * How many bytes a stream may hold unread before its subscription is ended rather than fed (§3.2):
54
+ * the client subscribes again and catches up from the log or a snapshot, which is bounded, where an
55
+ * event stream to a reader that has stalled is not.
56
+ */
57
+ export const PROJECT_STREAM_HIGH_WATER = 4 * 1024 * 1024;
58
+
59
+ /** Who follows the active project's host beside the streams: the collaboration rooms (§11.3). */
60
+ export interface ProjectEventsFollower {
61
+ /** Events the host of `root` emitted, in revision order. */
62
+ events: (root: string, events: ProjectEvent[]) => void;
63
+ /**
64
+ * The host of `root` is about to stop serving it (another project activated, or the service
65
+ * closing): the last moment anything can still go through it. The host closes once this settles.
66
+ */
67
+ retiring?: (running: ProjectStateHost) => Promise<void>;
68
+ /** The host of `root` stopped serving it: another project was activated, or the service closed. */
69
+ retired?: (root: string) => void;
70
+ /**
71
+ * The host of `root` answered a resubscribe with a snapshot (§3.1): a watcher recovery or a
72
+ * restart began a new epoch, so the events between are not coming and `snapshot` is the index
73
+ * now.
74
+ */
75
+ resynced?: (root: string, snapshot: ProjectSnapshot) => void;
76
+ }
77
+
78
+ export interface ProjectEventsOptions {
79
+ /** The project's extension registry, which the collection loader reads (§8.1). */
80
+ registryFor?: (root: string) => Promise<ExtensionRegistry>;
81
+ /** Creates the host; `createProjectStateHost` by default. */
82
+ createHost?: (options: ProjectStateHostOptions) => Promise<ProjectStateHost>;
83
+ /**
84
+ * The unread bytes past which a stream's subscription is ended;
85
+ * {@link PROJECT_STREAM_HIGH_WATER}.
86
+ */
87
+ streamHighWater?: number;
88
+ /** How often a stream sends a heartbeat comment, in ms; fifteen seconds by default. */
89
+ heartbeatMs?: number;
90
+ /** How long the usage query waits for the host to settle, in ms; two seconds by default. */
91
+ settleLimitMs?: number;
92
+ /** Show unsaved bytes to the live preview's readers of `path` in `root` (§11.3). */
93
+ publish?: (root: string, path: string, contents: string) => void;
94
+ /** Show the live preview's readers of `path` in `root` the file again. */
95
+ unpublish?: (root: string, path: string) => void;
96
+ /** How long a departed client's overlays are kept, in ms (§11.3). */
97
+ overlayGraceMs?: number;
98
+ }
99
+
100
+ /** The overlay a client sets or clears (§11.3): `path` is relative to the project served. */
101
+ export interface OverlayParams {
102
+ path?: string;
103
+ contents?: string;
104
+ clientId?: string;
105
+ }
106
+
107
+ /**
108
+ * The owner every overlay set without a `clientId` shares (§11.3). A request over HTTP is not tied
109
+ * to a stream, so it cannot be owned by one: any tab may clear what another set without naming
110
+ * itself, which is how the overlay behaved before it had owners.
111
+ */
112
+ const UNNAMED: OverlayOwner = { anonymous: "unnamed" };
113
+
114
+ /** The owner of an overlay request or a stream: the client it names, else {@link UNNAMED}. */
115
+ const ownerOf = (clientId: string | undefined): OverlayOwner => (clientId ? { clientId } : UNNAMED);
116
+
117
+ /** Where a request's path lands: in the active project, or a response refusing it. */
118
+ export interface ProjectFileTarget {
119
+ /** The path relative to the project the host serves. */
120
+ path: string;
121
+ }
122
+
123
+ export type ProjectEventsService = ReturnType<typeof createProjectEventsService>;
124
+
125
+ const encoder = new TextEncoder();
126
+
127
+ /** The headers that put a file request on the conditional path (§5). */
128
+ const CONDITIONAL_HEADERS = ["If-Match", "If-None-Match", "Jx-Write-Id"] as const;
129
+
130
+ /**
131
+ * Whether a `PUT` or `DELETE /__studio/file` names a base or an issuer, and so is the conditional
132
+ * write or delete of §5. One that names neither is the Studio Backend Protocol's unconditional
133
+ * form, last-writer-wins, which the dev server keeps for clients that have not subscribed.
134
+ */
135
+ export function isConditionalFileRequest(req: Request): boolean {
136
+ return CONDITIONAL_HEADERS.some((name) => req.headers.has(name));
137
+ }
138
+
139
+ /** Why a request's issuer was refused: no `Jx-Write-Id`, or a `Jx-Buffer-Rev` that is no revision. */
140
+ const MISSING_IDENTITY =
141
+ "The request names no Jx-Write-Id, or a Jx-Buffer-Rev that is not a non-negative integer.";
142
+
143
+ /** The answer to a refused write or delete: `412` naming what is at the path now (§5). */
144
+ function preconditionFailed(conflict: WriteConflict): Response {
145
+ return problem("preconditionFailed", `${conflict.path} is not what the request's base names.`, {
146
+ diskHash: conflict.diskHash,
147
+ docId: conflict.docId,
148
+ path: conflict.path,
149
+ });
150
+ }
151
+
152
+ /**
153
+ * The project state service of a dev server. `activate` names the project it serves; nothing runs
154
+ * until a request needs the host.
155
+ */
156
+ export function createProjectEventsService(options: ProjectEventsOptions = {}) {
157
+ const createHost = options.createHost ?? createProjectStateHost;
158
+ const highWater = options.streamHighWater ?? PROJECT_STREAM_HIGH_WATER;
159
+ const heartbeatMs = options.heartbeatMs ?? HEARTBEAT_MS;
160
+ const { registryFor, settleLimitMs } = options;
161
+ let root: string | null = null;
162
+ let starting: Promise<ProjectStateHost> | null = null;
163
+ let host: ProjectStateHost | null = null;
164
+ let closed = false;
165
+ const followers = new Set<ProjectEventsFollower>();
166
+ /** The overlays of the project served, `null` before the first activation (§11.3). */
167
+ let overlays: OverlayRegistry | null = null;
168
+
169
+ /** An overlay registry for `serving`, which publishes through the embedder. */
170
+ const overlaysFor = (serving: string): OverlayRegistry =>
171
+ createOverlayRegistry({
172
+ publish: (path, contents) => options.publish?.(serving, path, contents),
173
+ unpublish: (path) => options.unpublish?.(serving, path),
174
+ ...(options.overlayGraceMs !== undefined && { graceMs: options.overlayGraceMs }),
175
+ });
176
+
177
+ /**
178
+ * Drop the overlays of every document `snapshot` no longer holds: the host restarted or its
179
+ * watcher recovered, and the removals between were never emitted (§4.8).
180
+ */
181
+ const resyncOverlays = (snapshot: ProjectSnapshot, rev: number): void => {
182
+ const present = new Set(snapshot.files.map((file) => file.path));
183
+ const gone: ProjectEvent[] = (overlays?.published() ?? [])
184
+ .filter((doc) => !present.has(doc.path))
185
+ .map((doc) => ({
186
+ docId: doc.docId,
187
+ isDir: false,
188
+ origin: "external",
189
+ path: doc.path,
190
+ rev,
191
+ type: "fileRemoved",
192
+ }));
193
+ overlays?.apply(gone);
194
+ };
195
+
196
+ /**
197
+ * Fan the running host's events out to every follower, across its restarts. A resubscribe is
198
+ * answered from the log when it can be; a snapshot means the events between are lost, which the
199
+ * followers are told (§3.1).
200
+ */
201
+ const follow = (running: ProjectStateHost, again = false): void => {
202
+ const { response } = running.subscribe(
203
+ { epoch: running.epoch, sinceRev: running.rev },
204
+ {
205
+ end: () => {
206
+ if (host === running) {
207
+ follow(running, true);
208
+ }
209
+ },
210
+ events: (events) => {
211
+ overlays?.apply(events);
212
+ for (const follower of followers) {
213
+ follower.events(running.root, events);
214
+ }
215
+ },
216
+ },
217
+ );
218
+ if (again && response.kind === "snapshot") {
219
+ resyncOverlays(response.snapshot, response.rev);
220
+ for (const follower of followers) {
221
+ follower.resynced?.(running.root, response.snapshot);
222
+ }
223
+ }
224
+ };
225
+
226
+ /** The host of the active project, started on first use; a start that fails is tried again. */
227
+ const start = (): Promise<ProjectStateHost> => {
228
+ if (closed) {
229
+ return Promise.reject(new Error("The dev server is stopping."));
230
+ }
231
+ if (root === null) {
232
+ return Promise.reject(new Error("No project is active."));
233
+ }
234
+ if (starting === null) {
235
+ const serving = root;
236
+ const attempt = createHost({
237
+ ...(registryFor !== undefined && {
238
+ collections: collectionLoaderResolver(() => registryFor(serving)),
239
+ }),
240
+ onError: (error) => {
241
+ console.error(`[server] project state of ${serving}: ${error.message}`);
242
+ },
243
+ root: serving,
244
+ }).then(async (created) => {
245
+ if (root !== serving || closed) {
246
+ await created.close();
247
+ throw new Error("The project is no longer active.");
248
+ }
249
+ host = created;
250
+ follow(created);
251
+ return created;
252
+ });
253
+ starting = attempt;
254
+ attempt.catch(() => {
255
+ if (starting === attempt) {
256
+ starting = null;
257
+ }
258
+ });
259
+ }
260
+ return starting;
261
+ };
262
+
263
+ /**
264
+ * Stop the host of `retiring`, which ends every subscription, and tell the followers. The caller
265
+ * has already moved `root` on (or set `closed`), so a start still in flight closes what it made.
266
+ */
267
+ const retire = async (retiring: string | null): Promise<void> => {
268
+ const pending = starting;
269
+ starting = null;
270
+ host = null;
271
+ const running = await pending?.catch(() => null);
272
+ if (running) {
273
+ for (const follower of followers) {
274
+ await follower.retiring?.(running).catch((error: Error) => {
275
+ console.error(`[server] retiring ${running.root}: ${error.message}`);
276
+ });
277
+ }
278
+ }
279
+ await running?.close();
280
+ if (retiring !== null) {
281
+ for (const follower of followers) {
282
+ follower.retired?.(retiring);
283
+ }
284
+ }
285
+ };
286
+
287
+ /**
288
+ * Where `abs` lands in the project the service serves, or the response refusing it: a path that
289
+ * is not inside that project is not the host's to write.
290
+ */
291
+ const target = (abs: string): ProjectFileTarget | Response => {
292
+ if (root === null) {
293
+ return problem("invalidRequest", "No project is active.");
294
+ }
295
+ const path = relative(root, abs).replaceAll("\\", "/");
296
+ if (path === "" || path === ".." || path.startsWith("../") || isAbsolute(path)) {
297
+ return problem("invalidRequest", "path is outside the active project");
298
+ }
299
+ return { path };
300
+ };
301
+
302
+ /** Run `body` against the running host, answering a host that cannot start with a `500`. */
303
+ const withHost = async (body: (running: ProjectStateHost) => Promise<Response>) => {
304
+ let running: ProjectStateHost;
305
+ try {
306
+ running = await start();
307
+ } catch (error) {
308
+ return problem("internalError", error instanceof Error ? error.message : String(error));
309
+ }
310
+ return body(running);
311
+ };
312
+
313
+ /**
314
+ * `GET /__studio/project/events`: answer the subscribe `Last-Event-ID` names (§3.1, §3.2) as the
315
+ * first frame, then stream every later event, batched per turn. The stream closes when the host
316
+ * ends the subscription (a restart, a watcher recovery, another project activated) or when the
317
+ * reader falls more than the high-water mark behind; the client then subscribes again.
318
+ */
319
+ function handleEvents(
320
+ req: Request,
321
+ url: URL,
322
+ rootOf: (named: string) => string = resolve,
323
+ ): Promise<Response> {
324
+ const named = url.searchParams.get(PROJECT_ROOT_PARAM);
325
+ if (named && rootOf(named) !== root) {
326
+ return Promise.resolve(
327
+ problem("conflict", `${named} is not the project this server serves now.`),
328
+ );
329
+ }
330
+ return withHost((running) => {
331
+ const request = parseLastEventId(req.headers.get("Last-Event-ID"));
332
+ const clientId = url.searchParams.get(PROJECT_CLIENT_PARAM);
333
+ if (clientId) {
334
+ request.clientId = clientId;
335
+ }
336
+ let pending: ProjectEvent[] = [];
337
+ let scheduled = false;
338
+ let ended = false;
339
+ let finished = false;
340
+ let controller!: ReadableStreamDefaultController<Uint8Array>;
341
+
342
+ const owner = ownerOf(clientId ?? undefined);
343
+ const finish = (): void => {
344
+ if (!finished) {
345
+ finished = true;
346
+ clearInterval(heartbeat);
347
+ subscription.close();
348
+ if (clientId) {
349
+ owning?.closed(owner);
350
+ }
351
+ }
352
+ };
353
+ const send = (text: string): void => {
354
+ controller.enqueue(encoder.encode(text));
355
+ };
356
+ const flush = (): void => {
357
+ scheduled = false;
358
+ if (finished) {
359
+ return;
360
+ }
361
+ if (pending.length > 0) {
362
+ const batch = pending;
363
+ pending = [];
364
+ if ((controller.desiredSize ?? 0) < 0) {
365
+ // The reader has fallen behind: it catches up by subscribing again (§3.2).
366
+ ended = true;
367
+ } else {
368
+ send(encodeSseEvents(epoch, batch));
369
+ }
370
+ }
371
+ if (ended) {
372
+ finish();
373
+ controller.close();
374
+ }
375
+ };
376
+ const schedule = (): void => {
377
+ if (!scheduled) {
378
+ scheduled = true;
379
+ queueMicrotask(flush);
380
+ }
381
+ };
382
+
383
+ const stream = new ReadableStream<Uint8Array>(
384
+ {
385
+ cancel: finish,
386
+ start(streamController) {
387
+ controller = streamController;
388
+ },
389
+ },
390
+ new ByteLengthQueuingStrategy({ highWaterMark: highWater }),
391
+ );
392
+ const subscription = running.subscribe(request, {
393
+ end: () => {
394
+ ended = true;
395
+ schedule();
396
+ },
397
+ events: (events) => {
398
+ pending.push(...events);
399
+ schedule();
400
+ },
401
+ });
402
+ const { epoch } = subscription.response;
403
+ // The overlays of a client that names itself are kept while one of its streams is open.
404
+ const owning = overlays;
405
+ if (clientId) {
406
+ owning?.opened(owner);
407
+ }
408
+ send(encodeSseSubscribe(subscription.response));
409
+ const heartbeat = setInterval(() => {
410
+ if (!finished) {
411
+ send(": heartbeat\n\n");
412
+ }
413
+ }, heartbeatMs);
414
+ return Promise.resolve(
415
+ new Response(stream, {
416
+ headers: {
417
+ "Cache-Control": "no-store",
418
+ Connection: "keep-alive",
419
+ "Content-Type": "text/event-stream",
420
+ },
421
+ }),
422
+ );
423
+ });
424
+ }
425
+
426
+ /**
427
+ * A conditional write (§5): the body is the file's bytes, the base travels as `If-Match` (or
428
+ * `If-None-Match: *` for a create) and the issuer as `Jx-Write-Id`. A stale base is a `412`.
429
+ */
430
+ function handleWrite(req: Request, abs: string): Promise<Response> {
431
+ const at = target(abs);
432
+ if (at instanceof Response) {
433
+ return Promise.resolve(at);
434
+ }
435
+ const precondition = parseWritePrecondition(req.headers);
436
+ if (!precondition.ok) {
437
+ return Promise.resolve(
438
+ problem("invalidRequest", `The write's base is ${precondition.reason}.`),
439
+ );
440
+ }
441
+ const identity = parseWriteIdentity(req.headers);
442
+ if (identity === null) {
443
+ return Promise.resolve(problem("invalidRequest", MISSING_IDENTITY));
444
+ }
445
+ return withHost(async (running) => {
446
+ const contents = new Uint8Array(await req.arrayBuffer());
447
+ const result = await running.write({
448
+ baseHash: precondition.baseHash,
449
+ contents,
450
+ path: at.path,
451
+ ...identity,
452
+ });
453
+ if (!result.ok) {
454
+ return preconditionFailed(result.conflict);
455
+ }
456
+ return Response.json(
457
+ { hash: result.hash, ok: true, path: at.path, rev: result.rev },
458
+ { headers: { ETag: entityTag(result.hash) } },
459
+ );
460
+ });
461
+ }
462
+
463
+ /**
464
+ * A conditional delete (§5): a file's base travels as `If-Match`, a directory's `{ files }` as
465
+ * the JSON body, and the issuer as `Jx-Write-Id`. A stale base is a `412`.
466
+ */
467
+ async function handleDelete(req: Request, abs: string): Promise<Response> {
468
+ const at = target(abs);
469
+ if (at instanceof Response) {
470
+ return at;
471
+ }
472
+ const precondition = parseDeletePrecondition(req.headers, await req.text());
473
+ if (!precondition.ok) {
474
+ return problem("invalidRequest", `The delete's base is ${precondition.reason}.`);
475
+ }
476
+ const identity = parseWriteIdentity(req.headers);
477
+ if (identity === null) {
478
+ return problem("invalidRequest", MISSING_IDENTITY);
479
+ }
480
+ return withHost(async (running) => {
481
+ const result = await running.delete({
482
+ base: precondition.base,
483
+ path: at.path,
484
+ writeId: identity.writeId,
485
+ });
486
+ if (!result.ok) {
487
+ return preconditionFailed(result.conflict);
488
+ }
489
+ return Response.json({ ok: true, path: at.path, rev: result.rev });
490
+ });
491
+ }
492
+
493
+ /**
494
+ * A rename as one operation (§9): the body is a `RenameOperation` with project-relative paths,
495
+ * each rewrite's contents as `WireContents`, and the answer is the host's
496
+ * `RenameOperationResult`, a refusal included, as `200`. A malformed operation, or a path that is
497
+ * not project-relative or leaves the project, is a `400`. The paths carry no project, so the
498
+ * request names one (`?root=`, as the client activated it), and one naming a project other than
499
+ * the one served is a `409 conflict`, as a stream is. `moved` is told the old path of an applied
500
+ * rename, as the unconditional route tells the collaboration rooms.
501
+ */
502
+ async function handleRename(
503
+ req: Request,
504
+ url: URL,
505
+ rootOf: (named: string) => string = resolve,
506
+ moved?: (path: string) => void,
507
+ ): Promise<Response> {
508
+ const named = url.searchParams.get(PROJECT_ROOT_PARAM);
509
+ if (named && rootOf(named) !== root) {
510
+ return problem("conflict", `${named} is not the project this server serves now.`);
511
+ }
512
+ let operation: RenameOperation;
513
+ try {
514
+ // SAFETY: JSON.parse without a reviver yields a JSON value, which the decoder checks.
515
+ operation = decodeRenameOperation(JSON.parse(await req.text()) as JsonValue);
516
+ } catch (error) {
517
+ return problem("invalidRequest", toError(error).message);
518
+ }
519
+ return withHost(async (running) => {
520
+ try {
521
+ const result = await running.rename(operation);
522
+ if (result.ok) {
523
+ moved?.(operation.from);
524
+ }
525
+ return Response.json(result);
526
+ } catch (error) {
527
+ const failure = toError(error);
528
+ return problem(
529
+ failure instanceof TypeError ? "invalidRequest" : "internalError",
530
+ failure.message,
531
+ );
532
+ }
533
+ });
534
+ }
535
+
536
+ return {
537
+ /** The project the service serves, `null` before the first activation. */
538
+ get root(): string | null {
539
+ return root;
540
+ },
541
+ /** The running host, if one has started. */
542
+ get host(): ProjectStateHost | null {
543
+ return host;
544
+ },
545
+ start,
546
+ handleEvents,
547
+ handleWrite,
548
+ handleDelete,
549
+ handleRename,
550
+ /**
551
+ * Serve `next` from now on. Activating the project already served changes nothing; activating
552
+ * another closes the host, ending every subscription, and the next request starts a host over
553
+ * `next` in a new epoch (§10.2).
554
+ */
555
+ async activate(next: string): Promise<void> {
556
+ const resolved = resolve(next);
557
+ const previous = root;
558
+ if (resolved === previous) {
559
+ return;
560
+ }
561
+ root = resolved;
562
+ // The previous project's overlays are unpublished with it, as a desktop re-root does (§11.3).
563
+ overlays?.clearAll();
564
+ overlays?.close();
565
+ overlays = overlaysFor(resolved);
566
+ await retire(previous);
567
+ },
568
+ /** Publish a client's unsaved bytes for the document at `params.path` (§11.3). */
569
+ setOverlay(params: OverlayParams & { path: string; contents: string }): void {
570
+ const docId =
571
+ overlays?.published().find((doc) => doc.path === params.path)?.docId ??
572
+ host?.docIdAt(params.path) ??
573
+ `path:${params.path}`;
574
+ overlays?.set(ownerOf(params.clientId), docId, params.path, params.contents);
575
+ },
576
+ /** Drop a client's overlay of the document at `params.path`, or every overlay it set. */
577
+ clearOverlay(params: OverlayParams): void {
578
+ const owner = ownerOf(params.clientId);
579
+ if (params.path === undefined) {
580
+ overlays?.clear(owner);
581
+ return;
582
+ }
583
+ const at = overlays?.published().find((doc) => doc.path === params.path);
584
+ if (at !== undefined) {
585
+ overlays?.clear(owner, at.docId);
586
+ }
587
+ },
588
+ /** Follow the host's events beside the streams; the returned call stops following. */
589
+ follow(follower: ProjectEventsFollower): () => void {
590
+ followers.add(follower);
591
+ return () => {
592
+ followers.delete(follower);
593
+ };
594
+ },
595
+ /**
596
+ * What the graph knows for the usage query over `scanRoot` (§12): `null` when the host serves
597
+ * another project or none is running, below `indexed`, while its watcher is degraded, or when
598
+ * it has not settled within a bound, so a change the watcher has not delivered yet is never
599
+ * missed and the caller walks the tree.
600
+ */
601
+ async references(scanRoot: string): Promise<GraphReferences | null> {
602
+ const running = host;
603
+ return running === null || running.root !== resolve(scanRoot)
604
+ ? null
605
+ : settledReferences(running, settleLimitMs);
606
+ },
607
+ /** Stop: the host closed, every subscription ended, every follower told. */
608
+ async close(): Promise<void> {
609
+ if (closed) {
610
+ return;
611
+ }
612
+ closed = true;
613
+ overlays?.clearAll();
614
+ try {
615
+ await retire(root);
616
+ } finally {
617
+ // After the host, whose ending streams would otherwise arm graces on a closed registry.
618
+ overlays?.close();
619
+ }
620
+ },
621
+ };
622
+ }