@pgxsinkit/client 0.1.48 → 0.1.50

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.
Files changed (40) hide show
  1. package/dist/boot-report.d.ts +76 -0
  2. package/dist/boot-report.d.ts.map +1 -1
  3. package/dist/index.d.ts +84 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1549 -333
  6. package/dist/index.js.map +15 -12
  7. package/dist/local-store.d.ts +58 -0
  8. package/dist/local-store.d.ts.map +1 -1
  9. package/dist/local-tables.d.ts +340 -0
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation.d.ts +36 -0
  12. package/dist/mutation.d.ts.map +1 -1
  13. package/dist/mutations-api.d.ts +82 -0
  14. package/dist/mutations-api.d.ts.map +1 -0
  15. package/dist/schema.d.ts +62 -0
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  18. package/dist/worker/define-sync-worker.d.ts +17 -0
  19. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  20. package/dist/worker/live-query-fingerprint.d.ts +14 -0
  21. package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
  22. package/dist/worker/live-query-manager.d.ts +130 -0
  23. package/dist/worker/live-query-manager.d.ts.map +1 -0
  24. package/dist/worker/protocol.d.ts +53 -2
  25. package/dist/worker/protocol.d.ts.map +1 -1
  26. package/package.json +2 -2
  27. package/skills/core/SKILL.md +1 -1
  28. package/skills/operating/SKILL.md +29 -1
  29. package/src/boot-report.ts +108 -0
  30. package/src/index.ts +648 -152
  31. package/src/local-store.ts +150 -3
  32. package/src/local-tables.ts +49 -1
  33. package/src/mutation.ts +256 -15
  34. package/src/mutations-api.ts +310 -0
  35. package/src/schema.ts +406 -193
  36. package/src/worker/attach-sync-client.ts +193 -15
  37. package/src/worker/define-sync-worker.ts +267 -53
  38. package/src/worker/live-query-fingerprint.ts +128 -0
  39. package/src/worker/live-query-manager.ts +591 -0
  40. package/src/worker/protocol.ts +49 -1
@@ -25,6 +25,9 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
25
25
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
26
26
  import {
27
27
  buildRegistryReadHandles,
28
+ ClientDisposedError,
29
+ createMutationsApi,
30
+ type LiveQueryDiagnostics,
28
31
  type LiveRowsSubscription,
29
32
  type MutationBatchItem,
30
33
  type MutationDetail,
@@ -156,13 +159,23 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
156
159
  // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
157
160
  // resolution here guarantees the rows have already been applied by the materializer.
158
161
  const hydratedPending = new Map<string, () => void>();
162
+ // Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they
163
+ // reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn
164
+ // down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).
165
+ let detached = false;
166
+ const detachError = () => new Error("[pgxsinkit] client detached — the tab released its worker attachment");
159
167
 
160
168
  // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
161
169
  const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
162
170
  let resolveReady!: () => void;
163
- const ready = new Promise<void>((resolve) => {
171
+ // FIX 2: `ready` gains a reject path so a detach BEFORE initial sync settles it (an attached client stopped
172
+ // pre-ready would otherwise leave `client.ready` / `client.start()` pending forever). Guarded below.
173
+ let rejectReady!: (error: unknown) => void;
174
+ const ready = new Promise<void>((resolve, reject) => {
164
175
  resolveReady = resolve;
176
+ rejectReady = reject;
165
177
  });
178
+ void ready.catch(() => undefined);
166
179
  let readyResolved = false;
167
180
  const readyGroups = new Set<string>();
168
181
  const groupWaiters = new Map<string, Array<() => void>>();
@@ -213,6 +226,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
213
226
  markGroupReady(event.groupKey);
214
227
  break;
215
228
  }
229
+ case "milestone": {
230
+ // Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was
231
+ // attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.
232
+ if (event.stage === "writeReady") settleWriteReady();
233
+ else if (event.stage === "bootSettled") settleBootSettled();
234
+ break;
235
+ }
236
+ case "milestone-error": {
237
+ // The background write/sync tail rejected a downstream stage (ADR-0041): fail the matching stage so a
238
+ // gated write / `bootSettled` awaiter fails loudly. `localReadReady` and the resolved attach are
239
+ // unaffected — the engine reached local-read readiness before the tail failed.
240
+ if (event.stage === "writeReady") failWriteReady(rebuildError(event.error));
241
+ else if (event.stage === "bootSettled") failBootSettled(rebuildError(event.error));
242
+ break;
243
+ }
216
244
  case "conflict":
217
245
  options.onConflict?.(event.details as MutationDetail[]);
218
246
  break;
@@ -257,14 +285,22 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
257
285
  switch (envelope.type) {
258
286
  case "attach-ack": {
259
287
  const ack = payload as AttachAckPayload;
260
- // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so
261
- // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the
262
- // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already
263
- // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.
288
+ // A LOCAL-READ-CORE boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake
289
+ // so `attachSyncClient` rejects instead of hanging forever. On success, the engine reached
290
+ // `localReadReady` — resolve that stage now (the ack fires AT localReadReady, ADR-0041 Option B) and
291
+ // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`
292
+ // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).
264
293
  if (ack.error) {
265
294
  attachAckReject?.(rebuildError(ack.error));
266
295
  } else {
267
296
  if (ack.engineReady) markReady();
297
+ resolveLocalReadReady();
298
+ // Late-attach milestone fold: the stage may have already crossed (or failed) before this tab
299
+ // attached, in which case there is no broadcast to catch — settle it straight from the ack.
300
+ if (ack.writeReady) settleWriteReady();
301
+ if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
302
+ if (ack.bootSettled) settleBootSettled();
303
+ if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
268
304
  attachAckResolve?.(ack);
269
305
  }
270
306
  break;
@@ -328,6 +364,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
328
364
 
329
365
  // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
330
366
  const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
367
+ // A detached client has no live port listener, so a worker reply could never resolve this — reject at
368
+ // once rather than register a forever-pending waiter (ADR-0040 P2).
369
+ if (detached) return Promise.reject(detachError());
331
370
  const id = newId("rpc");
332
371
  return new Promise<T>((resolve, reject) => {
333
372
  rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
@@ -342,6 +381,127 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
342
381
  attachAckResolve = resolve;
343
382
  attachAckReject = reject;
344
383
  });
384
+
385
+ // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the
386
+ // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and
387
+ // `localReadReady` is settled off the ack. `writeReady`/`bootSettled` cross in the engine's background tail:
388
+ // they resolve off the `milestone` broadcast when this tab is attached as the stage fires, OR off the ack's
389
+ // late-attach fold when the stage had already fired before this tab attached — one engine crosses each stage
390
+ // once, so both routes observe the same monotonic sequence. A tail failure rejects the matching stage via
391
+ // the `milestone-error` broadcast / the ack's stage-error fold, so a gated write or a `bootSettled` awaiter
392
+ // fails loudly rather than hanging. All guarded so a rejection on an unconsumed stage is never unhandled.
393
+ let resolveLocalReadReady!: () => void;
394
+ const localReadReady = new Promise<void>((resolve) => {
395
+ resolveLocalReadReady = resolve;
396
+ });
397
+ let resolveWriteReady!: () => void;
398
+ let rejectWriteReady!: (error: unknown) => void;
399
+ const writeReady = new Promise<void>((resolve, reject) => {
400
+ resolveWriteReady = resolve;
401
+ rejectWriteReady = reject;
402
+ });
403
+ let resolveBootSettled!: () => void;
404
+ let rejectBootSettled!: (error: unknown) => void;
405
+ const bootSettled = new Promise<void>((resolve, reject) => {
406
+ resolveBootSettled = resolve;
407
+ rejectBootSettled = reject;
408
+ });
409
+ void localReadReady.catch(() => undefined);
410
+ void writeReady.catch(() => undefined);
411
+ void bootSettled.catch(() => undefined);
412
+ // Idempotent settlers — a stage may be signalled by BOTH the ack fold and a milestone event (or by a
413
+ // detach), and must settle exactly once. `localReadReady` never rejects (a local-read-core failure rejects
414
+ // the attach handshake instead, so this client is never handed out).
415
+ let writeReadySettled = false;
416
+ let bootSettledSettled = false;
417
+ const settleWriteReady = () => {
418
+ if (writeReadySettled) return;
419
+ writeReadySettled = true;
420
+ resolveWriteReady();
421
+ };
422
+ const failWriteReady = (error: unknown) => {
423
+ if (writeReadySettled) return;
424
+ writeReadySettled = true;
425
+ rejectWriteReady(error);
426
+ };
427
+ const settleBootSettled = () => {
428
+ if (bootSettledSettled) return;
429
+ bootSettledSettled = true;
430
+ resolveBootSettled();
431
+ };
432
+ const failBootSettled = (error: unknown) => {
433
+ if (bootSettledSettled) return;
434
+ bootSettledSettled = true;
435
+ rejectBootSettled(error);
436
+ };
437
+
438
+ // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────
439
+ // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its
440
+ // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime
441
+ // (ADR-0040 decision 1; surfaced by the two-tab board e2e). So the same detach runs from `stop()` AND from
442
+ // `pagehide` with `persisted === false` — the terminal signal of a real close/navigate-away. A
443
+ // bfcache-parked page (`persisted === true`) keeps its attachment: its port survives parking and resumes
444
+ // on restore, so detaching there would strand the restored page. Idempotent — pagehide then stop is safe.
445
+ //
446
+ // Installed BEFORE the attach handshake is posted/awaited (ADR-0040 P2): a tab that closes DURING a slow
447
+ // worker boot must still send `detach` and reject the pending attach-ack, rather than leaving the worker
448
+ // holding stale port/token bookkeeping for a page that is already gone. Pre-ack every pending map below is
449
+ // empty, so the settlement loops are no-ops except for the attach-ack rejection.
450
+ const detachFromWorker = (): void => {
451
+ if (detached) return;
452
+ detached = true;
453
+ status.isRunning = false;
454
+ // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
455
+ for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
456
+ diffHandlers.clear();
457
+ postBridgeMessage(port, codec, "detach", null);
458
+ // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an
459
+ // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so
460
+ // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are
461
+ // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not
462
+ // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
463
+ // it has already settled).
464
+ attachAckReject?.(detachError());
465
+ // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so
466
+ // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the
467
+ // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription
468
+ // rejections below, where the more specific "client detached" message is useful for a data operation.
469
+ // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already
470
+ // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.
471
+ const disposedError = new ClientDisposedError();
472
+ failWriteReady(disposedError);
473
+ failBootSettled(disposedError);
474
+ // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave
475
+ // `client.ready` / `client.start()` pending forever. Settle it once with the same disposed error.
476
+ if (!readyResolved) {
477
+ readyResolved = true;
478
+ rejectReady(disposedError);
479
+ }
480
+ for (const pending of rpcPending.values()) pending.reject(detachError());
481
+ rpcPending.clear();
482
+ for (const pending of initialPending.values()) pending.reject(detachError());
483
+ initialPending.clear();
484
+ for (const resolve of hydratedPending.values()) resolve();
485
+ hydratedPending.clear();
486
+ for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();
487
+ groupWaiters.clear();
488
+ if (pagehideListener) pageWindow?.removeEventListener("pagehide", pagehideListener);
489
+ port.removeEventListener("message", listener);
490
+ port.close?.();
491
+ };
492
+ // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).
493
+ interface PageLifecycleWindowLike {
494
+ addEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
495
+ removeEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
496
+ }
497
+ const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
498
+ const pagehideListener = pageWindow
499
+ ? (event: { persisted: boolean }) => {
500
+ if (!event.persisted) detachFromWorker();
501
+ }
502
+ : undefined;
503
+ if (pagehideListener) pageWindow?.addEventListener("pagehide", pagehideListener);
504
+
345
505
  const initialToken = options.getToken ? await options.getToken() : null;
346
506
  // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
347
507
  // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.
@@ -376,9 +536,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
376
536
  try {
377
537
  await attachAck;
378
538
  } catch (error) {
379
- // The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler
380
- // leaks, then let the boot error propagate out of `attachSyncClient`.
381
- port.removeEventListener("message", listener);
539
+ // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot
540
+ // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed
541
+ // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so
542
+ // a pagehide that already detached makes this a cheap no-op.
543
+ detachFromWorker();
382
544
  throw error;
383
545
  }
384
546
  status.isRunning = true;
@@ -388,6 +550,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
388
550
  input: SubscribeLiveRowsInput,
389
551
  onRows: (rows: TRow[]) => void,
390
552
  ): Promise<LiveRowsSubscription<TRow>> => {
553
+ // A detached client has no port listener, so `live-initial` could never arrive — reject at once rather
554
+ // than register a forever-pending initial waiter (ADR-0040 P2).
555
+ if (detached) throw detachError();
391
556
  const queryId = newId("live");
392
557
  const id = newId("sub");
393
558
  const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
@@ -409,6 +574,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
409
574
  ...(input.fields ? { fields: [...input.fields] } : {}),
410
575
  ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
411
576
  ...(input.use ? { use: [...input.use] } : {}),
577
+ // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
578
+ ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
412
579
  },
413
580
  id,
414
581
  );
@@ -482,19 +649,16 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
482
649
  },
483
650
  ]),
484
651
  ) as SyncClient<TRegistry>["tables"],
652
+ localReadReady,
653
+ writeReady,
654
+ bootSettled,
485
655
  ready,
486
656
  status,
487
657
  start: async () => {
488
658
  await ready;
489
659
  },
490
660
  stop: async () => {
491
- // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
492
- status.isRunning = false;
493
- for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
494
- diffHandlers.clear();
495
- postBridgeMessage(port, codec, "detach", null);
496
- port.removeEventListener("message", listener);
497
- port.close?.();
661
+ detachFromWorker();
498
662
  },
499
663
  destroy: notSupported("client.destroy"),
500
664
  dropReadCache: notSupported("client.dropReadCache"),
@@ -516,6 +680,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
516
680
  discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
517
681
  discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
518
682
  diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
683
+ // The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,
684
+ // wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot
685
+ // `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.
686
+ mutations: createMutationsApi({
687
+ registry: options.registry,
688
+ subscribeLiveRows,
689
+ query: (sql, params) => rpc<Results>("rawQuery", [sql, params]),
690
+ }),
519
691
  query: notSupported("client.query"),
520
692
  queryRow: notSupported("client.queryRow"),
521
693
  queryRaw: notSupported("client.queryRaw"),
@@ -573,6 +745,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
573
745
  return rpc<SyncTransactionResult>("transaction", [{ mode, items: collected }]);
574
746
  },
575
747
  groupReady: async (table) => {
748
+ // A detached client will never receive further `groupReady`/status edges — reject at once rather than
749
+ // register a waiter that detach already drained (ADR-0040 P2).
750
+ if (detached) throw detachError();
576
751
  const groupKey = groupKeyForTable(table);
577
752
  if (groupKey == null || readyGroups.has(groupKey)) return;
578
753
  await new Promise<void>((resolve) => {
@@ -585,6 +760,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
585
760
  // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns
586
761
  // the same report regardless of when this tab attached (a late tab reads a boot that predates it).
587
762
  bootReport: () => rpc<BootReport | null>("bootReport", []),
763
+ // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot over the
764
+ // bridge (digests + counts only — plain objects that structured-clone across the wire).
765
+ liveQueryDiagnostics: () => rpc<LiveQueryDiagnostics[]>("liveQueryDiagnostics", []),
588
766
  // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot
589
767
  // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the
590
768
  // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).