@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,215 @@
1
+ import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
+ import type { InsertChangeMessage, Lsn } from "./types";
3
+ /**
4
+ * The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's
5
+ * Electric subscription and the Sync applier. It buffers each shape's change messages keyed by
6
+ * LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the
7
+ * applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014
8
+ * per-PK fold that will live here) property-testable against an ordered per-row apply oracle.
9
+ *
10
+ * One inbox owns all shapes in a consistency group; the group commits atomically at the lowest
11
+ * complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays
12
+ * with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).
13
+ *
14
+ * COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live
15
+ * here and they are deliberately NOT the same number:
16
+ *
17
+ * - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below
18
+ * it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor
19
+ * (below) but above its raw frontier is still buffered, never dropped.
20
+ * - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see
21
+ * {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in
22
+ * {@link lowestCompleteLsn}; it never gates ingestion.
23
+ *
24
+ * Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable
25
+ * (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its
26
+ * `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up
27
+ * can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the
28
+ * group min-frontier below changes already delivered on the busy shape, holding them buffered until the
29
+ * quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The
30
+ * alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at
31
+ * catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose
32
+ * cached catch-up omitted it is still ingested and committed rather than dropped.
33
+ */
34
+ export declare class ShapeInbox {
35
+ private readonly changes;
36
+ private readonly completeLsns;
37
+ private readonly moveOuts;
38
+ private readonly moveIns;
39
+ private readonly epochs;
40
+ private readonly snapshotAccepted;
41
+ private readonly upToDateSeen;
42
+ private readonly lastUpToDateLsn;
43
+ private readonly commitFloors;
44
+ private aligned;
45
+ private lastAlignedFloor;
46
+ constructor(shapeNames: Iterable<string>);
47
+ /**
48
+ * Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from
49
+ * registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The
50
+ * commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver
51
+ * them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.
52
+ */
53
+ acceptsSnapshotRowsFor(shapeName: string): boolean;
54
+ /** The complete-LSN frontier for one shape (the already-seen dedup threshold). */
55
+ completeLsnFor(shapeName: string): Lsn;
56
+ /**
57
+ * The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it
58
+ * back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so
59
+ * the reset's own truncate+rebuild path owns that shape's post-reset state.
60
+ */
61
+ epochFor(shapeName: string): number;
62
+ /**
63
+ * Buffer a change message. A message at or below the shape's current complete frontier is
64
+ * already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.
65
+ */
66
+ ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void;
67
+ /** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */
68
+ commitFloorFor(shapeName: string): Lsn;
69
+ /**
70
+ * A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —
71
+ * the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity
72
+ * {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),
73
+ * and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.
74
+ */
75
+ effectiveLsnFor(shapeName: string): Lsn;
76
+ /**
77
+ * Whether this shape has reported `up-to-date` at least once since registration / its last
78
+ * {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:
79
+ * a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.
80
+ */
81
+ hasReportedUpToDate(shapeName: string): boolean;
82
+ /** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */
83
+ alignedFloor(): Lsn;
84
+ /**
85
+ * Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the
86
+ * one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.
87
+ *
88
+ * Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on
89
+ * that transition); `false` on every other call.
90
+ */
91
+ ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean;
92
+ /** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */
93
+ ingestMoveOut(shapeName: string, patterns: MovePattern[]): void;
94
+ /** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */
95
+ drainMoveOuts(shapeName: string): MovePattern[][];
96
+ /**
97
+ * Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs
98
+ * with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)
99
+ * only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the
100
+ * revocations buffered rather than silently losing them.
101
+ */
102
+ peekMoveOuts(shapeName: string): MovePattern[][];
103
+ /**
104
+ * Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit
105
+ * that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the
106
+ * peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)
107
+ * buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a
108
+ * {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so
109
+ * this no-ops rather than splicing the post-reset replacement.
110
+ */
111
+ ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void;
112
+ /** Whether any shape has a buffered `move-out` awaiting a commit. */
113
+ hasPendingMoveOuts(): boolean;
114
+ /** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */
115
+ ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void;
116
+ /** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */
117
+ drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
118
+ /** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */
119
+ peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
120
+ /**
121
+ * Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see
122
+ * {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a
123
+ * mid-commit {@link resetShape}), so the post-reset replacement rows survive.
124
+ */
125
+ ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void;
126
+ /** Whether any shape has a buffered `move-in` awaiting a commit. */
127
+ hasPendingMoveIns(): boolean;
128
+ /** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */
129
+ resetShape(shapeName: string): void;
130
+ /**
131
+ * The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's
132
+ * effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup
133
+ * frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global
134
+ * head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy
135
+ * shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'
136
+ * first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw
137
+ * {@link completeLsns}), so a late sub-floor change is still ingested and then committed.
138
+ */
139
+ lowestCompleteLsn(): Lsn;
140
+ /**
141
+ * Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit
142
+ * loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed
143
+ * target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change
144
+ * below the floor while the group frontier already sits at (or above) it, so no new frontier advance
145
+ * would otherwise trigger a commit for it.
146
+ */
147
+ hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean;
148
+ /**
149
+ * Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN
150
+ * order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs
151
+ * with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks
152
+ * (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)
153
+ * holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.
154
+ */
155
+ peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
156
+ /**
157
+ * Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a
158
+ * matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured
159
+ * at peek time; a shape whose epoch has since changed is **skipped entirely**.
160
+ *
161
+ * The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only
162
+ * advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit
163
+ * {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at
164
+ * LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop
165
+ * the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.
166
+ */
167
+ ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void;
168
+ /** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */
169
+ snapshotEpochs(): Map<string, number>;
170
+ /**
171
+ * Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order
172
+ * ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty
173
+ * array where nothing drained).
174
+ */
175
+ drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
176
+ }
177
+ /**
178
+ * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
179
+ * Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a
180
+ * *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk
181
+ * apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs
182
+ * three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is
183
+ * what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest
184
+ * of the order is irrelevant within the atomic commit.
185
+ */
186
+ export interface FoldedShapeBatch {
187
+ /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
188
+ deletes: ChangeMessage<Row<unknown>>[];
189
+ /** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */
190
+ inserts: InsertChangeMessage[];
191
+ /** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */
192
+ updates: ChangeMessage<Row<unknown>>[];
193
+ }
194
+ /**
195
+ * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
196
+ * (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …
197
+ * SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when
198
+ * the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:
199
+ *
200
+ * - **trailing `delete`** ⇒ a single DELETE;
201
+ * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
202
+ * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);
203
+ * - **only `update`s** ⇒ a single UPDATE with merged values;
204
+ * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
205
+ * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
206
+ * would collide with the row the dropped delete was meant to remove);
207
+ * - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream
208
+ * (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently
209
+ * dropping it.
210
+ *
211
+ * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
212
+ * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
213
+ */
214
+ export declare function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch;
215
+ //# sourceMappingURL=shape-inbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shape-inbox.d.ts","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,IAAI,OAAO,CAK3B;IAED,wGAAwG;IACxG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAmBlC;IAED;;;;;;;;OAQG;IACH,iBAAiB,IAAI,GAAG,CASvB;IAED;;;;;;OAMG;IACH,2BAA2B,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CASnD;IAED;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAgBnE;IAED;;;;;;;;;;OAUG;IACH,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAY/D;IAED,sGAAsG;IACtG,cAAc,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAEpC;IAED;;;;OAIG;IACH,SAAS,CAAC,SAAS,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAKpE;CACF;AAID;;;;;;;;GAQG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;IACvC,mGAAmG;IACnG,OAAO,EAAE,mBAAmB,EAAE,CAAC;IAC/B,mGAAmG;IACnG,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;CACxC;AAgBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAgBzF"}
@@ -0,0 +1,39 @@
1
+ import type { Offset } from "@electric-sql/client";
2
+ import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
3
+ import { type Lsn, type SubscriptionKey } from "./types";
4
+ export interface SubscriptionState {
5
+ key: SubscriptionKey;
6
+ shape_metadata: Record<string, ShapeSubscriptionState>;
7
+ last_lsn: Lsn;
8
+ }
9
+ export interface ShapeSubscriptionState {
10
+ handle: string;
11
+ offset: Offset;
12
+ }
13
+ export interface GetSubscriptionStateOptions {
14
+ readonly pg: PGliteInterface | Transaction;
15
+ readonly metadataSchema: string;
16
+ readonly subscriptionKey: SubscriptionKey;
17
+ }
18
+ export declare function getSubscriptionState({ pg, metadataSchema, subscriptionKey, }: GetSubscriptionStateOptions): Promise<SubscriptionState | null>;
19
+ export interface UpdateSubscriptionStateOptions {
20
+ pg: PGliteInterface | Transaction;
21
+ metadataSchema: string;
22
+ subscriptionKey: SubscriptionKey;
23
+ shapeMetadata: Record<string, ShapeSubscriptionState>;
24
+ lastLsn: Lsn;
25
+ debug?: boolean;
26
+ }
27
+ export declare function updateSubscriptionState({ pg, metadataSchema, subscriptionKey, shapeMetadata, lastLsn, debug, }: UpdateSubscriptionStateOptions): Promise<void>;
28
+ export interface DeleteSubscriptionStateOptions {
29
+ pg: PGliteInterface | Transaction;
30
+ metadataSchema: string;
31
+ subscriptionKey: SubscriptionKey;
32
+ }
33
+ export declare function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions): Promise<void>;
34
+ export interface MigrateSubscriptionMetadataTablesOptions {
35
+ pg: PGliteInterface | Transaction;
36
+ metadataSchema: string;
37
+ }
38
+ export declare function migrateSubscriptionMetadataTables({ pg, metadataSchema, }: MigrateSubscriptionMetadataTablesOptions): Promise<void>;
39
+ //# sourceMappingURL=subscription-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/sync/subscription-state.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,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e,EAAE,EAAE,8BAA8B,iBAGpH;AAED,MAAM,WAAW,wCAAwC;IACvD,EAAE,EAAE,eAAe,GAAG,WAAW,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,wBAAsB,iCAAiC,CAAC,EACtD,EAAE,EACF,cAAc,GACf,EAAE,wCAAwC,iBAc1C"}
@@ -0,0 +1,130 @@
1
+ import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
+ import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
3
+ import type { ApplyTarget } from "../local-tables";
4
+ /**
5
+ * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
6
+ * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)
7
+ * streams two extra things the plain change path ignores:
8
+ *
9
+ * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per
10
+ * grant/membership), plus `removed_tags` on an update;
11
+ * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — "the tag whose component at
12
+ * index `pos` equals `value` is withdrawn", i.e. that grant was revoked.
13
+ *
14
+ * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`
15
+ * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one
16
+ * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an
17
+ * Electric change.
18
+ *
19
+ * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:
20
+ * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.
21
+ */
22
+ /**
23
+ * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.
24
+ * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so
25
+ * the desync path (which is outside the engine) can key the tag store by this same constant.
26
+ */
27
+ export declare const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
28
+ /**
29
+ * Validate the metadata schema name at engine construction. The name is interpolated RAW into two
30
+ * positions a double-quoted identifier cannot cover:
31
+ * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
32
+ * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
33
+ * accept a quoted identifier the way a table/column position does, so the name cannot be safely
34
+ * quoted there.
35
+ * - the `CREATE SCHEMA <schema>` DDL identifier position.
36
+ * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
37
+ * lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
38
+ */
39
+ export declare function assertValidMetadataSchema(metadataSchema: string): void;
40
+ /**
41
+ * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config
42
+ * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by
43
+ * `migrateSubscriptionMetadataTables`, which renders that same pgTable.
44
+ */
45
+ export declare function shapeRowTagsTableName(metadataSchema: string): string;
46
+ /** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
47
+ export declare function shapeTableId(schema: string | undefined, table: string): string;
48
+ /**
49
+ * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
50
+ * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
51
+ * caller/test that builds the local schema without booting the sync engine that creates the store). The
52
+ * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
53
+ * guarded.
54
+ */
55
+ export declare function buildClearShapeTagsSql(shapeTable: string, metadataSchema?: string): string;
56
+ /**
57
+ * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
58
+ * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
59
+ * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
60
+ */
61
+ export declare function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string;
62
+ /**
63
+ * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
64
+ * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
65
+ * two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
66
+ * `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
67
+ *
68
+ * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
69
+ * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
70
+ */
71
+ export declare function splitTagComponents(tag: string): string[];
72
+ /**
73
+ * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
74
+ * of the shape's tag structure (one position per subquery condition that references it), so the event
75
+ * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
76
+ * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
77
+ * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
78
+ * matches nothing.
79
+ */
80
+ export declare function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean;
81
+ interface TagSyncOptions {
82
+ pg: PGliteInterface | Transaction;
83
+ metadataSchema: string;
84
+ shapeTable: string;
85
+ messages: ChangeMessage<Row<unknown>>[];
86
+ primaryKey: string[];
87
+ }
88
+ /**
89
+ * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
90
+ * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
91
+ * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
92
+ * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
93
+ * eviction in the same commit, so an add-then-remove within one batch resolves correctly.
94
+ */
95
+ export declare function applyShapeTagSync({ pg, metadataSchema, shapeTable, messages, primaryKey, }: TagSyncOptions): Promise<void>;
96
+ /**
97
+ * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
98
+ * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
99
+ * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
100
+ * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
101
+ * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
102
+ * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
103
+ * A row with no `tags` (a non-subquery shape) is a no-op.
104
+ */
105
+ export declare function addShapeRowTags({ pg, metadataSchema, shapeTable, messages, primaryKey, }: TagSyncOptions): Promise<void>;
106
+ interface MoveOutOptions {
107
+ pg: PGliteInterface | Transaction;
108
+ metadataSchema: string;
109
+ shapeTable: string;
110
+ /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
111
+ target: ApplyTarget;
112
+ /** One entry per buffered `move-out` event, each its own pattern set. */
113
+ patternSets: MovePattern[][];
114
+ debug: boolean;
115
+ }
116
+ /**
117
+ * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
118
+ * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
119
+ * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
120
+ * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
121
+ */
122
+ export declare function applyShapeMoveOut({ pg, metadataSchema, shapeTable, target, patternSets, debug, }: MoveOutOptions): Promise<number>;
123
+ /** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
124
+ export declare function clearShapeTags({ pg, metadataSchema, shapeTable, }: {
125
+ pg: PGliteInterface | Transaction;
126
+ metadataSchema: string;
127
+ shapeTable: string;
128
+ }): Promise<void>;
129
+ export {};
130
+ //# sourceMappingURL=tags.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/sync/tags.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAMzE,OAAO,KAAK,EAAE,W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A2ChC;AAED;;;;;;;;GAQG;AACH,wBAAsB,eAAe,CAAC,EACpC,EAAE,EACF,cAAc,EACd,UAAU,EACV,QAAQ,EACR,UAAU,GACX,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAehC;AAED,UAAU,cAAc;IACtB,EAAE,EAAE,eAAe,GAAG,WAAW,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,sGAAsG;IACtG,MAAM,EAAE,WAAW,CAAC;IACpB,yEAAyE;IACzE,WAAW,EAAE,WAAW,EAAE,EAAE,CAAC;IAC7B,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,EAAE,EACF,cAAc,EACd,UAAU,EACV,MAAM,EACN,WAAW,EACX,KAAK,GACN,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CA0ElC;AAED,0HAA0H;AAC1H,wBAAsB,cAAc,CAAC,EACnC,EAAE,EACF,cAAc,EACd,UAAU,GACX,EAAE;IACD,EAAE,EAAE,eAAe,GAAG,WAAW,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGhB"}
@@ -0,0 +1,126 @@
1
+ import type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from "@electric-sql/client";
2
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
3
+ import type { SyncTableRegistry } from "@pgxsinkit/contracts";
4
+ import type { GroupBootStamp } from "../boot-report";
5
+ export type { Row, ShapeStreamOptions } from "@electric-sql/client";
6
+ export type { MultiShapeMessages } from "@electric-sql/experimental";
7
+ export type Lsn = bigint;
8
+ export type SubscriptionKey = string;
9
+ export type InitialInsertMethod = "insert" | "copy" | "json";
10
+ /** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */
11
+ export declare const DEFAULT_MAX_COMMIT_RETRIES = 5;
12
+ /**
13
+ * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,
14
+ * projection, primary keys, apply strategy, column types — is derived by the engine from the
15
+ * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape
16
+ * stream, an optional per-shape backfill override, and the must-refetch hook remain.
17
+ */
18
+ export interface ShapeToTableOptions {
19
+ shape: ShapeStreamOptions<Row<unknown>>;
20
+ /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */
21
+ tableKey: string;
22
+ /**
23
+ * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle
24
+ * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①
25
+ * (`db.delete(table).where(…)`).
26
+ */
27
+ onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
28
+ /**
29
+ * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency
30
+ * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto
31
+ * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is
32
+ * derived from the entry and mapped, else the group-level default applies.
33
+ */
34
+ initialInsertMethod?: InitialInsertMethod | undefined;
35
+ }
36
+ export interface SyncShapesToTablesOptions {
37
+ key: string | null;
38
+ /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */
39
+ registry: SyncTableRegistry;
40
+ shapes: Record<string, ShapeToTableOptions>;
41
+ initialInsertMethod?: InitialInsertMethod | undefined;
42
+ onInitialSync?: (() => void) | undefined;
43
+ /**
44
+ * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a
45
+ * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine
46
+ * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the
47
+ * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and
48
+ * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it
49
+ * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so
50
+ * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the
51
+ * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior
52
+ * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the
53
+ * `freshStore` gate guarantees.
54
+ */
55
+ dbReady?: Promise<void> | undefined;
56
+ /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */
57
+ onError?: ((error: FetchError | Error) => void) | undefined;
58
+ /**
59
+ * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction
60
+ * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its
61
+ * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the
62
+ * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.
63
+ */
64
+ onSyncError?: ((error: Error) => void) | undefined;
65
+ /**
66
+ * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).
67
+ * The runtime uses this as the read path's "alive again" signal to clear an `auth-needed` status
68
+ * once sync resumes after re-authentication.
69
+ */
70
+ onSyncActivity?: (() => void) | undefined;
71
+ /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
72
+ maxCommitRetries?: number | undefined;
73
+ /**
74
+ * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to
75
+ * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an
76
+ * immediate retry instead of sleeping the real backoff.
77
+ */
78
+ commitRetryDelayMs?: ((attempt: number) => number) | undefined;
79
+ /**
80
+ * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
81
+ * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
82
+ * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
83
+ * boot without report instrumentation.
84
+ */
85
+ bootStamp?: GroupBootStamp | undefined;
86
+ }
87
+ export interface SyncShapesToTablesResult {
88
+ unsubscribe: () => void;
89
+ readonly isUpToDate: boolean;
90
+ streams: Record<string, ShapeStreamInterface<Row<unknown>>>;
91
+ }
92
+ /**
93
+ * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based
94
+ * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.
95
+ */
96
+ export interface SyncShapeToTableOptions {
97
+ shape: ShapeStreamOptions<Row<unknown>>;
98
+ registry: SyncTableRegistry;
99
+ tableKey: string;
100
+ shapeKey: string | null;
101
+ initialInsertMethod?: InitialInsertMethod | undefined;
102
+ onInitialSync?: (() => void) | undefined;
103
+ onError?: ((error: FetchError | Error) => void) | undefined;
104
+ /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */
105
+ onSyncError?: ((error: Error) => void) | undefined;
106
+ /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
107
+ maxCommitRetries?: number | undefined;
108
+ /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */
109
+ commitRetryDelayMs?: ((attempt: number) => number) | undefined;
110
+ onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
111
+ }
112
+ export interface SyncShapeToTableResult {
113
+ unsubscribe: () => void;
114
+ readonly isUpToDate: boolean;
115
+ stream: ShapeStreamInterface<Row<unknown>>;
116
+ }
117
+ export interface ElectricSyncOptions {
118
+ debug?: boolean;
119
+ metadataSchema?: string;
120
+ }
121
+ export type InsertChangeMessage = ChangeMessage<Row<unknown>> & {
122
+ headers: {
123
+ operation: "insert";
124
+ };
125
+ };
126
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sync/types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EA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AE,UAAU,GAAG,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAC5D,6GAA6G;IAC7G,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACnD,qHAAqH;IACrH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,8GAA8G;IAC9G,kBAAkB,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,SAAS,CAAC;IAC/D,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,CAAC;CACrE;AAED,MAAM,WAAW,sBAAsB;IACrC,WAAW,EAAE,MAAM,IAAI,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,MAAM,EAAE,oBAAoB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;CAC5C;AAED,MAAM,WAAW,mBAAmB;IAClC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,mBAAmB,GAAG,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG;IAC9D,OAAO,EAAE;QAAE,SAAS,EAAE,QAAQ,CAAA;KAAE,CAAC;CAClC,CAAC"}
@@ -0,0 +1,53 @@
1
+ import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
2
+ /** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
3
+ type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
4
+ /**
5
+ * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
6
+ * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
7
+ * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
8
+ * expires.
9
+ *
10
+ * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
11
+ * Electric resolves header-value functions on every request *and every retry*
12
+ * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
13
+ * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
14
+ *
15
+ * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
16
+ * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
17
+ * single-flight, so an N-shape consistency group does not trigger N refreshes.
18
+ */
19
+ /**
20
+ * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
21
+ * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
22
+ * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
23
+ * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
24
+ * whenever *either* a token provider or static headers are present, so a credential-only consumer
25
+ * (no per-request token) still sends its headers.
26
+ */
27
+ export declare function buildShapeHeaders(input: {
28
+ getAuthToken?: () => Promise<string | undefined>;
29
+ requestHeaders?: Record<string, string>;
30
+ }): ExternalHeadersRecord;
31
+ /** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
32
+ export declare function buildAuthShapeHeaders(getAuthToken: () => Promise<string | undefined>, requestHeaders?: Record<string, string>): ExternalHeadersRecord;
33
+ /**
34
+ * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
35
+ * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
36
+ * read-path identity (ADR-0013) and read-stream error surfacing (#4):
37
+ *
38
+ * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
39
+ * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
40
+ * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
41
+ * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
42
+ * makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
43
+ * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
44
+ * of silently believing the read path is live), then retry transient faults ({@link
45
+ * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
46
+ * later successful fetch (`onSyncActivity`) clears the degraded status back to live.
47
+ */
48
+ export declare function createShapeErrorHandler(options?: {
49
+ onAuthError?: () => void;
50
+ onReadStreamError?: (error: Error) => void;
51
+ }): ShapeStreamErrorHandler;
52
+ export {};
53
+ //# sourceMappingURL=sync-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-auth.d.ts","sourceRoot":"","sources":["../src/sync-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAEtF,yFAAyF;AACzF,KAAK,uBAAuB,GAAG,WAAW,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;GAcG;AACH;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC,GAAG,qBAAqB,CAYxB;AAED,wGAAwG;AACxG,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,EAC/C,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACtC,qBAAqB,CAEvB;AAuCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CAAO,GACrF,uBAAuB,CASzB"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker
3
+ * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.
4
+ */
5
+ export interface MemoryStoreForTests {
6
+ storePath: string;
7
+ }
8
+ /**
9
+ * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral
10
+ * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its
11
+ * options accept `storePath`): the client reads the internal marker and selects the memory backend.
12
+ *
13
+ * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the
14
+ * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance
15
+ * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.
16
+ */
17
+ export declare function memoryStoreForTests(storePath: string): MemoryStoreForTests;
18
+ /**
19
+ * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
20
+ * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
21
+ * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.
22
+ *
23
+ * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
24
+ * store voids the retention + journal durability guarantees.
25
+ */
26
+ export declare function testStoreAcknowledgment(): Record<never, never>;
27
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAkBA;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,mBAAmB,CAI1E;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,IAAI,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAG9D"}