@pgxsinkit/client 0.2.7 → 0.5.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.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +11 -3
- package/dist/boot-report.d.ts +11 -8
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +39 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +96 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.d.ts.map +1 -1
- package/dist/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +237 -113
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7037 -6665
- package/dist/index.js.map +46 -43
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +59 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +17 -25
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +84 -8
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- package/dist/sync/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +26 -7
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +4 -3
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +27 -14
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +52 -19
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -9
- package/skills/core/SKILL.md +145 -63
- package/skills/operating/SKILL.md +221 -221
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +13 -12
- package/src/circuits/envelope-to-change.ts +211 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +191 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +643 -0
- package/src/debug.ts +1 -85
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +24 -28
- package/src/export-store.ts +17 -17
- package/src/index.ts +797 -544
- package/src/lazy-guard.ts +1 -1
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +76 -5
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +126 -29
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +56 -40
- package/src/sync/apply.ts +104 -156
- package/src/sync/copy.ts +116 -21
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +43 -2
- package/src/sync/subscription-state.ts +28 -10
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +4 -4
- package/src/worker/attach-sync-client.ts +150 -57
- package/src/worker/define-sync-worker.ts +325 -87
- package/src/worker/engine-control.ts +89 -0
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +10 -10
- package/src/worker/protocol.ts +38 -7
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
package/dist/sync/types.d.ts
CHANGED
|
@@ -1,138 +1,18 @@
|
|
|
1
|
-
import type {
|
|
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";
|
|
1
|
+
import type { SyncChange } from "@pgxsinkit/contracts";
|
|
7
2
|
export type Lsn = bigint;
|
|
8
3
|
export type SubscriptionKey = string;
|
|
9
4
|
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
5
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
6
|
+
* A change the fold has established is the net UPSERT of a complete row.
|
|
7
|
+
*
|
|
8
|
+
* The narrowing is what the bulk paths rely on: `value` carries every projected column, so the rows
|
|
9
|
+
* can go out as one multi-row statement (or a COPY) with no per-row branch on which columns are
|
|
10
|
+
* present. Guaranteed by the engine, not merely hoped for — `row_to_json_cols` emits every column of
|
|
11
|
+
* the shape's `out_cols` on every upsert.
|
|
17
12
|
*/
|
|
18
|
-
export
|
|
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
|
-
/**
|
|
42
|
-
* ADR-0042: this group's sync bookkeeping (subscription cursor + tagged-subquery reason sets) is
|
|
43
|
-
* SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
|
|
44
|
-
* durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
|
|
45
|
-
* and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
|
|
46
|
-
* instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — a
|
|
47
|
-
* persistent group's storage is identical whether the bit is `false` or unset; it only scopes an
|
|
48
|
-
* ephemeral group's bookkeeping. One storage-scope bit; the engine never learns the retention model.
|
|
49
|
-
*/
|
|
50
|
-
sessionScoped?: boolean | undefined;
|
|
51
|
-
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
52
|
-
onInitialSync?: (() => void) | undefined;
|
|
53
|
-
/**
|
|
54
|
-
* Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a
|
|
55
|
-
* PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine
|
|
56
|
-
* starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the
|
|
57
|
-
* two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and
|
|
58
|
-
* gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it
|
|
59
|
-
* once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so
|
|
60
|
-
* the network catch-up overlaps those local phases instead of running strictly after them. Absent → the
|
|
61
|
-
* exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior
|
|
62
|
-
* subscription state, the overlap treats the group as a new subscription (`subState === null`), which the
|
|
63
|
-
* `freshStore` gate guarantees.
|
|
64
|
-
*/
|
|
65
|
-
dbReady?: Promise<void> | undefined;
|
|
66
|
-
/** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */
|
|
67
|
-
onError?: ((error: FetchError | Error) => void) | undefined;
|
|
68
|
-
/**
|
|
69
|
-
* Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction
|
|
70
|
-
* still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its
|
|
71
|
-
* buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the
|
|
72
|
-
* read cache cannot silently diverge; recovery is a later commit or a restart/refetch.
|
|
73
|
-
*/
|
|
74
|
-
onSyncError?: ((error: Error) => void) | undefined;
|
|
75
|
-
/**
|
|
76
|
-
* Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).
|
|
77
|
-
* The runtime uses this as the read path's "alive again" signal to clear an `auth-needed` status
|
|
78
|
-
* once sync resumes after re-authentication.
|
|
79
|
-
*/
|
|
80
|
-
onSyncActivity?: (() => void) | undefined;
|
|
81
|
-
/** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
|
|
82
|
-
maxCommitRetries?: number | undefined;
|
|
83
|
-
/**
|
|
84
|
-
* Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to
|
|
85
|
-
* the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an
|
|
86
|
-
* immediate retry instead of sleeping the real backoff.
|
|
87
|
-
*/
|
|
88
|
-
commitRetryDelayMs?: ((attempt: number) => number) | undefined;
|
|
89
|
-
/**
|
|
90
|
-
* Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
|
|
91
|
-
* batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
|
|
92
|
-
* (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
|
|
93
|
-
* boot without report instrumentation.
|
|
94
|
-
*/
|
|
95
|
-
bootStamp?: GroupBootStamp | undefined;
|
|
96
|
-
}
|
|
97
|
-
export interface SyncShapesToTablesResult {
|
|
98
|
-
unsubscribe: () => void;
|
|
99
|
-
readonly isUpToDate: boolean;
|
|
100
|
-
streams: Record<string, ShapeStreamInterface<Row<unknown>>>;
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based
|
|
104
|
-
* fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.
|
|
105
|
-
*/
|
|
106
|
-
export interface SyncShapeToTableOptions {
|
|
107
|
-
shape: ShapeStreamOptions<Row<unknown>>;
|
|
108
|
-
registry: SyncTableRegistry;
|
|
109
|
-
tableKey: string;
|
|
110
|
-
shapeKey: string | null;
|
|
111
|
-
/** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */
|
|
112
|
-
sessionScoped?: boolean | undefined;
|
|
113
|
-
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
114
|
-
onInitialSync?: (() => void) | undefined;
|
|
115
|
-
onError?: ((error: FetchError | Error) => void) | undefined;
|
|
116
|
-
/** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */
|
|
117
|
-
onSyncError?: ((error: Error) => void) | undefined;
|
|
118
|
-
/** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
|
|
119
|
-
maxCommitRetries?: number | undefined;
|
|
120
|
-
/** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */
|
|
121
|
-
commitRetryDelayMs?: ((attempt: number) => number) | undefined;
|
|
122
|
-
onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
|
|
123
|
-
}
|
|
124
|
-
export interface SyncShapeToTableResult {
|
|
125
|
-
unsubscribe: () => void;
|
|
126
|
-
readonly isUpToDate: boolean;
|
|
127
|
-
stream: ShapeStreamInterface<Row<unknown>>;
|
|
128
|
-
}
|
|
129
|
-
export interface ElectricSyncOptions {
|
|
130
|
-
debug?: boolean;
|
|
131
|
-
metadataSchema?: string;
|
|
132
|
-
}
|
|
133
|
-
export type InsertChangeMessage = ChangeMessage<Row<unknown>> & {
|
|
13
|
+
export type UpsertChangeMessage = SyncChange & {
|
|
134
14
|
headers: {
|
|
135
|
-
operation: "
|
|
15
|
+
operation: "upsert";
|
|
136
16
|
};
|
|
137
17
|
};
|
|
138
18
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/sync/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sync/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sync/types.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC;AAEzB,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AACrC,MAAM,MAAM,mBAAmB,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG;IAC7C,OAAO,EAAE;QAAE,SAAS,EAAE,QAAQ,CAAA;KAAE,CAAC;CAClC,CAAC"}
|
package/dist/testing.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export declare function memoryStoreForTests(storePath: string): MemoryStoreForTe
|
|
|
18
18
|
/**
|
|
19
19
|
* Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
|
|
20
20
|
* (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
|
|
21
|
-
*
|
|
21
|
+
* pgwasm via `pgwasmInstance` / `precreatedPgwasm`. Spread it alongside that option.
|
|
22
22
|
*
|
|
23
23
|
* Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
|
|
24
24
|
* store voids the retention + journal durability guarantees.
|
package/dist/testing.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// packages/client/src/store-path.ts
|
|
3
|
+
import { idbDatabaseName } from "@pgxsinkit/pgwasm-c";
|
|
3
4
|
var TEST_STORE_BACKEND = Symbol.for("pgxsinkit.internal.testStoreBackend");
|
|
4
5
|
|
|
5
6
|
// packages/client/src/testing.ts
|
|
@@ -10,8 +11,8 @@ function testStoreAcknowledgment() {
|
|
|
10
11
|
return { [TEST_STORE_BACKEND]: "acknowledged" };
|
|
11
12
|
}
|
|
12
13
|
export {
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
memoryStoreForTests,
|
|
15
|
+
testStoreAcknowledgment
|
|
15
16
|
};
|
|
16
17
|
|
|
17
|
-
//# debugId=
|
|
18
|
+
//# debugId=3C36F3E738F6693364756E2164756E21
|
package/dist/testing.js.map
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/store-path.ts", "../src/testing.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// PGlite storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by\n// the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the\n// filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` / `opfs://`\n// URLs (the export machinery's throwaway clone is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something a\n// consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old contract\n// loudly at the boundary rather than silently re-interpreting it.\n//\n// Under ADR-0049 (capability-driven engine placement) it also owns the browser-side STORE IDENTITY encoding\n// and the disjoint OPFS namespaces the placement probe, the commitment marker, and the store meta record all\n// key on. `storeIdentityComponent` is the one injective encoding for every browser-side identity surface\n// (OPFS namespace entries, leader lock, meta record key, communication-centre SharedWorker name; D11), and the\n// `pgxsinkit/stores|commitments|probe` namespace builders are the one place those names live (D6).\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /\n * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins\n * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a\n * consumer is never left guessing which store to hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: \"in-memory-default\" | \"memory-scheme\") {\n const reason =\n observed === \"in-memory-default\"\n ? \"its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)\"\n : \"its dataDir is a memory-backed store\";\n super(\n `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n /**\n * ADR-0049 (D1): the PLACEMENT PROBE's injected result — whether a REAL `createSyncAccessHandle` open\n * succeeded in the executing scope (the bench phase-0 mechanism, performed by the async boot path — never\n * method-presence sniffing). Optional so every existing `StoreEnv` construction stays valid; `undefined`\n * means \"no OPFS sync access\" (false). {@link detectStoreEnv} ALWAYS reports `false` for it: there is no\n * synchronous ambient detection for handle grants, and method-presence sniffing is forbidden — only the\n * boot path's real probe open can flip it true.\n */\n hasOpfsSyncAccess?: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n // `hasOpfsSyncAccess` is deliberately absent (false): the placement probe (an async handle open) is the\n // only honest source, and this synchronous ambient detector must never guess it (ADR-0049 D1).\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * The shared plain-`storePath` boundary guard (ADR-0036 decision 1). A storePath is a PLAIN name, never a\n * storage URL: empty/whitespace-only or scheme-bearing (`://`) values fail loudly with\n * {@link InvalidStorePathError}. Factored so {@link resolveStoreDataDir} and {@link storeIdentityComponent}\n * share ONE message set (no drift between the two identity-surface entry points).\n */\nfunction assertPlainStorePath(storePath: string): void {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (capability-selected opfs-repacked ' +\n \"with IndexedDB fallback in a browser, or the filesystem on Bun/Node) is derived for you; drop the \" +\n \"scheme prefix (ADR-0036/ADR-0049).\",\n );\n }\n}\n\n/**\n * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves\n * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;\n * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`\n * is internal-only: `\"memory\"` selects a scheme-selected `memory://<storePath>` test/ephemeral store.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n *\n * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in\n * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:\n * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →\n * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;\n * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace\n * builders below. Like every URL resolved here, it never leaks to consumers.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n assertPlainStorePath(storePath);\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n if (env.hasOpfsSyncAccess) return `opfs://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The per-component ENCODED length cap for {@link storeIdentityComponent}. A filesystem-safe bound for a\n * single OPFS name component; the fixed container/namespace names (`pgxsinkit`, `stores`, `commitments`,\n * `probe`) are SEPARATE path components and add nothing to this budget. Encoding is what is capped, not the\n * raw input — a short multi-byte name can expand past the bound.\n */\nconst STORE_IDENTITY_ENCODED_CAP = 128;\n\n/**\n * The ONE injective encoding for every browser-side identity surface (ADR-0049 D11, invariant 10): OPFS\n * namespace entries ({@link opfsStoreDirectoryPath} / {@link opfsCommitmentSentinelPath}), the leader lock\n * name, the store meta record key, and the communication-centre SharedWorker name all derive from this single\n * canonical component. Percent-encoding (`encodeURIComponent`) — injective, never lossy sanitising, so two\n * distinct store paths can never collapse to one identity (e.g. `\"foo/bar\"` → `foo%2Fbar` vs the literal\n * `\"foo%2Fbar\"` → `foo%252Fbar`).\n *\n * Domain (invariant 10):\n * - Same boundary guards as {@link resolveStoreDataDir}: empty/whitespace-only or scheme-bearing (`://`)\n * paths throw {@link InvalidStorePathError} (shared {@link assertPlainStorePath}).\n * - A lone UTF-16 surrogate makes `encodeURIComponent` raise a `URIError`; that is wrapped into\n * {@link InvalidStorePathError} so callers branch one error type at the boundary.\n * - `.` and `..` pass through `encodeURIComponent` UNCHANGED, but the File System Standard reserves them as\n * invalid file names, so both are rejected.\n * - The ENCODED length is capped at {@link STORE_IDENTITY_ENCODED_CAP} (a per-component filesystem-safe\n * bound); overflow is rejected.\n */\nexport function storeIdentityComponent(storePath: string): string {\n assertPlainStorePath(storePath);\n let identity: string;\n try {\n identity = encodeURIComponent(storePath);\n } catch (error) {\n // The only `encodeURIComponent` failure is a lone UTF-16 surrogate (`URIError`); rewrap it so the domain\n // presents ONE error type at the boundary (never a bare `URIError`).\n if (error instanceof URIError) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: it contains a lone UTF-16 surrogate, which has no ` +\n \"valid encoding as a store identity (ADR-0049).\",\n );\n }\n throw error;\n }\n if (identity === \".\" || identity === \"..\") {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: \".\" and \"..\" are reserved file names (File System ` +\n \"Standard) and cannot be a store identity (ADR-0049).\",\n );\n }\n if (identity.length > STORE_IDENTITY_ENCODED_CAP) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: its encoded store identity is ${identity.length} ` +\n `characters, over the ${STORE_IDENTITY_ENCODED_CAP}-character per-component cap (ADR-0049). Note the ` +\n \"cap is on the ENCODED form — a short multi-byte name can expand past it.\",\n );\n }\n return identity;\n}\n\n/**\n * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,\n * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `\"foo\"`'s\n * commitment sentinel vs a store literally named `\"foo.committed\"`). This module is the ONLY place that knows\n * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`\n * prefix.\n */\nexport const OPFS_TOOLKIT_CONTAINER = \"pgxsinkit\";\n\n/**\n * OPFS path (segment array) of a store's four-file VFS directory: `pgxsinkit/stores/<identity>` (ADR-0049 D6).\n * Returned as SEGMENTS, not a joined string, because consumers traverse OPFS via a `getDirectoryHandle` chain.\n */\nexport function opfsStoreDirectoryPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"stores\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of a store's commitment marker sentinel: `pgxsinkit/commitments/<identity>`\n * (ADR-0049 D6). Disjoint from {@link opfsStoreDirectoryPath} — the store directory holds exactly the four\n * VFS-owned files, and a suffix-sibling sentinel would collide across valid identities. Segments, not a joined\n * string, for the same `getDirectoryHandle`-chain reason.\n */\nexport function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"commitments\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No\n * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.\n */\nexport function opfsProbeDirectoryPath(): readonly [string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"probe\"];\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite\n * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`\n * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a\n * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather\n * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return `/pglite/${storePath}`;\n}\n\n/**\n * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending\n * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a\n * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,\n * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the\n * two accidental non-persistent shapes, it is not a storage-backend whitelist).\n */\nexport function classifyNonPersistentDataDir(\n dataDir: string | undefined,\n): \"in-memory-default\" | \"memory-scheme\" | null {\n if (dataDir == null) return \"in-memory-default\";\n if (dataDir.startsWith(\"memory://\")) return \"memory-scheme\";\n return null;\n}\n\n/**\n * The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses — just the\n * never-creating `getDirectoryHandle` hop. Declared locally so the module carries no DOM lib dependency\n * (matching how the rest of it reads capabilities structurally off `globalThis`).\n */\ninterface OpfsDirectoryHandle {\n getDirectoryHandle(name: string, options: { create: false }): Promise<OpfsDirectoryHandle>;\n}\n\n/**\n * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target\n * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at\n * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via\n * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is\n * ONLY the fresh-target gate; it is emphatically NOT commitment authority — a store directory without a\n * commitment marker is an uncommitted CANDIDATE, and deciding that is the store meta record's phase machine\n * (plan step 2), never this function. `navigator.storage`/`getDirectory` absent → best-effort `false`\n * (mirrors the idb `databases()` stance — never fabricate a positive). A `NotFoundError` anywhere in the\n * chain → `false`; any OTHER error propagates (a genuine failure the restore caller must see).\n * A missing OPFS directory does not finish a granted browser check: IDB is also probed, because a predecessor\n * or fixed-placement store may still own the same public path.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * PGlite-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to PGlite's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n if (dataDir.startsWith(\"opfs://\")) {\n // Structural typing off `globalThis` — no DOM lib dependency (like the rest of the module).\n const storage = (\n globalThis as {\n navigator?: {\n storage?: { getDirectory?: () => Promise<OpfsDirectoryHandle> };\n };\n }\n ).navigator?.storage;\n // API absent → best-effort false (never a fabricated positive), same stance as idb `databases()`.\n if (storage?.getDirectory != null) {\n const segments = opfsStoreDirectoryPath(storePath);\n try {\n let handle = await storage.getDirectory();\n for (const segment of segments) {\n // Never-creating existence walk: `{ create: false }` at every hop — this is a gate, not a mkdir.\n handle = await handle.getDirectoryHandle(segment, { create: false });\n }\n return true;\n } catch (error) {\n // A missing entry anywhere in the chain proves OPFS absence; anything else is a real failure to surface.\n if ((error as { name?: string }).name !== \"NotFoundError\") throw error;\n }\n }\n // A granted browser must also reject an IDB predecessor at this path; fall through to the shared IDB probe.\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
|
|
6
|
-
"// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).\n//\n// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a\n// memory store: `createSyncClient`/`
|
|
5
|
+
"import type { StorageDescription } from \"@pgxsinkit/pgwasm\";\nimport { idbDatabaseName } from \"@pgxsinkit/pgwasm-c\";\n\n// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createPgwasmClient`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// pgwasm storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by\n// the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the\n// filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` / `opfs://`\n// URLs (the export machinery's throwaway clone is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something a\n// consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old contract\n// loudly at the boundary rather than silently re-interpreting it.\n//\n// Under ADR-0049 (capability-driven engine placement) it also owns the browser-side STORE IDENTITY encoding\n// and the disjoint OPFS namespaces the placement probe, the commitment marker, and the store meta record all\n// key on. `storeIdentityComponent` is the one injective encoding for every browser-side identity surface\n// (OPFS namespace entries, leader lock, meta record key, communication-centre SharedWorker name; D11), and the\n// `pgxsinkit/stores|commitments|probe` namespace builders are the one place those names live (D6).\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned store handed to {@link CreateSyncClientOptions.pgwasmInstance} /\n * {@link CreateSyncClientOptions.precreatedPgwasm} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `storage` is memory (pgwasm's default — the bare `createPgwasm({ build })` a copy-paste reaches — or an\n * explicit `memory://`), or a filesystem that explicitly reports itself non-persistent. Names both the why (durability\n * semantics assume a persisted store) and the two exits, so a consumer is never left guessing which store to\n * hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: NonPersistentStorage) {\n const reason =\n observed === \"memory\"\n ? \"its storage is in memory (pgwasm's default without a `dataDir`, or `memory://`)\"\n : \"its storage is a filesystem that explicitly reports itself non-persistent\";\n super(\n `[pgxsinkit] refusing a non-persistent store: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createPgwasmClient} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createPgwasmClient(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: pgwasm's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n /**\n * ADR-0049 (D1): the PLACEMENT PROBE's injected result — whether a REAL `createSyncAccessHandle` open\n * succeeded in the executing scope (the bench phase-0 mechanism, performed by the async boot path — never\n * method-presence sniffing). Optional so every existing `StoreEnv` construction stays valid; `undefined`\n * means \"no OPFS sync access\" (false). {@link detectStoreEnv} ALWAYS reports `false` for it: there is no\n * synchronous ambient detection for handle grants, and method-presence sniffing is forbidden — only the\n * boot path's real probe open can flip it true.\n */\n hasOpfsSyncAccess?: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n // `hasOpfsSyncAccess` is deliberately absent (false): the placement probe (an async handle open) is the\n // only honest source, and this synchronous ambient detector must never guess it (ADR-0049 D1).\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * The shared plain-`storePath` boundary guard (ADR-0036 decision 1). A storePath is a PLAIN name, never a\n * storage URL: empty/whitespace-only or scheme-bearing (`://`) values fail loudly with\n * {@link InvalidStorePathError}. Factored so {@link resolveStoreDataDir} and {@link storeIdentityComponent}\n * share ONE message set (no drift between the two identity-surface entry points).\n */\nfunction assertPlainStorePath(storePath: string): void {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (capability-selected opfs-repacked ' +\n \"with IndexedDB fallback in a browser, or the filesystem on Bun/Node) is derived for you; drop the \" +\n \"scheme prefix (ADR-0036/ADR-0049).\",\n );\n }\n}\n\n/**\n * Resolve a plain {@link storePath} to the pgwasm dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves\n * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;\n * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`\n * is internal-only: `\"memory\"` selects a scheme-selected `memory://<storePath>` test/ephemeral store.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n *\n * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in\n * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:\n * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →\n * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — pgwasm does NOT accept it as a `dataDir`;\n * {@link createPgwasmClient} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace\n * builders below. Like every URL resolved here, it never leaks to consumers.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n assertPlainStorePath(storePath);\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n if (env.hasOpfsSyncAccess) return `opfs://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The per-component ENCODED length cap for {@link storeIdentityComponent}. A filesystem-safe bound for a\n * single OPFS name component; the fixed container/namespace names (`pgxsinkit`, `stores`, `commitments`,\n * `probe`) are SEPARATE path components and add nothing to this budget. Encoding is what is capped, not the\n * raw input — a short multi-byte name can expand past the bound.\n */\nconst STORE_IDENTITY_ENCODED_CAP = 128;\n\n/**\n * The ONE injective encoding for every browser-side identity surface (ADR-0049 D11, invariant 10): OPFS\n * namespace entries ({@link opfsStoreDirectoryPath} / {@link opfsCommitmentSentinelPath}), the leader lock\n * name, the store meta record key, and the communication-centre SharedWorker name all derive from this single\n * canonical component. Percent-encoding (`encodeURIComponent`) — injective, never lossy sanitising, so two\n * distinct store paths can never collapse to one identity (e.g. `\"foo/bar\"` → `foo%2Fbar` vs the literal\n * `\"foo%2Fbar\"` → `foo%252Fbar`).\n *\n * Domain (invariant 10):\n * - Same boundary guards as {@link resolveStoreDataDir}: empty/whitespace-only or scheme-bearing (`://`)\n * paths throw {@link InvalidStorePathError} (shared {@link assertPlainStorePath}).\n * - A lone UTF-16 surrogate makes `encodeURIComponent` raise a `URIError`; that is wrapped into\n * {@link InvalidStorePathError} so callers branch one error type at the boundary.\n * - `.` and `..` pass through `encodeURIComponent` UNCHANGED, but the File System Standard reserves them as\n * invalid file names, so both are rejected.\n * - The ENCODED length is capped at {@link STORE_IDENTITY_ENCODED_CAP} (a per-component filesystem-safe\n * bound); overflow is rejected.\n */\nexport function storeIdentityComponent(storePath: string): string {\n assertPlainStorePath(storePath);\n let identity: string;\n try {\n identity = encodeURIComponent(storePath);\n } catch (error) {\n // The only `encodeURIComponent` failure is a lone UTF-16 surrogate (`URIError`); rewrap it so the domain\n // presents ONE error type at the boundary (never a bare `URIError`).\n if (error instanceof URIError) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: it contains a lone UTF-16 surrogate, which has no ` +\n \"valid encoding as a store identity (ADR-0049).\",\n );\n }\n throw error;\n }\n if (identity === \".\" || identity === \"..\") {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: \".\" and \"..\" are reserved file names (File System ` +\n \"Standard) and cannot be a store identity (ADR-0049).\",\n );\n }\n if (identity.length > STORE_IDENTITY_ENCODED_CAP) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: its encoded store identity is ${identity.length} ` +\n `characters, over the ${STORE_IDENTITY_ENCODED_CAP}-character per-component cap (ADR-0049). Note the ` +\n \"cap is on the ENCODED form — a short multi-byte name can expand past it.\",\n );\n }\n return identity;\n}\n\n/**\n * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,\n * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `\"foo\"`'s\n * commitment sentinel vs a store literally named `\"foo.committed\"`). This module is the ONLY place that knows\n * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the client's sole route to the\n * IndexedDB database names.\n */\nexport const OPFS_TOOLKIT_CONTAINER = \"pgxsinkit\";\n\n/**\n * OPFS path (segment array) of a store's four-file VFS directory: `pgxsinkit/stores/<identity>` (ADR-0049 D6).\n * Returned as SEGMENTS, not a joined string, because consumers traverse OPFS via a `getDirectoryHandle` chain.\n */\nexport function opfsStoreDirectoryPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"stores\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of a store's commitment marker sentinel: `pgxsinkit/commitments/<identity>`\n * (ADR-0049 D6). Disjoint from {@link opfsStoreDirectoryPath} — the store directory holds exactly the four\n * VFS-owned files, and a suffix-sibling sentinel would collide across valid identities. Segments, not a joined\n * string, for the same `getDirectoryHandle`-chain reason.\n */\nexport function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"commitments\", storeIdentityComponent(storePath)];\n}\n\n/**\n * The Web Lock name of a store's OPFS OWNERSHIP (`store-ownership-lock.ts`): held EXCLUSIVELY by the context\n * that holds the store directory's sync-access handles, from before it opens them until after it closes them,\n * and taken by anything that deletes the directory. Keyed on the same injective identity as the OPFS paths, so\n * two valid identities never share a lock.\n */\nexport function storeOwnershipLockName(storePath: string): string {\n return `${OPFS_TOOLKIT_CONTAINER}:store-owner:${storeIdentityComponent(storePath)}`;\n}\n\n/**\n * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No\n * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.\n */\nexport function opfsProbeDirectoryPath(): readonly [string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"probe\"];\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. pgwasm\n * maps `idb://<storePath>` to the IndexedDB database `/pgwasm/<storePath>` (the IDBFS mount point: its root\n * `/pgwasm` joined with the path after the scheme), and the name comes from `@pgxsinkit/pgwasm-c`'s own\n * `idbDatabaseName`, never re-encoded here. Exposed so a consumer that GCs its own stores routes that\n * pgwasm-internal naming knowledge through the library rather than re-deriving the prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return idbDatabaseName(storePath);\n}\n\n/** The provably-non-persistent storage shapes {@link classifyNonPersistentStorage} reports. */\nexport type NonPersistentStorage = \"memory\" | \"non-persistent-vfs\";\n\n/**\n * Classify a store's own `pg.storage` for the BYO refusal (ADR-0036 decision 4). Returns the offending shape\n * when the store is PROVABLY non-persistent (`memory`, pgwasm's default or an explicit `memory://`; a `vfs`\n * filesystem explicitly reporting `persistent: false`), or `null` when it passes: `idb`, `file`, a persistent\n * `vfs` (the OPFS-repacked store) and a `vfs` that doesn't declare its persistence (a custom filesystem is\n * the caller's own call). The guard catches the accidental non-persistent shapes; it is not a\n * storage-backend whitelist.\n */\nexport function classifyNonPersistentStorage(storage: StorageDescription): NonPersistentStorage | null {\n if (storage.kind === \"memory\") return \"memory\";\n if (storage.kind === \"vfs\" && storage.persistent === false) return \"non-persistent-vfs\";\n return null;\n}\n\n/**\n * The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses — just the\n * never-creating `getDirectoryHandle` hop. Declared locally so the module carries no DOM lib dependency\n * (matching how the rest of it reads capabilities structurally off `globalThis`).\n */\ninterface OpfsDirectoryHandle {\n getDirectoryHandle(name: string, options: { create: false }): Promise<OpfsDirectoryHandle>;\n}\n\n/**\n * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target\n * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as pgwasm's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at\n * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via\n * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is\n * ONLY the fresh-target gate; it is emphatically NOT commitment authority — a store directory without a\n * commitment marker is an uncommitted CANDIDATE, and deciding that is the store meta record's phase machine\n * (plan step 2), never this function. `navigator.storage`/`getDirectory` absent → best-effort `false`\n * (mirrors the idb `databases()` stance — never fabricate a positive). A `NotFoundError` anywhere in the\n * chain → `false`; any OTHER error propagates (a genuine failure the restore caller must see).\n * A missing OPFS directory does not finish a granted browser check: IDB is also probed, because a predecessor\n * or fixed-placement store may still own the same public path.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * pgwasm-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to pgwasm's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n if (dataDir.startsWith(\"opfs://\")) {\n // Structural typing off `globalThis` — no DOM lib dependency (like the rest of the module).\n const storage = (\n globalThis as {\n navigator?: {\n storage?: { getDirectory?: () => Promise<OpfsDirectoryHandle> };\n };\n }\n ).navigator?.storage;\n // API absent → best-effort false (never a fabricated positive), same stance as idb `databases()`.\n if (storage?.getDirectory != null) {\n const segments = opfsStoreDirectoryPath(storePath);\n try {\n let handle = await storage.getDirectory();\n for (const segment of segments) {\n // Never-creating existence walk: `{ create: false }` at every hop — this is a gate, not a mkdir.\n handle = await handle.getDirectoryHandle(segment, { create: false });\n }\n return true;\n } catch (error) {\n // A missing entry anywhere in the chain proves OPFS absence; anything else is a real failure to surface.\n if ((error as { name?: string }).name !== \"NotFoundError\") throw error;\n }\n }\n // A granted browser must also reject an IDB predecessor at this path; fall through to the shared IDB probe.\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
|
|
6
|
+
"// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).\n//\n// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a\n// memory store: `createSyncClient`/`createPgwasmClient` take a plain `storePath` whose backend is derived\n// (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory\n// stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export\n// machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so\n// reaching a memory store is always a visible, deliberate act. App bundles never import it, so the whole\n// module (and any mention of memory) tree-shakes away.\n//\n// The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}\n// marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:\n//\n// createSyncClient({ ...memoryStoreForTests(\"my-test\"), registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })\n// createSyncClient({ ...testStoreAcknowledgment(), pgwasmInstance, registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })\n\nimport { TEST_STORE_BACKEND } from \"./store-path\";\n\n/**\n * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker\n * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.\n */\nexport interface MemoryStoreForTests {\n storePath: string;\n}\n\n/**\n * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral\n * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its\n * options accept `storePath`): the client reads the internal marker and selects the memory backend.\n *\n * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the\n * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance\n * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.\n */\nexport function memoryStoreForTests(storePath: string): MemoryStoreForTests {\n // The marker is a symbol-keyed property, so it survives an object spread but is invisible to the public\n // type and to `Object.keys`. Cast because the return TYPE deliberately hides it (ADR-0036 decision 3).\n return { storePath, [TEST_STORE_BACKEND]: \"memory\" } as MemoryStoreForTests;\n}\n\n/**\n * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal\n * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent\n * pgwasm via `pgwasmInstance` / `precreatedPgwasm`. Spread it alongside that option.\n *\n * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent\n * store voids the retention + journal durability guarantees.\n */\nexport function testStoreAcknowledgment(): Record<never, never> {\n // An empty public shape carrying only the internal marker — nothing for a consumer to configure.\n return { [TEST_STORE_BACKEND]: \"acknowledged\" } as Record<never, never>;\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";;
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";;AACA;AA2FO,IAAM,qBAAoC,OAAO,IAAI,qCAAqC;;;ACzD1F,SAAS,mBAAmB,CAAC,WAAwC;AAAA,EAG1E,OAAO,EAAE,YAAY,qBAAqB,SAAS;AAAA;AAW9C,SAAS,uBAAuB,GAAyB;AAAA,EAE9D,OAAO,GAAG,qBAAqB,eAAe;AAAA;",
|
|
9
|
+
"debugId": "3C36F3E738F6693364756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -46,10 +46,10 @@ export interface ElectedEngineWorker {
|
|
|
46
46
|
/**
|
|
47
47
|
* The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
|
|
48
48
|
* follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
|
|
49
|
-
* (`StoreOwnedError`)
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
49
|
+
* (`StoreOwnedError`). The wait for the dead worker's agent to release the handles lives in the SUCCESSOR'S OPEN
|
|
50
|
+
* PATH: the respawned engine first takes the store's ownership Web Lock (`store-ownership-lock.ts`), which the
|
|
51
|
+
* predecessor holds until its handles are closed or its context is gone, then its `createOpfsPgwasm` open retries
|
|
52
|
+
* on any residual owned-store contention (the `openWithBoundedRetries` wrapper) — the fault-matrix row.
|
|
53
53
|
* So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
|
|
54
54
|
*/
|
|
55
55
|
export declare function resolvedOwnershipRelease(): Promise<void>;
|
|
@@ -87,7 +87,9 @@ export declare class ElectedEngineUnconstructibleError extends Error {
|
|
|
87
87
|
*
|
|
88
88
|
* - **SW-direct.** The attempt lives in the SharedWorker and is left running (an in-flight store open cannot be
|
|
89
89
|
* safely abandoned — a second open against the same store is an ownership conflict). A later
|
|
90
|
-
* {@link attachSyncClient} ADOPTS it if it completed and
|
|
90
|
+
* {@link attachSyncClient} ADOPTS it if it completed, and waits on a genuinely stuck one only within the
|
|
91
|
+
* engine's spare-store adoption budget (`provisionAdoptionBudgetMs`, default 20000 from the attempt's start),
|
|
92
|
+
* past which that attach is refused with {@link ProvisionStalledError} instead of hanging; a retried
|
|
91
93
|
* provision re-acks against the SAME attempt, so a second open never starts. A stuck storage open blocks that
|
|
92
94
|
* store whether or not it was ever provisioned, and expiring this promise neither causes nor cures that.
|
|
93
95
|
* - **Elected.** This deadline is ALSO the provision claim's expiry, so the claim releases here too. When it is
|
|
@@ -108,10 +110,19 @@ export declare class ProvisionExpiredError extends Error {
|
|
|
108
110
|
}
|
|
109
111
|
/**
|
|
110
112
|
* Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
|
|
111
|
-
* (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the
|
|
113
|
+
* (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the pgwasm idb database. The destruction machine is
|
|
112
114
|
* backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
|
|
113
115
|
* the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
|
|
114
116
|
* unit-testable with fakes.
|
|
117
|
+
*
|
|
118
|
+
* **A context that cannot open OPFS at all** (ADR-0036 amendment, 2026-09-28): when an OPFS delete meets a root
|
|
119
|
+
* that rejects ({@link isOpfsRootUnavailableError} — WebKit's throwaway contexts, probably Safari private windows)
|
|
120
|
+
* the store there runs on IndexedDB, and destroy removes what it CAN reach: it durably records "OPFS deletion
|
|
121
|
+
* pending" for the store identity (in IndexedDB, {@link writeOpfsDeletionPending}) and carries on with the idb
|
|
122
|
+
* database and the meta record. The marker is written from the sentinel step, i.e. while the `deleting` record
|
|
123
|
+
* still stands, so the obligation to delete the OPFS side is never unrecorded; the next boot that can reach OPFS
|
|
124
|
+
* finishes it before opening anything (`store-boot.ts`). With no IndexedDB to record it in, the original failure
|
|
125
|
+
* propagates. A context that can open OPFS takes exactly the old path (ownership lock included).
|
|
115
126
|
*/
|
|
116
127
|
export declare function createStoreDestructionEffects(storePath: string, deps?: {
|
|
117
128
|
opfs?: OpfsEffectsDeps;
|
|
@@ -125,8 +136,10 @@ export declare function createStoreDestructionEffects(storePath: string, deps?:
|
|
|
125
136
|
* **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
|
|
126
137
|
* supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
|
|
127
138
|
* `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
|
|
128
|
-
* behind, a wipe of known store paths.
|
|
129
|
-
*
|
|
139
|
+
* behind, a wipe of known store paths. The OPFS delete first takes the store's ownership lock
|
|
140
|
+
* (`store-ownership-lock.ts`), so an owner that is still going away (a reloaded page's dying engine worker) is
|
|
141
|
+
* waited for, never raced. Called on a path a live engine still holds, it fails with `StoreOwnershipWaitError`
|
|
142
|
+
* after the bounded wait — loud, and safely RE-RUNNABLE: the destruction sequence is
|
|
130
143
|
* idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
|
|
131
144
|
* completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
|
|
132
145
|
* already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
|
|
@@ -343,8 +356,8 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
343
356
|
* OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
|
|
344
357
|
* `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
|
|
345
358
|
* against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
|
|
346
|
-
* worker's own `
|
|
347
|
-
* (the `openWithBoundedRetries` wrapper in `
|
|
359
|
+
* worker's own `createOpfsPgwasm` open throws the owned-store contention error and is retried with backoff
|
|
360
|
+
* (the `openWithBoundedRetries` wrapper in `createPgwasmClient`) until the dead worker's agent releases the
|
|
348
361
|
* handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
|
|
349
362
|
* until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
|
|
350
363
|
*/
|
|
@@ -370,9 +383,9 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
370
383
|
/**
|
|
371
384
|
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
372
385
|
* token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
|
|
373
|
-
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker
|
|
374
|
-
*
|
|
375
|
-
* `drizzle.transaction()`.
|
|
386
|
+
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker, and `isSynced`
|
|
387
|
+
* is answered from the worker-pushed started-state snapshot (ADR-0059); the members that throw are the
|
|
388
|
+
* structurally unproxiable ones — `pglite`, `dropReadCache`, and `drizzle.transaction()`.
|
|
376
389
|
*/
|
|
377
390
|
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
378
391
|
notifyAuthChanged: () => void;
|
|
@@ -407,7 +420,7 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
407
420
|
};
|
|
408
421
|
/**
|
|
409
422
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
410
|
-
* freshly-named spare `SharedWorker`: the worker runs
|
|
423
|
+
* freshly-named spare `SharedWorker`: the worker runs pgwasm `create`/initdb only and holds the raw store idle
|
|
411
424
|
* until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
|
|
412
425
|
* settled); rejects if the worker reports the create failed, if it refuses the storage declaration, if the elected
|
|
413
426
|
* engine is unconstructible, or — bounding the whole thing — with {@link ProvisionExpiredError} once
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attach-sync-client.d.ts","sourceRoot":"","sources":["../../src/worker/attach-sync-client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"attach-sync-client.d.ts","sourceRoot":"","sources":["../../src/worker/attach-sync-client.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAEV,iBAAiB,EACjB,sBAAsB,EAEtB,iBAAiB,EAElB,MAAM,sBAAsB,CAAC;AAI9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAMjD,OAAO,EAQL,KAAK,cAAc,EAEnB,KAAK,UAAU,EAGhB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,EAAiD,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEtG,OAAO,EAAE,KAAK,kBAAkB,EAAkB,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EAEL,KAAK,aAAa,EAGnB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAQL,KAAK,oBAAoB,EAE1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,KAAK,eAAe,EAIrB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAOL,K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1
1
|
import type { SyncStorageDeclaration, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
2
|
+
import type { PostgresBuild } from "@pgxsinkit/pgwasm";
|
|
2
3
|
import type { EventLaneOptions } from "../event-lane";
|
|
3
|
-
import { type
|
|
4
|
+
import { type PgwasmClient, type CreateSyncClientOptions, type SyncClient } from "../index";
|
|
4
5
|
import { type PlacementProbeResult } from "../placement-probe";
|
|
6
|
+
import { type StoreEngineModuleLoader } from "../store-engine";
|
|
5
7
|
import { type ExecutionLimitConfig } from "./engine-control";
|
|
6
8
|
import { type BridgeCodec, type BridgePort } from "./protocol";
|
|
7
9
|
import { type SwPlacementResult } from "./sw-placement";
|
|
@@ -21,13 +23,30 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
21
23
|
*/
|
|
22
24
|
resolveRegistry?: (role: string | undefined) => TRegistry | undefined;
|
|
23
25
|
/**
|
|
24
|
-
* How the worker creates its raw
|
|
25
|
-
* {@link
|
|
26
|
+
* How the worker creates its raw pgwasm store (provision + fresh-attach paths). Defaults to
|
|
27
|
+
* {@link createPgwasmClient}, which loads pgwasm's own boot assets — in a browser worker those hit the
|
|
26
28
|
* same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
|
|
27
29
|
* Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
|
|
28
30
|
*/
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
createStore?: (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>;
|
|
32
|
+
/**
|
|
33
|
+
* The Postgres build this worker's stores run on: the boot's own mint, the provision mint and every spare
|
|
34
|
+
* mint (never on the wire — code cannot cross it). Defaults to `cBuild`. Pass `createCBuild({ assets })` to
|
|
35
|
+
* boot over assets warmed in the worker. It must be the registry's declared `storage.build` (default
|
|
36
|
+
* `"c"`, ADR-0063): a mismatch throws `StorageBuildMismatchError` before any store is touched. A store a
|
|
37
|
+
* {@link createStore} factory returns is checked against its own `pg.build` the same way.
|
|
38
|
+
*/
|
|
39
|
+
build?: PostgresBuild;
|
|
40
|
+
/**
|
|
41
|
+
* How this scope imports a DECLARED store-engine module (ADR-0050 addendum 2026-09-08). Defaults to the
|
|
42
|
+
* scope's own dynamic `import()`; injected by a unit test that has no module to load. It is consulted
|
|
43
|
+
* only when the store's bound declaration carries `storage.engine`, and never for the built-in store.
|
|
44
|
+
*/
|
|
45
|
+
loadStoreEngineModule?: StoreEngineModuleLoader;
|
|
46
|
+
/** The pgxsinkit control plane — subscribe, token re-mint, convergence barrier (ADR-0055). */
|
|
47
|
+
controlPlaneUrl: string;
|
|
48
|
+
/** The edge that serves durable-streams reads. */
|
|
49
|
+
streamBaseUrl: string;
|
|
31
50
|
batchWriteUrl: string;
|
|
32
51
|
/** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
|
|
33
52
|
requestHeaders?: Record<string, string>;
|
|
@@ -43,9 +62,10 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
43
62
|
*/
|
|
44
63
|
batchEventUrl?: string;
|
|
45
64
|
/**
|
|
46
|
-
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff,
|
|
47
|
-
* per-Event-stream overrides. A worker-ENTRY option, never an
|
|
48
|
-
* engine-wide policy, and the Outbox it drains is shared by every
|
|
65
|
+
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, the
|
|
66
|
+
* acked ledger's retention (ADR-0060), and per-Event-stream overrides. A worker-ENTRY option, never an
|
|
67
|
+
* attach option — flush cadence is one engine-wide policy, and the Outbox it drains is shared by every
|
|
68
|
+
* attached tab.
|
|
49
69
|
*/
|
|
50
70
|
events?: EventLaneOptions;
|
|
51
71
|
/**
|
|
@@ -69,19 +89,32 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
69
89
|
* channel to probe, so an enabled value is rejected as unsupported before engine boot.
|
|
70
90
|
*/
|
|
71
91
|
executionLimit?: ExecutionLimitConfig;
|
|
92
|
+
/**
|
|
93
|
+
* How long an attach may wait for the engine's IN-FLIGHT spare provision (ADR-0032 decision 5) before it
|
|
94
|
+
* fails typed with {@link ProvisionStalledError} instead of waiting. Measured from the provision attempt's
|
|
95
|
+
* START, not from the attach — a tab attaching late inherits however much of the budget the spare has
|
|
96
|
+
* already burned. The stalled attempt is LEFT RUNNING (an in-flight OPFS/IDB store open cannot be safely
|
|
97
|
+
* abandoned — a second open against the same store is an ownership conflict), so a later attach still
|
|
98
|
+
* ADOPTS it if it completes; refusing costs at most one extra initdb, never data (the spare is schemaless
|
|
99
|
+
* and holds no writes). Default 20000. `Number.POSITIVE_INFINITY` restores the unbounded wait (NOT
|
|
100
|
+
* recommended: a stalled spare then hangs every attach forever). Must be > 0 — anything else throws at
|
|
101
|
+
* construction. This bounds the ACCELERATOR only; nothing is inferred from it about engine liveness
|
|
102
|
+
* (ADR-0049 D5's refusal of timing-based engine-death detection is unchanged).
|
|
103
|
+
*/
|
|
104
|
+
provisionAdoptionBudgetMs?: number;
|
|
72
105
|
/** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
|
|
73
106
|
installGlobal?: boolean;
|
|
74
107
|
/** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
|
|
75
108
|
codec?: BridgeCodec;
|
|
76
109
|
/**
|
|
77
|
-
* A raw
|
|
78
|
-
* {@link CreateSyncClientOptions.
|
|
110
|
+
* A raw pgwasm the worker uses instead of creating its own (forwarded to `createSyncClient`'s
|
|
111
|
+
* {@link CreateSyncClientOptions.precreatedPgwasm}) — the client still applies schema/reconcile. In a
|
|
79
112
|
* browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in
|
|
80
113
|
* tests, and the future spare-worker claim (ADR-0032 decision 5).
|
|
81
114
|
*/
|
|
82
|
-
|
|
83
|
-
/** A fully-provisioned
|
|
84
|
-
|
|
115
|
+
precreatedPgwasm?: CreateSyncClientOptions<TRegistry>["precreatedPgwasm"];
|
|
116
|
+
/** A fully-provisioned pgwasm (forwarded to {@link CreateSyncClientOptions.pgwasmInstance}; caller owns schema). */
|
|
117
|
+
pgwasmInstance?: CreateSyncClientOptions<TRegistry>["pgwasmInstance"];
|
|
85
118
|
/**
|
|
86
119
|
* App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
|
|
87
120
|
* schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
|
|
@@ -91,8 +124,8 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
91
124
|
* a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
|
|
92
125
|
* this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
|
|
93
126
|
*
|
|
94
|
-
* Runs on the storePath, {@link
|
|
95
|
-
* {@link
|
|
127
|
+
* Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
|
|
128
|
+
* {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
|
|
96
129
|
* runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
|
|
97
130
|
* invariant does not hold there.
|
|
98
131
|
*/
|
|
@@ -104,17 +137,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
104
137
|
* tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
|
|
105
138
|
* that depend on the registry's local tables, which DO exist by the time this runs.
|
|
106
139
|
*
|
|
107
|
-
* Runs on the storePath, {@link
|
|
108
|
-
* {@link
|
|
140
|
+
* Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
|
|
141
|
+
* {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there).
|
|
109
142
|
*/
|
|
110
143
|
prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
|
|
111
144
|
/**
|
|
112
145
|
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
|
|
113
|
-
* subscriber leaves, a nonzero effective keep-alive retains its
|
|
146
|
+
* subscriber leaves, a nonzero effective keep-alive retains its pgwasm registration + diff state for a grace
|
|
114
147
|
* period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
|
|
115
148
|
* re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
|
|
116
149
|
* down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
|
|
117
|
-
* full SQL rerun + diff on every dependent write —
|
|
150
|
+
* full SQL rerun + diff on every dependent write — pgwasm live queries cannot be paused — so retention
|
|
118
151
|
* only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
|
|
119
152
|
* no surprise standing SQL reruns.
|
|
120
153
|
*/
|