@pgxsinkit/client 0.1.51 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. package/src/worker/sw-placement.ts +64 -0
@@ -1,6 +1,9 @@
1
1
  import type { SyncTableRegistry } from "@pgxsinkit/contracts";
2
- import { type ClientPGlite, type CreateSyncClientOptions, type SyncClient } from "../index";
2
+ import { type AdoptionDeclaration, type ClientPGlite, type CreateSyncClientOptions, type SyncClient } from "../index";
3
+ import { type PlacementProbeResult } from "../placement-probe";
4
+ import { type ExecutionLimitConfig } from "./engine-control";
3
5
  import { type BridgeCodec, type BridgePort } from "./protocol";
6
+ import { type SwPlacementResult } from "./sw-placement";
4
7
  export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
5
8
  /**
6
9
  * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
@@ -23,8 +26,19 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
23
26
  * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
24
27
  */
25
28
  createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
29
+ /**
30
+ * ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
31
+ * reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
32
+ * committed OPFS successor. A worker-ENTRY option (baked into the worker file as code, like
33
+ * {@link executionLimit}), NEVER an attach option — a tab cannot set it (adoption DELETES local-only data, so
34
+ * only the code author may authorize it). Forwarded verbatim to the {@link createSyncClient} boot below. DEFAULT
35
+ * OFF (`undefined`): hook absence is never authority — only `"server-reconstructible"` (or the manual
36
+ * `adoptStore` API) authorizes deleting the idb predecessor. Honoured only where the engine home grants OPFS
37
+ * access (SW-direct / elected placement); inert on the browser-idb fallback where there is no opfs successor.
38
+ */
39
+ adoption?: AdoptionDeclaration;
26
40
  electricUrl: string;
27
- writeUrl: string;
41
+ batchWriteUrl: string;
28
42
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
29
43
  requestHeaders?: Record<string, string>;
30
44
  /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
@@ -45,6 +59,15 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
45
59
  * (`flush` + `reconcile` queries). Default 15000.
46
60
  */
47
61
  convergenceIntervalMs?: number;
62
+ /**
63
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5), threaded into the ROUTER when this
64
+ * SharedWorker lands in `elected-worker` placement (router-only mode). DISABLED by default (`undefined` /
65
+ * absent `maxDispatchMs`) — no finite worst-case query duration exists, so an absent limit means the router
66
+ * forwards no probe and queries run unbounded; enabling it is a deliberate consumer choice.
67
+ * Elected placement ONLY: on SW-direct (`shared-worker`) the engine home is in-scope and there is no control
68
+ * channel to probe, so an enabled value is rejected as unsupported before engine boot.
69
+ */
70
+ executionLimit?: ExecutionLimitConfig;
48
71
  /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
49
72
  installGlobal?: boolean;
50
73
  /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
@@ -58,14 +81,41 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
58
81
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
59
82
  /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
60
83
  pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
84
+ /**
85
+ * App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
86
+ * schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
87
+ * timing as the in-process client. This is a worker-ENTRY option (baked into the worker file as code),
88
+ * NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
89
+ * supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
90
+ * a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
91
+ * this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
92
+ *
93
+ * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
94
+ * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
95
+ * runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
96
+ * invariant does not hold there.
97
+ */
98
+ prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
99
+ /**
100
+ * App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
101
+ * exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbAfterSchema}, same timing as the in-process
102
+ * client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
103
+ * tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
104
+ * that depend on the registry's local tables, which DO exist by the time this runs.
105
+ *
106
+ * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
107
+ * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
108
+ */
109
+ prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
61
110
  /**
62
111
  * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
63
112
  * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
64
113
  * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
65
114
  * 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.
115
+ * down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
116
+ * full SQL rerun + diff on every dependent write — PGlite live queries cannot be paused — so retention
117
+ * only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
118
+ * no surprise standing SQL reruns.
69
119
  */
70
120
  liveQueries?: {
71
121
  /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
@@ -90,4 +140,111 @@ export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
90
140
  * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.
91
141
  */
92
142
  export declare function defineSyncWorker<const TRegistry extends SyncTableRegistry>(options: DefineSyncWorkerOptions<TRegistry>): SyncWorkerHost<TRegistry>;
143
+ /**
144
+ * The literal key of the CONTROL-CHANNEL DELIVERY message (ADR-0049 step 9). The spawning coordinator's step-10
145
+ * wiring posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }` on the elected engine worker's IMPLICIT port WITH the
146
+ * engine end of the announce control channel as a transferred `MessagePort`. The engine entry starts that port
147
+ * and runs its control plane on it. Distinct namespace from the data-path bridge envelope and the `pgx0049`
148
+ * control envelope, so it is unambiguous on the shared implicit-port transport.
149
+ */
150
+ export declare const CONTROL_PORT_DELIVERY_KEY: "pgx0049ControlPort";
151
+ /**
152
+ * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per
153
+ * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
154
+ * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
155
+ * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
156
+ *
157
+ * `globalScope` defaults to `globalThis` (the real worker binding); tests inject a fake scope to exercise the
158
+ * dedicated-worker control-plane arm (ADR-0049 step 9) without a real Worker.
159
+ */
160
+ export declare function bindGlobalScope(connect: (port: BridgePort) => void, globalScope?: unknown): void;
161
+ /**
162
+ * The PLACEMENT-QUERY envelope key: a tab posts `{ [PLACEMENT_QUERY_KEY]: true }` on its SharedWorker
163
+ * connection to learn the engine home; the SharedWorker replies `{ [PLACEMENT_RESULT_KEY]: PlacementQueryResult }`.
164
+ * A distinct namespace from the data-path bridge envelope and the `pgx0049` control envelope, so it is
165
+ * unambiguous on the shared tab↔SharedWorker transport (the attach client reads it off the raw message).
166
+ */
167
+ export declare const PLACEMENT_QUERY_KEY: "pgx0049Placement";
168
+ /** The reply to a {@link PLACEMENT_QUERY_KEY} query — carries the engine home, `electionRequired`, and SW id. */
169
+ export declare const PLACEMENT_RESULT_KEY: "pgx0049PlacementResult";
170
+ /**
171
+ * The DESTROY peer-count query key (ADR-0049 D8, plan fault row "`destroy()` with peers attached → refused").
172
+ * A tab about to destroy the store posts `{ [DESTROY_QUERY_KEY]: true }`; the SharedWorker — which alone knows
173
+ * the attached-tab count — replies `{ [DESTROY_VERDICT_KEY]: { peers } }`. `peers` INCLUDES the querying tab, so
174
+ * `peers > 1` means other tabs still hold the store and destruction is refused.
175
+ */
176
+ export declare const DESTROY_QUERY_KEY: "pgx0049DestroyQuery";
177
+ /** The reply to a {@link DESTROY_QUERY_KEY} query — the attached-tab count (querying tab included). */
178
+ export declare const DESTROY_VERDICT_KEY: "pgx0049DestroyVerdict";
179
+ /** The placement a tab learns from the SharedWorker (the reply payload under {@link PLACEMENT_RESULT_KEY}). */
180
+ export interface PlacementQueryResult {
181
+ engineHome: SwPlacementResult["engineHome"];
182
+ /** True in `elected-worker` mode — the tab's election coordinator must spawn the engine worker. */
183
+ electionRequired: boolean;
184
+ swInstanceId: string;
185
+ /**
186
+ * The SharedWorker's OWN script URL (`self.location.href`, ADR-0049 D5). In `elected-worker` mode the winning
187
+ * tab constructs the elected engine as `new Worker(swScriptUrl, { type: "module" })` — the worker entry is
188
+ * dual-scope (one file serves both homes), so no consumer wiring is needed; a `createEngineWorker` override is
189
+ * only for entries that cannot be reconstructed from their URL as a module worker. Absent when the scope cannot
190
+ * report its location (a plain test scope) — then a tab with no override fails attach with a typed wiring error.
191
+ */
192
+ swScriptUrl?: string;
193
+ }
194
+ /** The SharedWorker placement bootstrap's dependencies (all injected so it is unit-testable off-worker). */
195
+ export interface SharedWorkerBootstrapDeps {
196
+ /** The engine host `connect` — used in SW-direct (`shared-worker`) placement to pipe a port to the in-scope engine. */
197
+ connect: (port: BridgePort) => void;
198
+ /** Quiesce and close the in-scope host before SW-direct destruction acknowledges handle release. */
199
+ closeHost?: () => Promise<void>;
200
+ /** Current attached-tab count for the DESTROY verdict in SW-direct mode (the host's own port set). */
201
+ peerCount: () => number;
202
+ /** The opt-in execution limit, threaded into the router in `elected-worker` (router-only) placement. */
203
+ executionLimit?: ExecutionLimitConfig;
204
+ /**
205
+ * The registry declared `backend: "idbfs"` (ADR-0049 D1) — the ONE opt-out. TRUE: skip the probe entirely and
206
+ * bind the in-SharedWorker engine host on the idbfs backend (the declared mode, not a fallback; the placement
207
+ * query answers `electionRequired: false`). FALSE (the default, `backend: "opfs"`): run the UNCONDITIONAL
208
+ * placement probe — a granted verdict boots the engine in-scope on OPFS-repacked, a denied one goes router-only
209
+ * and each tab elects a dedicated engine worker.
210
+ */
211
+ declaredIdbfs?: boolean;
212
+ /** Test seam: inject the placement decision (a fake probe result) instead of the real {@link decideSwPlacement}. */
213
+ decidePlacement?: () => Promise<SwPlacementResult>;
214
+ /** Defaults to `globalThis`; tests inject a fake SharedWorker scope. */
215
+ globalScope?: unknown;
216
+ /**
217
+ * Notified once the placement grant for THIS scope resolves (SharedWorker decision, dedicated-engine probe, or
218
+ * the plain-scope immediate settle). The entry threads `opfsGranted` into its `hasOpfsSyncAccess` boot grant and
219
+ * `engineHome` into the BootReport, and opens its boot gate. `engineHome` is `undefined` for a plain test/Node
220
+ * scope (no home) so the report omits it, exactly as before placement.
221
+ */
222
+ onPlacement?: (outcome: PlacementBootstrapOutcome) => void;
223
+ /**
224
+ * Test seam: inject the DEDICATED elected-engine scope's OPFS probe (a fake verdict) instead of the real
225
+ * {@link probeOpfsSyncAccess}. Defaults to the real probe (invariant 8 — a real `createSyncAccessHandle` open in
226
+ * the engine's own scope, per boot, never sniffed or cached).
227
+ */
228
+ probe?: () => Promise<PlacementProbeResult>;
229
+ }
230
+ /** The resolved placement grant for a worker scope, threaded to the entry's boot grant + BootReport engine home. */
231
+ export interface PlacementBootstrapOutcome {
232
+ /** The engine home for this scope; `undefined` for a plain test/Node scope (the report then omits it). */
233
+ engineHome: SwPlacementResult["engineHome"] | undefined;
234
+ /** True when THIS scope actually holds OPFS sync-access (in-scope SW-direct, or the elected engine's own probe). */
235
+ opfsGranted: boolean;
236
+ /**
237
+ * The verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (ADR-0049 D1/D12, a
238
+ * capability-absence fallback) — stamped into the boot's `storageFallbackReason`. Absent on a granted opfs boot
239
+ * AND on the declared `backend: "idbfs"` mode (the contract, not a fallback).
240
+ */
241
+ storageFallbackReason?: string;
242
+ }
243
+ /**
244
+ * Bootstrap the running worker scope for ADR-0049 placement. A SharedWorker scope runs the placement decision
245
+ * and gates every `onconnect` port on it ({@link wireSharedWorkerPlacement}); any other scope (the dedicated
246
+ * elected-engine worker, or a plain test/Node scope) delegates to {@link bindGlobalScope} unchanged. Called by
247
+ * `defineSyncWorker` in place of the old direct `bindGlobalScope(connect)`.
248
+ */
249
+ export declare function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void;
93
250
  //# sourceMappingURL=define-sync-worker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"define-sync-worker.d.ts","sourceRoot":"","sources":["../../src/worker/define-sync-worker.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AAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAkBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,yBAAyB,GAAG,IAAI,CA4D1E"}
@@ -0,0 +1,95 @@
1
+ /** The prefix every per-store leader lock name carries (CONTEXT "Leader lock"). */
2
+ export declare const LEADER_LOCK_PREFIX = "pgx-leader-";
3
+ /**
4
+ * The per-store leader-lock name: {@link LEADER_LOCK_PREFIX} + the injective store-identity component (D11,
5
+ * invariant 10). Using {@link storeIdentityComponent} keeps the lock name on the SAME one canonical encoding as
6
+ * every other browser-side identity surface (OPFS namespaces, the meta record key, the SharedWorker name), so
7
+ * two distinct store paths can never collapse to one lock (e.g. `"foo/bar"` → `pgx-leader-foo%2Fbar`).
8
+ */
9
+ export declare function leaderLockName(storePath: string): string;
10
+ /** A minimal MessagePort-shaped end — only ever TRANSFERRED across the SW bridge, never called on here. */
11
+ type ControlChannel = {
12
+ port1: unknown;
13
+ port2: unknown;
14
+ };
15
+ /** The tab's SW bridge port (control plane): where the coordinator posts `pgx0049` envelopes and reads acks. */
16
+ export interface SwBridgePort {
17
+ postMessage(message: unknown, transfer?: unknown[]): void;
18
+ addEventListener(type: "message", listener: (event: {
19
+ data: unknown;
20
+ }) => void): void;
21
+ removeEventListener(type: "message", listener: (event: {
22
+ data: unknown;
23
+ }) => void): void;
24
+ }
25
+ export interface CoordinatorDeps {
26
+ /** navigator.locks-shaped, injectable: `request(name, {signal}, callback)` — the callback's returned promise
27
+ HOLDS the lock; resolving it releases the lock, aborting the signal cancels a still-queued request. */
28
+ locks: {
29
+ request(name: string, options: {
30
+ signal?: AbortSignal;
31
+ }, callback: () => Promise<void>): Promise<void>;
32
+ };
33
+ /** Spawn the elected engine worker; returns a handle with `terminate()` and an error-event subscription. */
34
+ spawnEngineWorker: () => {
35
+ terminate(): void;
36
+ onError(listener: (message: string) => void): void;
37
+ };
38
+ /** Create the engine control MessageChannel; default `() => new MessageChannel()` — injectable so tests see
39
+ both ends. The ROUTER end (`port1`) is transferred to the SharedWorker via `engine-announce`; the ENGINE
40
+ end (`port2`) is wired to the elected engine worker in step 9. */
41
+ createControlChannel?: () => ControlChannel;
42
+ /** The tab's SW bridge port (control plane): the coordinator posts `pgx0049` envelopes (leader-granted,
43
+ engine-announce with the transferred control port, engine-retiring, engine-teardown, control-ping) and
44
+ receives control-acks + relocation notices on it. */
45
+ swPort: SwBridgePort;
46
+ /** Reconstruct the SharedWorker via the attach worker FACTORY (ADR-0049 D5) → the NEW swPort. Absent only for a
47
+ bare-instance attach input, where a SharedWorker cannot be rebuilt from itself: keepalive recovery is then
48
+ structurally unavailable (the still-live engine + grant are untouched; recovery narrows to leader-op-or-reload). */
49
+ reconstructSw?: () => SwBridgePort;
50
+ /** Await the VFS ownership release after a deliberate terminate (step 10 wires the real wait; tests fake it). */
51
+ awaitOwnershipRelease: () => Promise<void>;
52
+ timers: {
53
+ setTimeout(fn: () => void, ms: number): unknown;
54
+ clearTimeout(handle: unknown): void;
55
+ };
56
+ /** Page-lifecycle subscription seam (BFCache): `pagehide`/`pageshow`; injectable. */
57
+ pageLifecycle?: {
58
+ onPageHide(listener: (persisted: boolean) => void): void;
59
+ onPageShow(listener: () => void): void;
60
+ };
61
+ }
62
+ export interface ElectionCoordinatorOptions {
63
+ storePath: string;
64
+ /** ms between leader-keepalive pings (default 20000). */
65
+ keepaliveIntervalMs?: number;
66
+ /** consecutive unanswered keepalive pings before SharedWorker reconstruction (default 2). */
67
+ keepaliveMissThreshold?: number;
68
+ /** ms to wait for the teardown ack before terminating anyway (default 3000). */
69
+ teardownAckTimeoutMs?: number;
70
+ }
71
+ export interface ElectionCoordinator {
72
+ /** Claim for a pre-attach provision (optionally expiry-bounded — an abandoned warmed provision retires
73
+ itself when the timer fires). Returns an idempotent release fn (invariant 2). */
74
+ claimForProvision(opts?: {
75
+ expiryMs?: number;
76
+ }): () => void;
77
+ /** Claim for one attachment. Returns an idempotent release fn (invariant 2). */
78
+ claimForAttach(): () => void;
79
+ /** True while this tab holds the granted leader lock. */
80
+ isLeader(): boolean;
81
+ /** True while an elected engine worker handle is held. */
82
+ hasEngine(): boolean;
83
+ /**
84
+ * Deliberately RETIRE this tab's elected engine and resolve once its teardown handshake has completed — the
85
+ * point at which the engine's EXCLUSIVE OPFS sync-access handle is provably released (ADR-0049 D8). The
86
+ * destroy supervisor awaits this BEFORE deleting the backend store so `deleteBackendStore` never races the
87
+ * engine's async handle release (which surfaced as `NoModificationAllowedError`). Runs the retirement notice →
88
+ * `engine-teardown` → ack/timeout → terminate → lock-settle sequence, then awaits the ownership-release seam.
89
+ * A no-op (resolves at once) when this tab holds no engine (not the leader). Idempotent.
90
+ */
91
+ retireEngine(): Promise<void>;
92
+ }
93
+ export declare function createElectionCoordinator(deps: CoordinatorDeps, options: ElectionCoordinatorOptions): ElectionCoordinator;
94
+ export {};
95
+ //# sourceMappingURL=election-coordinator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"election-coordinator.d.ts","sourceRoot":"","sources":["../../src/worker/election-coordinator.ts"],"names":[],"mappings":"AAyCA,mFAAmF;AACnF,eAAO,MAAM,kBAAkB,gBAAgB,CAAC;AAEhD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,2GAA2G;AAC3G,KAAK,cAAc,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAEzD,gHAAgH;AAChH,MAAM,WAAW,YAAY;IAC3B,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC1D,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI,CAAC;IACtF,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAA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AAM,CAAC;IAC7B,6FAA6F;IAC7F,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gFAAgF;IAChF,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,mBAAmB;IAClC;wFACoF;IACpF,iBAAiB,CAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,IAAI,CAAC;IAC5D,gFAAgF;IAChF,cAAc,IAAI,MAAM,IAAI,CAAC;IAC7B,yDAAyD;IACzD,QAAQ,IAAI,OAAO,CAAC;IACpB,0DAA0D;IAC1D,SAAS,IAAI,OAAO,CAAC;IACrB;;;;;;;OAOG;IACH,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;AAuBD,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CA2TrB"}
@@ -0,0 +1,265 @@
1
+ /** Namespaced wire key shared by every placement control-plane participant. */
2
+ export declare const ENGINE_CONTROL_ENVELOPE_KEY: "pgx0049";
3
+ /** Wrap a control message in the namespaced envelope used beside the bridge protocol. */
4
+ export declare function wrapControlEnvelope(message: EngineControlMessage): {
5
+ [ENGINE_CONTROL_ENVELOPE_KEY]: EngineControlMessage;
6
+ };
7
+ /** Read a control message from its namespaced envelope, ignoring unrelated bridge traffic. */
8
+ export declare function readControlEnvelope(data: unknown): EngineControlMessage | undefined;
9
+ /**
10
+ * The PAIR naming one announced engine: the SharedWorker instance that stamped it plus a generation
11
+ * counter that is monotonic ONLY within that one SharedWorker instance (it resets with the SharedWorker).
12
+ * Authority and staleness checks always compare the pair — never the bare counter — because two different
13
+ * SharedWorker instances can each hold a generation `0`.
14
+ */
15
+ export interface EngineIdentity {
16
+ /** Opaque id of the SharedWorker instance that minted this identity. Scopes {@link generation}. */
17
+ swInstanceId: string;
18
+ /** Monotonic counter WITHIN one `swInstanceId`; resets to 0 under a new SharedWorker instance. */
19
+ generation: number;
20
+ }
21
+ /** Two identities are equal only when BOTH fields match (the pair, never the bare counter). */
22
+ export declare function engineIdentityEquals(a: EngineIdentity, b: EngineIdentity): boolean;
23
+ /**
24
+ * Staleness rule (invariant 7): a tagged message is applied ONLY when its identity equals the CURRENT
25
+ * identity exactly — the pair, never the bare counter (it resets with the SharedWorker). So a message is
26
+ * STALE precisely when it is not `engineIdentityEquals` the current identity.
27
+ */
28
+ export declare function isStaleIdentity(current: EngineIdentity, tagged: EngineIdentity): boolean;
29
+ /**
30
+ * Mint the next identity that THIS SharedWorker instance (`swInstanceId`) should announce.
31
+ *
32
+ * - No `previous` → generation `0` (the first engine this SharedWorker announces).
33
+ * - `previous` belongs to the SAME `swInstanceId` → `previous.generation + 1` (a succession within one
34
+ * SharedWorker: a fresh elected engine worker replacing the last).
35
+ * - `previous` belongs to a DIFFERENT `swInstanceId` (a re-announce arriving at a NEW SharedWorker
36
+ * instance, after SharedWorker death recovery) → the counter RESTARTS at `0` under the new instance id.
37
+ * The generation is scoped to one SharedWorker instance, so it cannot carry across instances.
38
+ */
39
+ export declare function mintEngineIdentity(swInstanceId: string, previous?: EngineIdentity): EngineIdentity;
40
+ /**
41
+ * The identity-tagged control plane the communication centre, the elected engine worker, and the tab
42
+ * coordinators exchange (distinct from the data-path bridge in `protocol.ts`; the SharedWorker never sees
43
+ * RPC payloads). Payload interfaces mirror `protocol.ts` conventions: a discriminating `type`, typed
44
+ * fields only, and MessagePorts travelling as transferables OUTSIDE the JSON body (see individual members).
45
+ * Identity-tagged members carry the {@link EngineIdentity} they belong to so a stale one is discarded.
46
+ */
47
+ export type EngineControlMessage =
48
+ /**
49
+ * SharedWorker → tab (the lock holder): the leader lock was granted; SPAWN the engine. Pre-spawn, so no
50
+ * identity exists yet — it OPENS the handoff window on the attach side (a relocation notice, CONTEXT
51
+ * "Handoff window"). Untagged: there is no engine identity to compare against before the engine exists.
52
+ */
53
+ {
54
+ type: "leader-granted";
55
+ }
56
+ /**
57
+ * tab → SharedWorker: the freshly spawned engine's MessagePort is announced so the SharedWorker can
58
+ * stamp it with a minted {@link EngineIdentity}. The announce ITSELF carries no identity (the SharedWorker
59
+ * mints it on receipt). The engine's control MessagePort travels as a TRANSFERABLE outside this JSON body
60
+ * (the same way `protocol.ts` transfers ports — never a serialized field), so nothing is typed here.
61
+ */
62
+ | {
63
+ type: "engine-announce";
64
+ }
65
+ /**
66
+ * tab → SharedWorker (ADR-0049 D8): this tab is detaching — UNREGISTER it from the router so `tabCount`
67
+ * (the destroy peer-refusal input) falls. The platform fires no SharedWorker port-close event and the tab's
68
+ * `detach` bridge envelope rides the per-tab PIPE (which the router never sees), so this control-plane signal
69
+ * on the SW port is the only channel the router observes. Untagged + always-applied: it names no engine (it
70
+ * concerns the tab's own registration), and a detaching tab must be dropped regardless of the current engine
71
+ * generation. The router stays payload-blind — this is a `pgx0049` control message, never a bridge envelope.
72
+ */
73
+ | {
74
+ type: "tab-detach";
75
+ }
76
+ /**
77
+ * elected engine → SharedWorker (ADR-0049 D1, capability-absence fallback): the elected dedicated engine's
78
+ * OWN-scope OPFS probe was DENIED (or the OPFS API is absent/throwing in the dedicated home too), so no home on
79
+ * this platform can hold sync-access handles. The engine reports that here so the router-only SharedWorker
80
+ * abandons election and boots the in-scope IDBFS engine instead (with the registry-declared durability) — the
81
+ * declared-idbfs shape reached by capability detection rather than declaration. Untagged: it names no engine
82
+ * (the engine never became authoritative — it is reporting that it cannot host), and the SharedWorker must act
83
+ * on it regardless of the current generation. `reason` is the verbatim probe attribution stamped into the
84
+ * fallback boot's `storageFallbackReason` (decision 12).
85
+ */
86
+ | {
87
+ type: "engine-fallback";
88
+ reason: string;
89
+ }
90
+ /**
91
+ * SharedWorker → engine (ADR-0049 step 9): the identity the router just minted for this engine, handed to
92
+ * the elected engine worker's control plane RIGHT AFTER the router stamps the `engine-announce` (before any
93
+ * `connect-port`). Although it carries an {@link EngineIdentity}, it is ALWAYS-APPLIED — it is the ASSIGNMENT
94
+ * itself, so it is never gated on the receiver's (still-absent or stale) current identity; every subsequent
95
+ * tagged message the engine receives is compared against THIS assigned identity. The engine remembers it and
96
+ * replies `engine-ready` (control-plane readiness, NOT engine boot — the engine still boots lazily on first
97
+ * attach). Sits with the untagged members in {@link shouldApplyControlMessage}'s always-apply set.
98
+ */
99
+ | {
100
+ type: "assign-identity";
101
+ identity: EngineIdentity;
102
+ }
103
+ /** SharedWorker → tab: the announced engine is live under this identity (the stamp fan-out). */
104
+ | {
105
+ type: "engine-ready";
106
+ identity: EngineIdentity;
107
+ }
108
+ /**
109
+ * SharedWorker → engine: accept a per-tab proxy pipe. The tab-end MessagePort is transferred ALONGSIDE
110
+ * this message (outside the JSON body, as a transferable), fed into `SyncWorkerHost.connect` (ADR D4).
111
+ */
112
+ | {
113
+ type: "connect-port";
114
+ identity: EngineIdentity;
115
+ }
116
+ /**
117
+ * A liveness probe request. Used BOTH as a tab↔SharedWorker keepalive (the leader keepalive) AND as a
118
+ * SharedWorker↔engine control-channel probe (the execution-limit path). `pingId` correlates the ack.
119
+ */
120
+ | {
121
+ type: "control-ping";
122
+ identity: EngineIdentity;
123
+ pingId: number;
124
+ }
125
+ /**
126
+ * The answer to a {@link EngineControlMessage} `control-ping`; `pingId` echoes the request. ONE reserved
127
+ * value: `pingId: -1` is the TEARDOWN ack by convention (ADR-0049 step 9) — the engine emits it in reply to
128
+ * an `engine-teardown` (not to any real ping), the router RELAYS it to every tab, and the coordinator's
129
+ * teardown wait settles on it. A `-1` therefore never correlates a probe ping (those start at 1).
130
+ */
131
+ | {
132
+ type: "control-ack";
133
+ identity: EngineIdentity;
134
+ pingId: number;
135
+ /** Present only when the reserved teardown acknowledgement reports that host close failed. */
136
+ error?: {
137
+ message: string;
138
+ detail?: unknown;
139
+ };
140
+ }
141
+ /**
142
+ * tab → SharedWorker: an execution-limit report — a dispatch has been outstanding `elapsedMs` past the
143
+ * configured limit (ADR D5). The SharedWorker then probes the engine's control channel; it is NOT itself
144
+ * a death verdict (the limit CONVERTS slow to terminated only after the probe threshold).
145
+ */
146
+ | {
147
+ type: "overdue-dispatch";
148
+ identity: EngineIdentity;
149
+ elapsedMs: number;
150
+ }
151
+ /**
152
+ * The retirement notice that PRECEDES every DELIBERATE termination — last-claim teardown, BFCache exit,
153
+ * and execution-limit termination all send it first (ADR D5), so the attach side opens the handoff window
154
+ * and queues new calls instead of racing a dying engine.
155
+ */
156
+ | {
157
+ type: "engine-retiring";
158
+ identity: EngineIdentity;
159
+ }
160
+ /** The teardown handshake after a retirement notice; ack/timeout settles the lock callback. */
161
+ | {
162
+ type: "engine-teardown";
163
+ identity: EngineIdentity;
164
+ };
165
+ /** Discriminants that carry an {@link EngineIdentity} and are therefore staleness-gated. `assign-identity`
166
+ carries one but is the ASSIGNMENT itself (always-applied), so it is excluded here alongside the untagged. */
167
+ type TaggedControlType = Exclude<EngineControlMessage, {
168
+ type: "leader-granted" | "engine-announce" | "assign-identity" | "tab-detach" | "engine-fallback";
169
+ }>["type"];
170
+ /**
171
+ * Whether a received control message should be APPLIED given the receiver's current engine identity.
172
+ *
173
+ * - ALWAYS-APPLY members (`leader-granted`, `engine-announce`, `assign-identity`, `tab-detach`, `engine-fallback`)
174
+ * always apply — `leader-granted`/`engine-announce`/`tab-detach`/`engine-fallback` carry no identity to compare
175
+ * (they precede any engine, mint an identity, concern the tab's own registration, or report that no engine can
176
+ * host), and `assign-identity` IS the assignment, so it applies unconditionally.
177
+ * - IDENTITY-TAGGED members apply only when `current` is set AND the identities match exactly (the pair,
178
+ * invariant 7). A tagged message with no current identity, or a stale identity, is discarded.
179
+ *
180
+ * The switch is exhaustive with a `never`-guard: a new union member fails to type-check until it is
181
+ * classified here (the runtime exhaustiveness test pairs with this compile-time guard).
182
+ */
183
+ export declare function shouldApplyControlMessage(current: EngineIdentity | undefined, message: EngineControlMessage): boolean;
184
+ /** Runtime companion to {@link shouldApplyControlMessage}'s compile-time guard: is this type staleness-gated? */
185
+ export declare function isTaggedControlType(type: EngineControlMessage["type"]): type is TaggedControlType;
186
+ /**
187
+ * The opt-in execution limit (ADR D5). ONE engine-construction value; DISABLED BY DEFAULT — no finite
188
+ * worst-case query duration exists, and the limit CONVERTS slow to terminated by policy, so enabling it
189
+ * must be a deliberate consumer choice (the public contract). When enabled, the limit
190
+ * CONVERTS slow to terminated after the control-probe threshold — it is NEVER claimed as death evidence.
191
+ * This feature is ELECTED-PLACEMENT ONLY: on SharedWorker-direct placement (WebKit) the option is rejected
192
+ * as unsupported — that rejection is wired in a later step; this module only defines the config + the
193
+ * cross-tab mismatch rule.
194
+ */
195
+ export interface ExecutionLimitConfig {
196
+ /** ms; `undefined` = DISABLED (the default — preserves unbounded queries). */
197
+ maxDispatchMs?: number;
198
+ }
199
+ /**
200
+ * Thrown at attach when a tab's execution-limit value disagrees with the engine's construction value
201
+ * (ADR D5): every tab must carry the SAME config. Named + `[pgxsinkit]`-prefixed like the repo's other
202
+ * protocol errors so a consumer can `instanceof`-branch it.
203
+ */
204
+ export declare class ExecutionLimitMismatchError extends Error {
205
+ readonly engineValue: number | undefined;
206
+ readonly attachValue: number | undefined;
207
+ constructor(engineValue: number | undefined, attachValue: number | undefined);
208
+ }
209
+ declare const EXECUTION_LIMIT_MISMATCH_CODE = "execution-limit-mismatch";
210
+ export declare function executionLimitMismatchToWire(error: ExecutionLimitMismatchError): {
211
+ code: typeof EXECUTION_LIMIT_MISMATCH_CODE;
212
+ engineValue?: number;
213
+ attachValue?: number;
214
+ };
215
+ export declare function executionLimitMismatchFromWire(detail: unknown): ExecutionLimitMismatchError | undefined;
216
+ /**
217
+ * Attach-time guard (ADR D5): every tab must carry the SAME execution-limit value as the running engine.
218
+ * Any mismatch — including one side disabled (`undefined`) and the other set — throws
219
+ * {@link ExecutionLimitMismatchError}. Equal values (both `undefined`, or the same number) pass.
220
+ */
221
+ export declare function assertSameExecutionLimit(engineValue: number | undefined, attachValue: number | undefined): void;
222
+ /**
223
+ * The two honest relocation outcomes (ADR D10, invariant 5). There is deliberately NO blanket "retryable":
224
+ * - `"not-dispatched"` — the call NEVER reached the engine (a queued call failed on the handoff queue's
225
+ * cap/deadline, or was never sent). SAFE TO RETRY.
226
+ * - `"unknown"` — a DISPATCHED mutation whose response was lost to relocation. Its journal update MAY
227
+ * already exist and there is NO mutation-dedup key, so it must be inspected/reconciled, NEVER auto-retried.
228
+ *
229
+ * A dispatched READ that lost its response is NOT a third outcome: repeating a read is safe, so that is the
230
+ * CALLER'S policy (repeat the read), not a distinct wire value.
231
+ */
232
+ export type EngineRelocatedOutcome = "not-dispatched" | "unknown";
233
+ /** The stable clone-safe discriminator carried on the wire (ADR D10). Consumers branch on this, never prose. */
234
+ export declare const ENGINE_RELOCATED_CODE = "engine-relocated";
235
+ /**
236
+ * The clone-safe wire form of a relocation failure (ADR D10). It travels inside the EXISTING bridge error
237
+ * `detail` field — the `{ message, detail }` error shape in `protocol.ts` (~line 330, e.g.
238
+ * `RpcResultPayload.error`) — so no new protocol field is needed. The attach side (step 7) calls
239
+ * {@link engineRelocatedFromWire} on every bridge error `detail` to reconstruct the typed error.
240
+ */
241
+ export interface EngineRelocatedWire {
242
+ code: typeof ENGINE_RELOCATED_CODE;
243
+ outcome: EngineRelocatedOutcome;
244
+ }
245
+ /**
246
+ * The exported, consumer-visible relocation error (ADR D10, invariant 5). Consumers branch on `code` +
247
+ * `outcome`, never on message prose — but the message NAMES the semantics so a developer hitting it in a
248
+ * log understands immediately. `[pgxsinkit]`-prefixed like the repo's other errors.
249
+ */
250
+ export declare class EngineRelocatedError extends Error {
251
+ readonly code = "engine-relocated";
252
+ readonly outcome: EngineRelocatedOutcome;
253
+ constructor(outcome: EngineRelocatedOutcome);
254
+ }
255
+ /** Encode a {@link EngineRelocatedError} to its clone-safe wire form for the bridge error `detail` field. */
256
+ export declare function engineRelocatedToWire(error: EngineRelocatedError): EngineRelocatedWire;
257
+ /**
258
+ * Reconstruct a typed {@link EngineRelocatedError} from a bridge error's `detail` (step 7 calls this on
259
+ * every bridge error detail). STRICT shape check: returns `undefined` for anything that is not exactly the
260
+ * `{ code: "engine-relocated", outcome }` wire form (a foreign/absent detail, a wrong code, a bogus or
261
+ * missing outcome, a non-object) — so a non-relocation error is never misclassified.
262
+ */
263
+ export declare function engineRelocatedFromWire(detail: unknown): EngineRelocatedError | undefined;
264
+ export {};
265
+ //# sourceMappingURL=engine-control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-control.d.ts","sourceRoot":"","sources":["../../src/worker/engine-control.ts"],"names":[],"mappings":"AAYA,+EAA+E;AAC/E,eAAO,MAAM,2BAA2B,EAAG,SAAkB,CAAC;AAE9D,yFAAyF;AACzF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG;IAClE,CAAC,2BAA2B,CAAC,EAAE,oBAAoB,CAAC;CACrD,CAEA;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,OAAO,GAAG,oBAAoB,GAAG,SAAS,CAMnF;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,mGAAmG;IACnG,YAAY,EAAE,MAAM,CAAC;IACrB,kGAAkG;IAClG,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,+FAA+F;AAC/F,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,EAAE,cAAc,GAAG,OAAO,CAElF;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAExF;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,cAAc,CAGlG;AAID;;;;;;GAMG;AACH,MAAM,MAAM,oBAAoB;AAE9B;;;;GAIG;AACD;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE;AAC5B;;;;;GAKG;GACD;IAAE,IAAI,EAAE,iBAAiB,CAAA;CAAE;AAC7B;;;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