@pgxsinkit/client 0.1.48 → 0.1.49

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.
@@ -1 +1 @@
1
- {"version":3,"file":"attach-sync-client.d.ts","sourceRoot":"","sources":["../../src/worker/attach-sync-client.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAEV,iBAAiB,EAEjB,iBAAiB,EAElB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAIjD,OAAO,EAIL,KAAK,cAAc,EAEnB,KAAK,UAAU,EAGhB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAG7D,OAAO,EAGL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAEhB,KAAK,UAAU,EACf,KAAK,kBAAkB,EAaxB,MAAM,YAAY,CAAC;AAEpB,mHAAmH;AACnH,UAAU,UAAU;IAClB,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,kBAAkB,EAAE,KAAK,IAAI,CAAC;IAC1E,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,KAAK,IAAI,CAAC;IAC3F,mBAAmB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,KAAK,IAAI,CAAC;CAC/F;AAED,MAAM,WAAW,uBAAuB,CAAC,SAAS,SAAS,iBAAiB;IAC1E,QAAQ,EAAE,SAAS,CAAC;IACpB,mGAAmG;IACnG,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,mGAA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;GAGG;AACH,MAAM,MAAM,kBAAkB,CAAC,SAAS,SAAS,iBAAiB,IAAI,UAAU,CAAC,SAAS,CAAC,GAAG;IAC5F,iBAAiB,EAAE,MAAM,IAAI,CAAC;IAC9B;;;;OAIG;IACH,SAAS,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACtC,CAAC;AAEF,wBAAsB,gBAAgB,CAAC,KAAK,CAAC,SAAS,SAAS,iBAAiB,EAC9E,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,GAC1C,OAAO,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,CA4iBxC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,SAAS,iBAAiB,EACrE,OAAO,EAAE,IAAI,CAAC,uBAAuB,CAAC,SAAS,CAAC,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,GAAG,WAAW,GAAG,OAAO,CAAC,GACvG,OAAO,CAAC,IAAI,CAAC,CAuBf"}
@@ -58,6 +58,23 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
58
58
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
59
59
  /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
60
60
  pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
61
+ /**
62
+ * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
63
+ * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
64
+ * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
65
+ * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
66
+ * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing
67
+ * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —
68
+ * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.
69
+ */
70
+ liveQueries?: {
71
+ /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
72
+ defaultKeepAliveMs?: number;
73
+ /** Max simultaneously-retained (zero-subscriber) entries — LRU-evicted past this. Default 16. */
74
+ maxRetainedQueries?: number;
75
+ /** Max total rows across all retained entries — LRU-evicted past this. Default 50_000. */
76
+ maxRetainedRows?: number;
77
+ };
61
78
  }
62
79
  /** The worker-side host: attach ports, await the boot, and (for tests) tear down. */
63
80
  export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
@@ -1 +1 @@
1
- {"version":3,"file":"define-sync-worker.d.ts","sourceRoot":"","sources":["../../src/worker/define-sync-worker.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAoC,iBAAiB,EAAa,MAAM,sBAAsB,CAAC;AAI3G,OAAO,EACL,KAAK,YAAY,EAEjB,KAAK,uBAAuB,EAO5B,KAAK,UAAU,EAChB,MAAM,UAAU,CAAC;AAKlB,OAAO,EAEL,KAAK,WAAW,EAGhB,KAAK,UAAU,EAWhB,MAAM,YAAY,CAAC;AAGpB,MAAM,WAAW,uBAAuB,CAAC,SAAS,SAAS,iBAAiB;IAC1E;;;;OAIG;IACH,QAAQ,EAAE,SAAS,CAAC;IACpB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,SAAS,GAAG,SAAS,CAAC;IACtE;;;;;OAKG;IACH,YAAY,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,QAAQ,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;IACxF,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,sGAAsG;IACtG,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,+GAA+G;IAC/G,mBAAmB,CAAC,EAAE,MAAM,CAAC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W,CAAC,EAAE;QACZ,6GAA6G;QAC7G,kBAAkB,CAAC,EAAE,MAAM,CAAC;QAC5B,iGAAiG;QACjG,kBAAkB,CAAC,EAAE,MAAM,CAAC;QAC5B,0FAA0F;QAC1F,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH;AAED,qFAAqF;AACrF,MAAM,WAAW,cAAc,CAAC,SAAS,SAAS,iBAAiB;IACjE,8GAA8G;IAC9G,OAAO,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,IAAI,CAAC;IACpC,uGAAuG;IACvG,UAAU,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;IACjD,kGAAkG;IAClG,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B;AASD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,CAAC,SAAS,SAAS,iBAAiB,EACxE,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,GAC1C,cAAc,CAAC,SAAS,CAAC,CA8uB3B"}
@@ -0,0 +1,14 @@
1
+ /** The map key (full canonical string — the dedup identity) plus a short digest for diagnostics (Slice 5). */
2
+ export interface LiveQueryFingerprint {
3
+ /** The exact dedup key: two subscriptions share a registration iff their `key` is identical. */
4
+ key: string;
5
+ /** A short, opaque hash of `key` — for diagnostics/observability only, NEVER used for dedup. */
6
+ digest: string;
7
+ }
8
+ /**
9
+ * Fingerprint a live query. `materialSql` is the POST-WRAP SQL (the manager's registration input); `params`
10
+ * are the decoded bound params; `pkColumns` selects the key mode. Returns the full canonical `key` (the dedup
11
+ * identity) and a short `digest` for diagnostics.
12
+ */
13
+ export declare function fingerprintLiveQuery(materialSql: string, params: readonly unknown[], pkColumns?: readonly string[]): LiveQueryFingerprint;
14
+ //# sourceMappingURL=live-query-fingerprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-query-fingerprint.d.ts","sourceRoot":"","sources":["../../src/worker/live-query-fingerprint.ts"],"names":[],"mappings":"AAYA,8GAA8G;AAC9G,MAAM,WAAW,oBAAoB;IACnC,gGAAgG;IAChG,GAAG,EAAE,MAAM,CAAC;IACZ,gGAAgG;IAChG,MAAM,EAAE,MAAM,CAAC;CAChB;AAqFD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,SAAS,OAAO,EAAE,EAC1B,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,GAC5B,oBAAoB,CAetB"}
@@ -0,0 +1,130 @@
1
+ import type { LiveNamespace } from "@electric-sql/pglite/live";
2
+ import type { LiveDiffPayload } from "./protocol";
3
+ type Row = Record<string, unknown>;
4
+ /** The wire diff a subscriber receives — exactly `computeLiveDiff`'s output, minus the caller's `queryId`. */
5
+ export type LiveDiffWire = Omit<LiveDiffPayload, "queryId">;
6
+ /** The two delivery callbacks a subscriber supplies; the caller wires these to its bridge posting. */
7
+ export interface LiveSubscriber {
8
+ /** The verbatim initial snapshot (NOT a diff), delivered ONCE before any diff (rows-before-diff ordering). */
9
+ deliverInitial(rows: readonly Row[]): void;
10
+ /** A subsequent change, already diffed against the last delivered set. */
11
+ deliverDiff(diff: LiveDiffWire): void;
12
+ }
13
+ /** Post-wrap SQL + bound params + optional single-column PK (selects `incrementalQuery` vs `query`). */
14
+ export interface LiveQuerySpec {
15
+ materialSql: string;
16
+ params: unknown[];
17
+ pkColumns?: readonly string[];
18
+ }
19
+ /** Per-subscription options (ADR-0040). */
20
+ export interface LiveSubscribeOptions {
21
+ /**
22
+ * How long (ms) THIS subscriber asks the entry to be retained after IT (and any siblings) leave. The
23
+ * entry's effective keep-alive is `max(policy default, the max hint of the current active generation)`
24
+ * (see the generation rule on `subscribe`); the worker count/row budgets stay authoritative over any hint.
25
+ * Absent / 0 → no retention from this subscriber. Must be a finite number ≥ 0.
26
+ */
27
+ keepAliveMs?: number;
28
+ /**
29
+ * An opaque grouping key for diagnostics only (ADR-0040 decision 5) — never part of the fingerprint, so it
30
+ * NEVER affects dedup or registration. The worker passes one stable scope per bridge port, so a snapshot's
31
+ * `scopeCount` reads as the distinct-tab count; the in-process client passes none.
32
+ */
33
+ scope?: string;
34
+ }
35
+ /** A live registration's handle: awaited/tracked teardown and a coalesced refresh. */
36
+ export interface LiveSubscription {
37
+ /** Non-blocking for the caller; the promise is retained internally so `dispose()` awaits it (decision 1). */
38
+ unsubscribe(): Promise<void>;
39
+ /** Force one recompute; concurrent calls SHARE one underlying `live.refresh()` (never N stacked reruns). */
40
+ refresh(): Promise<void>;
41
+ }
42
+ /** The manager's bounded keep-alive policy (ADR-0040 decision 4). All fields default; the block is opt-in. */
43
+ export interface LiveQueryPolicy {
44
+ /**
45
+ * Default retention (ms) for a zero-subscriber entry, floored by each subscriber's own `keepAliveMs` hint.
46
+ * Default 0 — the current route-scoped behaviour (tear a query down the moment its last consumer leaves).
47
+ * The standing argument for 0: a retained zero-subscriber entry STILL pays a full SQL rerun + diff on every
48
+ * dependent-table write — PGlite live queries cannot be paused, only torn down — so retention trades that
49
+ * standing cost for avoiding re-materialization, and is only worth it for a genuinely hot, re-mounted query.
50
+ */
51
+ defaultKeepAliveMs?: number;
52
+ /** Max simultaneously-retained (zero-subscriber) entries; LRU-evicted past this. Active entries never count. */
53
+ maxRetainedQueries?: number;
54
+ /** Max total rows held across ALL retained entries; LRU-evicted past this. Active entries never count. */
55
+ maxRetainedRows?: number;
56
+ }
57
+ type TimerHandle = unknown;
58
+ export interface LiveQueryManagerDeps {
59
+ /** The engine's `live` namespace — only the two registration entry points are used. */
60
+ live: Pick<LiveNamespace, "query" | "incrementalQuery">;
61
+ /** Bounded keep-alive policy (ADR-0040 decision 4); omitted → all defaults (retention off). */
62
+ policy?: LiveQueryPolicy;
63
+ /** Monotonic clock for keep-alive LRU accounting. Default `performance.now()` (Date.now fallback). */
64
+ now?: () => number;
65
+ /** Injectable eviction timer (tests drive it deterministically). Default `setTimeout`. */
66
+ setTimer?: (callback: () => void, ms: number) => TimerHandle;
67
+ /** Injectable timer cancel. Default `clearTimeout`. */
68
+ clearTimer?: (handle: TimerHandle) => void;
69
+ }
70
+ /**
71
+ * A structured-clone-safe, per-entry diagnostics record (ADR-0040 decision 5). It carries ONLY opaque
72
+ * fingerprint digests and counts/timings — NEVER SQL text, bound param values, or result-row values (those
73
+ * live only in the fingerprint's private `key`, which is deliberately absent here). Safe to cross the bridge
74
+ * and surface in support tooling.
75
+ */
76
+ export interface LiveQueryDiagnostics {
77
+ /** The opaque fingerprint digest (a short hash — see live-query-fingerprint.ts). NEVER the full key. */
78
+ digest: string;
79
+ /** Current subscriber count (0 while retained). */
80
+ subscriberCount: number;
81
+ /**
82
+ * Distinct subscription scopes on this entry. The worker passes one scope per bridge port, so in WORKER
83
+ * mode this is the number of distinct tabs on the query; the in-process client passes none, so it stays 1
84
+ * while any subscriber is attached (0 while retained).
85
+ */
86
+ scopeCount: number;
87
+ /** Rows currently held in the shared diff state. */
88
+ rowCount: number;
89
+ /** Whether this is a zero-subscriber entry currently kept alive (ADR-0040 decision 4). */
90
+ retained: boolean;
91
+ /** How many subscribes JOINED this entry rather than creating it (active-joins + retained rejoins). */
92
+ dedupHits: number;
93
+ /** Monotonic stamp (ms) when the entry was created. */
94
+ createdAt: number;
95
+ /** Time (ms) the registration setup took, or `null` until setup completes. */
96
+ setupMs: number | null;
97
+ /** Refresh timings for the shared registration (the hydration-chain / force refreshes). */
98
+ refresh: {
99
+ count: number;
100
+ lastMs: number | null;
101
+ totalMs: number;
102
+ maxMs: number;
103
+ };
104
+ /** Monotonic stamp (ms) of the last transition to zero subscribers, or `null` if never retained. */
105
+ lastUsedAt: number | null;
106
+ /** How long (ms) the entry has been retained (now − lastUsedAt), or `null` when not retained. */
107
+ retainedSinceMs: number | null;
108
+ /** A teardown is in flight (the entry is unsubscribing from PGlite). */
109
+ teardownPending: boolean;
110
+ }
111
+ export interface LiveQueryManager {
112
+ subscribe(spec: LiveQuerySpec, subscriber: LiveSubscriber, opts?: LiveSubscribeOptions): Promise<LiveSubscription>;
113
+ /** Tear down every live registration and await ALL teardowns (the Slice-1 close-vs-unsubscribe guard). */
114
+ dispose(): Promise<void>;
115
+ /**
116
+ * A point-in-time diagnostics snapshot (ADR-0040 decision 5): one plain-object record per live entry,
117
+ * carrying digests + counts/timings only — NO SQL, params, or rows. For the `liveQueryDiagnostics` RPC and
118
+ * support tooling.
119
+ */
120
+ snapshot(): LiveQueryDiagnostics[];
121
+ }
122
+ /**
123
+ * Validate a keep-alive policy at the public boundary (ADR-0040 decision 4 — bounded, no permanent retention).
124
+ * Every provided field must be a finite number ≥ 0; the two budgets must additionally be integers. Throws a
125
+ * `TypeError` naming the offending field so a misconfiguration fails at construction, not at first subscribe.
126
+ */
127
+ export declare function validateLiveQueryPolicy(policy: LiveQueryPolicy | undefined): void;
128
+ export declare function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryManager;
129
+ export {};
130
+ //# sourceMappingURL=live-query-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-query-manager.d.ts","sourceRoot":"","sources":["../../src/worker/live-query-manager.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,aAAa,EAA+B,MAAM,2BAA2B,CAAC;AAK5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnC,8GAA8G;AAC9G,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;AAE5D,sGAAsG;AACtG,MAAM,WAAW,cAAc;IAC7B,8GAA8G;IAC9G,cAAc,CAAC,IAAI,EAAE,SAAS,GAAG,EAAE,GAAG,IAAI,CAAC;IAC3C,0EAA0E;IAC1E,WAAW,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;CACvC;AAED,wGAAwG;AACxG,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,MAAM,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;;OAIG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,0FAA0F;IAC1F,QAAQ,EAAE,OAAO,CAAC;IAClB,uGAAuG;IACvG,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,SAAS,EAAE,MAAM,CAAC;IAClB,8EAA8E;IAC9E,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,2FAA2F;IAC3F,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAClF,oGAAoG;IACpG,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,iGAAiG;IACjG,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,wEAAwE;IACxE,eAAe,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,IAAI,EAAE,aAAa,EAAE,UAAU,EAAE,cAAc,EAAE,IAAI,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACnH,0GAA0G;IAC1G,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB;;;;OAIG;IACH,QAAQ,IAAI,oBAAoB,EAAE,CAAC;CACpC;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,GAAG,IAAI,CAsBjF;AAyCD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB,CA8WnF"}
@@ -176,7 +176,7 @@ export interface TokenResponsePayload {
176
176
  * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors
177
177
  * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).
178
178
  */
179
- export type RpcOp = "create" | "update" | "delete" | "batch" | "transaction" | "flush" | "reconcile" | "retryFailed" | "recoverSending" | "discardConflict" | "discardQuarantined" | "desync" | "discardEphemeral" | "readMutationDetails" | "diagnostics" | "rawQuery" | "rawExec" | "bootReport" | "exportStore" | "exportDiagnostics" | "exportData";
179
+ export type RpcOp = "create" | "update" | "delete" | "batch" | "transaction" | "flush" | "reconcile" | "retryFailed" | "recoverSending" | "discardConflict" | "discardQuarantined" | "desync" | "discardEphemeral" | "readMutationDetails" | "diagnostics" | "rawQuery" | "rawExec" | "bootReport" | "liveQueryDiagnostics" | "exportStore" | "exportDiagnostics" | "exportData";
180
180
  /** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
181
181
  export interface RpcPayload {
182
182
  op: RpcOp;
@@ -234,6 +234,14 @@ export interface SubscribePayload {
234
234
  pkColumns?: string[];
235
235
  /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */
236
236
  use?: string[];
237
+ /**
238
+ * Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long
239
+ * the shared registration should be retained after this subscription's last consumer leaves, so a matching
240
+ * resubscribe reuses it verbatim. ADDITIVE and backward-compatible both directions — an older tab omits it
241
+ * (the worker falls back to its `liveQueries.defaultKeepAliveMs`), and an older worker ignores it. Absent
242
+ * means "no hint".
243
+ */
244
+ keepAliveMs?: number;
237
245
  }
238
246
  /** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */
239
247
  export interface LiveInitialPayload {
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/worker/protocol.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;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C;IAAC,QAAQ,CAAC,EAAE,kBAAkB,EAAE,CAAA;CAAE,CAU/D;AAED,mHAAmH;AACnH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,cAAc,CAOtE;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,UAAU,EAChB,KAAK,EAAE,WAAW,EAClB,IAAI,EAAE,iBAAiB,EACvB,OAAO,EAAE,OAAO,EAChB,EAAE,CAAC,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,kBAAkB,EAAE,GAC9B,IAAI,CAQN"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/client",
3
- "version": "0.1.48",
3
+ "version": "0.1.49",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -36,7 +36,7 @@
36
36
  "@electric-sql/client": "^1.5.24",
37
37
  "@electric-sql/experimental": "^6.0.24",
38
38
  "@electric-sql/pglite-tools": "0.4.4",
39
- "@pgxsinkit/contracts": "0.1.48"
39
+ "@pgxsinkit/contracts": "0.1.49"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@electric-sql/pglite": "0.5.4",
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: core
15
15
  library: "@pgxsinkit/client"
16
- library_version: "0.1.48"
16
+ library_version: "0.1.49"
17
17
  source: https://pgxsinkit.github.io/llms-full.txt
18
18
  ---
19
19
 
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: task
15
15
  library: "@pgxsinkit/client"
16
- library_version: "0.1.48"
16
+ library_version: "0.1.49"
17
17
  source: https://pgxsinkit.github.io/start/operating-in-production/
18
18
  ---
19
19
 
@@ -153,6 +153,34 @@ shows nothing" is worker mode working as designed, not an absence of requests. I
153
153
  rejections surface only there). Full model:
154
154
  <https://pgxsinkit.github.io/concepts/worker-mode/>.
155
155
 
156
+ ## Live-query manager: dedup + keep-alive (ADR-0040)
157
+
158
+ Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
159
+ query**: PGlite materialises it once, then re-runs + diffs it on every write to its tables. That registration
160
+ is a real cost — ~a few hundred ms to materialise a heavy aggregate — and is **automatically deduplicated**:
161
+ identical queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run +
162
+ diff per write, fanned to every subscriber. So N components — or N tabs on the shared worker — on the same
163
+ query cost one materialisation, not N. You do nothing to get this.
164
+
165
+ Default lifetime is route-scoped: a live query is torn down the instant its last consumer unmounts, so a
166
+ navigate-away-and-back RE-materialises it. Opt a genuinely hot query into a grace period with a per-hook hint
167
+ `useLiveDrizzleRows(build, deps, { keepAliveMs: 30_000 })` (or the raw-hook / `subscribeLiveRows` field), or
168
+ set a worker/client-wide policy `defineSyncWorker({ …, liveQueries: { defaultKeepAliveMs, maxRetainedQueries,
169
+ maxRetainedRows } })` (defaults `0` / `16` / `50_000`; same block on `createSyncClient`). The effective
170
+ keep-alive is `max(default, subscribers' hints)`; the count/row budgets are authoritative over any hint and
171
+ LRU-evict zero-subscriber entries past them; active (still-subscribed) entries are never evicted.
172
+
173
+ **Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused —
174
+ PGlite live queries can't be — so it still pays a full re-run + diff on every write to its tables for as long
175
+ as it's held. Retention wins only for a frequently-re-mounted, write-COLD query; for a write-hot one it costs
176
+ more idle than the one re-materialisation it saves. For a fixed hot set, the endorsed "permanent" pattern is a
177
+ **mounted subscriber** (a root-provider hook that never unmounts) — one live registration for the app's life,
178
+ every route dedups onto it — not a retention setting; there is deliberately no retain-forever knob.
179
+
180
+ `client.liveQueryDiagnostics()` returns a per-entry snapshot — fingerprint DIGEST (never SQL/params/rows),
181
+ subscriber + row counts, setup/refresh timings, retention state — safe to log. The manager also emits
182
+ `live-query register|dedup-hit|retained|evicted|teardown-complete` lines on the debug rail (digests only).
183
+
156
184
  ## Store naming, backups, and restore (ADR-0035/0036)
157
185
 
158
186
  **Stores are named by a plain `storePath`, never a storage URL.** The backend is derived (browser/worker →
package/src/index.ts CHANGED
@@ -71,6 +71,13 @@ import {
71
71
  } from "./store-path";
72
72
  import { createSyncEngine, type SyncEngine } from "./sync";
73
73
  import { buildShapeHeaders } from "./sync-auth";
74
+ import { LiveRowsMaterializer } from "./worker/live-diff";
75
+ import {
76
+ createLiveQueryManager,
77
+ type LiveQueryDiagnostics,
78
+ type LiveQueryManager,
79
+ validateLiveQueryPolicy,
80
+ } from "./worker/live-query-manager";
74
81
 
75
82
  export { generateLocalSchemaSql };
76
83
  export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
@@ -140,6 +147,7 @@ export {
140
147
  rowKey,
141
148
  seedLiveDiffState,
142
149
  } from "./worker/live-diff";
150
+ export type { LiveQueryDiagnostics };
143
151
  export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
144
152
  export {
145
153
  type AttachAckPayload,
@@ -490,6 +498,18 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
490
498
  * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
491
499
  */
492
500
  provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
501
+ /**
502
+ * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4) — same block as
503
+ * {@link DefineSyncWorkerOptions.liveQueries}. Takes effect in BOTH client forms: the in-process client
504
+ * now owns its own manager (decision 6), so this policy governs its live-query dedup and retention just as
505
+ * it does the worker's. Defaults: `defaultKeepAliveMs` 0 (tear a query down the instant its last consumer
506
+ * leaves), `maxRetainedQueries` 16, `maxRetainedRows` 50_000.
507
+ */
508
+ liveQueries?: {
509
+ defaultKeepAliveMs?: number;
510
+ maxRetainedQueries?: number;
511
+ maxRetainedRows?: number;
512
+ };
493
513
  }
494
514
 
495
515
  export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
@@ -615,6 +635,13 @@ export interface SubscribeLiveRowsInput {
615
635
  * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
616
636
  */
617
637
  use?: readonly string[];
638
+ /**
639
+ * Per-subscription keep-alive hint (ms) for the live-query manager (ADR-0040 decision 4): retain this
640
+ * query's shared registration for the grace period after its last consumer leaves, so a re-mount reuses it
641
+ * verbatim (no re-materialization). Honoured in BOTH modes — the worker manager and the in-process manager
642
+ * (decision 6). Bounded by the `liveQueries` policy budgets. Absent → no hint.
643
+ */
644
+ keepAliveMs?: number;
618
645
  }
619
646
 
620
647
  /** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
@@ -866,6 +893,13 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
866
893
  * stored report. The push counterpart is the `onBootReport` client option.
867
894
  */
868
895
  bootReport: () => Promise<BootReport | null>;
896
+ /**
897
+ * Live-query diagnostics (ADR-0040 decision 5): a point-in-time snapshot of the live-query manager's
898
+ * entries — opaque fingerprint digests plus counts/timings only, NEVER SQL, params, or row values. Both
899
+ * client forms return the real snapshot: in WORKER mode this pulls the worker manager's snapshot over the
900
+ * bridge; the IN-PROCESS client returns its own manager's snapshot directly.
901
+ */
902
+ liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
869
903
  /**
870
904
  * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
871
905
  * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
@@ -953,6 +987,8 @@ export function replAdapter(
953
987
  export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
954
988
  options: CreateSyncClientOptions<TRegistry>,
955
989
  ): Promise<SyncClient<TRegistry>> {
990
+ // Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
991
+ validateLiveQueryPolicy(options.liveQueries);
956
992
  const status: SyncRuntimeStatus = {
957
993
  phase: "booting",
958
994
  isRunning: false,
@@ -1741,6 +1777,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1741
1777
  return builder;
1742
1778
  };
1743
1779
 
1780
+ // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
1781
+ // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
1782
+ // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
1783
+ // settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).
1784
+ // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.
1785
+ const liveManager: LiveQueryManager = createLiveQueryManager({
1786
+ live: pglite.live,
1787
+ ...(options.liveQueries ? { policy: options.liveQueries } : {}),
1788
+ });
1789
+
1744
1790
  const client: SyncClient<TRegistry> = {
1745
1791
  drizzle: drizzleDb,
1746
1792
  pglite,
@@ -1775,6 +1821,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1775
1821
  // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
1776
1822
  // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
1777
1823
  await engine.close();
1824
+ // Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any
1825
+ // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
1826
+ await liveManager.dispose();
1778
1827
  await pglite.close();
1779
1828
  },
1780
1829
  destroy: (destroyOptions) =>
@@ -1809,6 +1858,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1809
1858
  // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1810
1859
  // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1811
1860
  await engine.close();
1861
+ // Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as
1862
+ // `stop()` (ADR-0040 decisions 1 & 6).
1863
+ await liveManager.dispose();
1812
1864
  await pglite.close();
1813
1865
  }),
1814
1866
  dropReadCache: () =>
@@ -1856,20 +1908,39 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1856
1908
  transaction,
1857
1909
  groupReady: groupReadyForTable,
1858
1910
  hydratingTablesFor,
1859
- // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React
1860
- // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
1861
- // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
1862
- // incrementally against its own materialized state; the column set only matters for the worker bridge.
1863
- subscribeLiveRows: async ({ sql, params, fields, use }, onRows) => {
1911
+ // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical
1912
+ // contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent
1913
+ // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff
1914
+ // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a
1915
+ // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
1916
+ // public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
1917
+ // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
1918
+ // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.
1919
+ subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
1864
1920
  // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
1865
1921
  // temp-view creation (`column "title" specified more than once`) unless every output column has a
1866
- // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
1922
+ // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays
1923
+ // caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.
1867
1924
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
1868
- const registered = await pglite.live.query<Record<string, unknown>>(materialSql, params as unknown[]);
1869
- const listener = (results: { rows: Record<string, unknown>[] }) => {
1870
- onRows(results.rows as never);
1871
- };
1872
- registered.subscribe(listener);
1925
+ // Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;
1926
+ // each diff folds into a fresh ordered array whose unchanged rows keep their object identity.
1927
+ const materializer = new LiveRowsMaterializer<Record<string, unknown>>(undefined);
1928
+ const subscription = await liveManager.subscribe(
1929
+ { materialSql, params: params as unknown[] },
1930
+ {
1931
+ // The initial snapshot is returned via `initialRows`, NOT `onRows` (which fires on CHANGES only) —
1932
+ // so `deliverInitial` just seeds the materializer; `initialRows` is read from it below.
1933
+ deliverInitial: (rows) => {
1934
+ materializer.seed(rows);
1935
+ },
1936
+ deliverDiff: (diff) => {
1937
+ onRows(materializer.apply(diff) as never);
1938
+ },
1939
+ },
1940
+ keepAliveMs != null ? { keepAliveMs } : undefined,
1941
+ );
1942
+ // Seeded synchronously by `deliverInitial` during `subscribe` above.
1943
+ const initialRows = materializer.current();
1873
1944
  let unsubscribed = false;
1874
1945
  // The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)
1875
1946
  // are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.
@@ -1880,22 +1951,25 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1880
1951
  // yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a
1881
1952
  // post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build
1882
1953
  // `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live
1883
- // query against the caught-up store (its listener delivers the rows synchronously inside the refresh),
1884
- // THEN resolve — so a UI flipping out of its loading state on this promise can never flash a false empty.
1954
+ // query (the manager's coalesced refresh; its listener delivers the caught-up rows as a diff → onRows,
1955
+ // synchronously inside the refresh), THEN resolve — so a UI flipping out of its loading state on this
1956
+ // promise can never flash a false empty.
1885
1957
  const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });
1886
1958
  const hydrated =
1887
1959
  hydratingTables.length > 0
1888
1960
  ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))
1889
1961
  .then(async () => {
1890
- if (!unsubscribed) await registered.refresh();
1962
+ if (!unsubscribed) await subscription.refresh();
1891
1963
  })
1892
1964
  .catch(() => undefined)
1893
1965
  : undefined;
1894
1966
  return {
1895
- initialRows: registered.initialResults.rows as never,
1967
+ initialRows: initialRows as never,
1896
1968
  unsubscribe: () => {
1897
1969
  unsubscribed = true;
1898
- void registered.unsubscribe(listener);
1970
+ // Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
1971
+ // `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).
1972
+ void subscription.unsubscribe();
1899
1973
  },
1900
1974
  ...(lazyTables.length > 0 ? { lazyTables } : {}),
1901
1975
  ...(hydrated ? { hydrated } : {}),
@@ -1904,6 +1978,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1904
1978
  // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
1905
1979
  // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.
1906
1980
  bootReport: async () => finalizedBootReport,
1981
+ // Live-query diagnostics (ADR-0040 decisions 5 & 6): the in-process client now owns a real manager, so
1982
+ // this returns its live snapshot (digests + counts/timings only — never SQL/params/rows).
1983
+ liveQueryDiagnostics: async () => liveManager.snapshot(),
1907
1984
  exportStore: async (exportOptions) => {
1908
1985
  // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
1909
1986
  // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.