@pgxsinkit/client 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +10 -3
  5. package/dist/boot-report.d.ts +8 -8
  6. package/dist/circuits/envelope-to-change.d.ts +9 -5
  7. package/dist/circuits/envelope-to-change.d.ts.map +1 -1
  8. package/dist/circuits/group-sync.d.ts +2 -2
  9. package/dist/circuits/group-sync.d.ts.map +1 -1
  10. package/dist/circuits/stream-source.d.ts +6 -0
  11. package/dist/circuits/stream-source.d.ts.map +1 -1
  12. package/dist/circuits/sync-engine.d.ts +2 -2
  13. package/dist/circuits/sync-engine.d.ts.map +1 -1
  14. package/dist/event-lane.d.ts +32 -1
  15. package/dist/event-lane.d.ts.map +1 -1
  16. package/dist/export-data.d.ts +3 -3
  17. package/dist/export-dump.d.ts +10 -10
  18. package/dist/export-dump.d.ts.map +1 -1
  19. package/dist/export-store.d.ts +13 -13
  20. package/dist/index.d.ts +196 -100
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1044 -487
  23. package/dist/index.js.map +39 -36
  24. package/dist/local-store.d.ts +1 -1
  25. package/dist/local-store.d.ts.map +1 -1
  26. package/dist/local-tables.d.ts +58 -0
  27. package/dist/local-tables.d.ts.map +1 -1
  28. package/dist/mutation.d.ts +2 -2
  29. package/dist/mutation.d.ts.map +1 -1
  30. package/dist/mutations-api.d.ts +1 -1
  31. package/dist/mutations-api.d.ts.map +1 -1
  32. package/dist/opfs-effects.d.ts +30 -2
  33. package/dist/opfs-effects.d.ts.map +1 -1
  34. package/dist/schema.d.ts +12 -1
  35. package/dist/schema.d.ts.map +1 -1
  36. package/dist/store-boot.d.ts +30 -2
  37. package/dist/store-boot.d.ts.map +1 -1
  38. package/dist/store-build.d.ts +19 -0
  39. package/dist/store-build.d.ts.map +1 -0
  40. package/dist/store-engine.d.ts +22 -0
  41. package/dist/store-engine.d.ts.map +1 -0
  42. package/dist/store-meta.d.ts +29 -3
  43. package/dist/store-meta.d.ts.map +1 -1
  44. package/dist/store-ownership-lock.d.ts +33 -0
  45. package/dist/store-ownership-lock.d.ts.map +1 -0
  46. package/dist/store-path.d.ts +43 -31
  47. package/dist/store-path.d.ts.map +1 -1
  48. package/dist/sync/apply.d.ts +5 -5
  49. package/dist/sync/apply.d.ts.map +1 -1
  50. package/dist/sync/copy.d.ts +82 -6
  51. package/dist/sync/copy.d.ts.map +1 -1
  52. package/dist/sync/drizzle-executor.d.ts +4 -4
  53. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  54. package/dist/sync/subscription-state.d.ts +5 -5
  55. package/dist/sync/subscription-state.d.ts.map +1 -1
  56. package/dist/testing.d.ts +1 -1
  57. package/dist/testing.js +2 -1
  58. package/dist/testing.js.map +4 -4
  59. package/dist/worker/attach-sync-client.d.ts +24 -13
  60. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  61. package/dist/worker/define-sync-worker.d.ts +35 -18
  62. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  63. package/dist/worker/live-query-manager.d.ts +3 -3
  64. package/dist/worker/live-query-manager.d.ts.map +1 -1
  65. package/dist/worker/live-query-params-guard.d.ts +5 -5
  66. package/dist/worker/live-query-params-guard.d.ts.map +1 -1
  67. package/dist/worker/protocol.d.ts +26 -7
  68. package/dist/worker/protocol.d.ts.map +1 -1
  69. package/package.json +11 -8
  70. package/skills/core/SKILL.md +80 -15
  71. package/skills/operating/SKILL.md +129 -129
  72. package/skills/operating/references/postgres-builds.md +48 -0
  73. package/src/boot-report.ts +12 -12
  74. package/src/circuits/envelope-to-change.ts +121 -12
  75. package/src/circuits/group-sync.ts +2 -2
  76. package/src/circuits/stream-source.ts +35 -9
  77. package/src/circuits/sync-engine.ts +6 -4
  78. package/src/event-lane.ts +132 -14
  79. package/src/export-data.ts +4 -4
  80. package/src/export-dump.ts +31 -36
  81. package/src/export-store.ts +20 -20
  82. package/src/index.ts +576 -340
  83. package/src/live-rows-sql.ts +1 -1
  84. package/src/local-store.ts +2 -2
  85. package/src/local-tables.ts +70 -6
  86. package/src/mutation.ts +9 -8
  87. package/src/mutations-api.ts +4 -4
  88. package/src/opfs-effects.ts +74 -10
  89. package/src/schema.ts +124 -18
  90. package/src/store-boot.ts +71 -7
  91. package/src/store-build.ts +37 -0
  92. package/src/store-engine.ts +94 -0
  93. package/src/store-lifecycle.ts +1 -1
  94. package/src/store-meta.ts +155 -4
  95. package/src/store-ownership-lock.ts +109 -0
  96. package/src/store-path.ts +59 -43
  97. package/src/sync/apply.ts +32 -46
  98. package/src/sync/copy.ts +108 -13
  99. package/src/sync/drizzle-executor.ts +18 -19
  100. package/src/sync/metadata-tables.ts +1 -1
  101. package/src/sync/subscription-state.ts +7 -7
  102. package/src/testing.ts +3 -3
  103. package/src/worker/attach-sync-client.ts +146 -60
  104. package/src/worker/define-sync-worker.ts +212 -83
  105. package/src/worker/engine-router.ts +1 -1
  106. package/src/worker/live-query-fingerprint.ts +4 -4
  107. package/src/worker/live-query-manager.ts +12 -12
  108. package/src/worker/live-query-params-guard.ts +16 -15
  109. package/src/worker/protocol.ts +38 -7
@@ -1,3 +1,4 @@
1
+ import type { StorageDescription } from "@pgxsinkit/pgwasm";
1
2
  /**
2
3
  * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or
3
4
  * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the
@@ -8,14 +9,15 @@ export declare class InvalidStorePathError extends Error {
8
9
  constructor(message: string);
9
10
  }
10
11
  /**
11
- * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /
12
- * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its
13
- * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins
14
- * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a
15
- * consumer is never left guessing which store to hand us instead.
12
+ * Thrown when a caller-owned store handed to {@link CreateSyncClientOptions.pgwasmInstance} /
13
+ * {@link CreateSyncClientOptions.precreatedPgwasm} is PROVABLY non-persistent (ADR-0036 decision 4): its
14
+ * `storage` is memory (pgwasm's default — the bare `createPgwasm({ build })` a copy-paste reaches — or an
15
+ * explicit `memory://`), or a filesystem that explicitly reports itself non-persistent. Names both the why (durability
16
+ * semantics assume a persisted store) and the two exits, so a consumer is never left guessing which store to
17
+ * hand us instead.
16
18
  */
17
19
  export declare class NonPersistentStoreError extends Error {
18
- constructor(observed: "in-memory-default" | "memory-scheme");
20
+ constructor(observed: NonPersistentStorage);
19
21
  }
20
22
  /**
21
23
  * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY
@@ -52,10 +54,10 @@ export type WithTestStoreMarker = {
52
54
  /** Read the internal testing marker off an options object, or `undefined` when none was stamped. */
53
55
  export declare function readTestStoreMarker(options: unknown): TestStoreMarker | undefined;
54
56
  /**
55
- * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain
57
+ * What {@link createPgwasmClient} (and any store-opening seam) accepts as its store argument: a plain
56
58
  * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a
57
59
  * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing
58
- * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests("x"))` without a consumer ever
60
+ * helper's output flow STRAIGHT into `createPgwasmClient(memoryStoreForTests("x"))` without a consumer ever
59
61
  * naming a backend.
60
62
  */
61
63
  export type StorePathInput = string | ({
@@ -68,7 +70,7 @@ export declare function normaliseStorePathInput(input: StorePathInput): {
68
70
  };
69
71
  /**
70
72
  * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in
71
- * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's
73
+ * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: pgwasm's
72
74
  * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but
73
75
  * Bun/Node do not — so it distinguishes "run in the browser" (idb) from "run on the server" (filesystem)
74
76
  * without a DOM-lib dependency.
@@ -86,7 +88,7 @@ export interface StoreEnv {
86
88
  hasOpfsSyncAccess?: boolean;
87
89
  }
88
90
  /**
89
- * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
91
+ * Resolve a plain {@link storePath} to the pgwasm dataDir URL the store opens at — the ONE derivation point
90
92
  * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves
91
93
  * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;
92
94
  * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`
@@ -96,16 +98,16 @@ export interface StoreEnv {
96
98
  * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is
97
99
  * internal plumbing; do not surface it to consumers as something to imitate.
98
100
  *
99
- * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
100
- * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
101
- * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
102
- * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
101
+ * CRITICAL (ADR-0036 decision 5, probed before the pgwasm switch — ADR-0062): memory selection is ALWAYS the
102
+ * scheme-selected `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an
103
+ * explicit-`fs` instance silently omits relation files created after initdb, so a restored clone raises "relation
104
+ * does not exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
103
105
  *
104
106
  * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
105
107
  * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
106
108
  * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →
107
- * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;
108
- * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
109
+ * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — pgwasm does NOT accept it as a `dataDir`;
110
+ * {@link createPgwasmClient} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
109
111
  * builders below. Like every URL resolved here, it never leaks to consumers.
110
112
  */
111
113
  export declare function resolveStoreDataDir(storePath: string, backendOverride?: "memory", env?: StoreEnv): string;
@@ -132,8 +134,8 @@ export declare function storeIdentityComponent(storePath: string): string;
132
134
  * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,
133
135
  * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `"foo"`'s
134
136
  * commitment sentinel vs a store literally named `"foo.committed"`). This module is the ONLY place that knows
135
- * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`
136
- * prefix.
137
+ * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the client's sole route to the
138
+ * IndexedDB database names.
137
139
  */
138
140
  export declare const OPFS_TOOLKIT_CONTAINER = "pgxsinkit";
139
141
  /**
@@ -148,6 +150,13 @@ export declare function opfsStoreDirectoryPath(storePath: string): readonly [str
148
150
  * string, for the same `getDirectoryHandle`-chain reason.
149
151
  */
150
152
  export declare function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string];
153
+ /**
154
+ * The Web Lock name of a store's OPFS OWNERSHIP (`store-ownership-lock.ts`): held EXCLUSIVELY by the context
155
+ * that holds the store directory's sync-access handles, from before it opens them until after it closes them,
156
+ * and taken by anything that deletes the directory. Keyed on the same injective identity as the OPFS paths, so
157
+ * two valid identities never share a lock.
158
+ */
159
+ export declare function storeOwnershipLockName(storePath: string): string;
151
160
  /**
152
161
  * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No
153
162
  * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.
@@ -155,22 +164,25 @@ export declare function opfsCommitmentSentinelPath(storePath: string): readonly
155
164
  export declare function opfsProbeDirectoryPath(): readonly [string, string];
156
165
  /**
157
166
  * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for
158
- * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite
159
- * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`
160
- * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a
161
- * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather
162
- * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as
167
+ * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. pgwasm
168
+ * maps `idb://<storePath>` to the IndexedDB database `/pgwasm/<storePath>` (the IDBFS mount point: its root
169
+ * `/pgwasm` joined with the path after the scheme), and the name comes from `@pgxsinkit/pgwasm-c`'s own
170
+ * `idbDatabaseName`, never re-encoded here. Exposed so a consumer that GCs its own stores routes that
171
+ * pgwasm-internal naming knowledge through the library rather than re-deriving the prefix itself. Rejects a scheme-bearing/empty path exactly as
163
172
  * {@link resolveStoreDataDir} does, so the two stay in lockstep.
164
173
  */
165
174
  export declare function storeIndexedDbDatabaseName(storePath: string): string;
175
+ /** The provably-non-persistent storage shapes {@link classifyNonPersistentStorage} reports. */
176
+ export type NonPersistentStorage = "memory" | "non-persistent-vfs";
166
177
  /**
167
- * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending
168
- * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a
169
- * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,
170
- * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the
171
- * two accidental non-persistent shapes, it is not a storage-backend whitelist).
178
+ * Classify a store's own `pg.storage` for the BYO refusal (ADR-0036 decision 4). Returns the offending shape
179
+ * when the store is PROVABLY non-persistent (`memory`, pgwasm's default or an explicit `memory://`; a `vfs`
180
+ * filesystem explicitly reporting `persistent: false`), or `null` when it passes: `idb`, `file`, a persistent
181
+ * `vfs` (the OPFS-repacked store) and a `vfs` that doesn't declare its persistence (a custom filesystem is
182
+ * the caller's own call). The guard catches the accidental non-persistent shapes; it is not a
183
+ * storage-backend whitelist.
172
184
  */
173
- export declare function classifyNonPersistentDataDir(dataDir: string | undefined): "in-memory-default" | "memory-scheme" | null;
185
+ export declare function classifyNonPersistentStorage(storage: StorageDescription): NonPersistentStorage | null;
174
186
  /**
175
187
  * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target
176
188
  * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:
@@ -181,7 +193,7 @@ export declare function classifyNonPersistentDataDir(dataDir: string | undefined
181
193
  * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported
182
194
  * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
183
195
  * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
184
- * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
196
+ * exactly as pgwasm's filesystem backend and {@link resolveStoreDataDir} do.
185
197
  * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at
186
198
  * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via
187
199
  * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is
@@ -196,7 +208,7 @@ export declare function classifyNonPersistentDataDir(dataDir: string | undefined
196
208
  * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
197
209
  * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
198
210
  * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a
199
- * PGlite-level boot failure. We never fake a positive.
211
+ * pgwasm-level boot failure. We never fake a positive.
200
212
  */
201
213
  export declare function storeTargetExists(storePath: string, backendOverride?: "memory", env?: StoreEnv): Promise<boolean>;
202
214
  //# sourceMappingURL=store-path.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"store-path.d.ts","sourceRoot":"","sources":["../src/store-path.ts"],"names":[],"mappings":"AAsBA;;;;;GAKG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAED;;;;;;GAMG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,YAAY,QAAQ,EAAE,mBAAmB,GAAG,eAAe,EAa1D;CACF;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAY,SAAS,EAAE,MAAM,EAQ5B;CACF;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAA0D,CAAC;AAEnG;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,cAAc,CAAC;AAExD,2GAA2G;AAC3G,MAAM,MAAM,mBAAmB,GAAG;IAAE,CAAC,kBAAkB,CAAC,CAAC,EAAE,eAAe,CAAA;CAAE,CAAC;AAE7E,oGAAoG;AACpG,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,GAAG,SAAS,CAIjF;AAED;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,CAAC;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,mBAAmB,CAAC,CAAC;AAEpF,+GAA+G;AAC/G,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,eAAe,CA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AAM,EACjB,eAAe,CAAC,EAAE,QAAQ,EAC1B,GAAG,GAAE,QAA2B,GAC/B,MAAM,CAKR;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CA8BhE;AAED;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,cAAc,CAAC;AAElD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAE3F;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAE/F;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAElE;AAED;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAYpE;AAED,+FAA+F;AAC/F,MAAM,MAAM,oBAAoB,GAAG,QAAQ,GAAG,oBAAoB,CAAC;AAEnE;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,kBAAkB,GAAG,oBAAoB,GAAG,IAAI,CAIrG;AAWD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,EACjB,eAAe,CAAC,EAAE,QAAQ,EAC1B,GAAG,GAAE,QAA2B,GAC/B,OAAO,CAAC,OAAO,CAAC,CA2ClB"}
@@ -1,16 +1,16 @@
1
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
2
1
  import { type SyncChange } from "@pgxsinkit/contracts";
2
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
3
3
  import type { ApplyTarget } from "../local-tables";
4
4
  import type { UpsertChangeMessage } from "./types";
5
5
  export interface ApplyMessageToTableOptions {
6
- pg: PGliteInterface | Transaction;
6
+ pg: Pgwasm | Transaction;
7
7
  target: ApplyTarget;
8
8
  message: SyncChange;
9
9
  debug: boolean;
10
10
  }
11
- export declare function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions): Promise<import("@electric-sql/pglite").Results<never>>;
11
+ export declare function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions): Promise<import("@pgxsinkit/pgwasm").Results<never>>;
12
12
  export interface BulkApplyMessagesToTableOptions {
13
- pg: PGliteInterface | Transaction;
13
+ pg: Pgwasm | Transaction;
14
14
  target: ApplyTarget;
15
15
  messages: UpsertChangeMessage[];
16
16
  debug: boolean;
@@ -40,7 +40,7 @@ export declare function applyMessagesToTableWithJson(options: BulkApplyMessagesT
40
40
  export declare function applyUpsertsToTableWithJson(options: BulkApplyMessagesToTableOptions): Promise<void>;
41
41
  export declare function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions): Promise<void>;
42
42
  export interface BulkKeyedApplyOptions {
43
- pg: PGliteInterface | Transaction;
43
+ pg: Pgwasm | Transaction;
44
44
  target: ApplyTarget;
45
45
  /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */
46
46
  messages: SyncChange[];
@@ -1 +1 @@
1
- {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../src/sync/apply.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAIzE,OAAO,EAAmB,KAAK,UAAU,EAAqC,MAAM,sBAAsB,CAAC;AAE3G,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGnD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA4EnD,MAAM,WAAW,0BAA0B;IACzC,EAAE,EA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AAqB;IACpC,EAAE,EAAE,MAAM,GAAG,WAAW,CAAC;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,qGAAqG;IACrG,QAAQ,EAAE,UAAU,EAAE,CAAC;IACvB,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,qBAAqB,iBA+BnG"}
@@ -2,15 +2,23 @@
2
2
  * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT
3
3
  * text)` stream.
4
4
  *
5
- * Values reach this module already decoded — the read path hands the applier
6
- * JSON cell values, never Postgres wire text — so the runtime types it accepts
7
- * are the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
8
- * `boolean`, `json`/`jsonb` as parsed objects/arrays, array columns as
9
- * (possibly nested) JS arrays, `int8` as `bigint`, and every other type as its
10
- * raw Postgres text representation (a `string`). To feed those values back into
5
+ * Values reach this module already decoded, so the runtime types it accepts are
6
+ * the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
7
+ * `boolean`, `json`/`jsonb` as parsed objects/arrays/scalars, `int8` as
8
+ * `bigint`, and every other type — **array columns included** — as its raw
9
+ * Postgres text representation (a `string`). To feed those values back into
11
10
  * `COPY` we have to reverse that: turn each value into the exact text Postgres'
12
11
  * input functions expect, then apply the COPY framing.
13
12
  *
13
+ * Only the json ones are decoded on the way in, and by exactly one step:
14
+ * `envelopeToChange`'s `decodeJsonColumns` (`../circuits/envelope-to-change`).
15
+ * The wire itself carries EVERY non-int/float/bool cell as Postgres output text
16
+ * — a `jsonb` column included — so without that step the `JSON.stringify` below
17
+ * would encode already-encoded JSON a second time and the column would land as a
18
+ * JSON string scalar. An array column's `array_out` text is deliberately left
19
+ * alone: it passes through {@link valueToText} unchanged and `COPY`'s `array_in`
20
+ * parses it, which is why a `json[]` value here is a `string`, not a JS array.
21
+ *
14
22
  * Rather than invent an escaping scheme (the previous CSV-based approach broke
15
23
  * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the
16
24
  * two relevant PostgreSQL backend routines:
@@ -22,6 +30,8 @@
22
30
  * internally, has a single well-defined escaping algorithm, and round-trips
23
31
  * every built-in type.
24
32
  */
33
+ import { type AnyPgTable } from "drizzle-orm/pg-core";
34
+ import type { RawStatement } from "../index";
25
35
  /**
26
36
  * Serialize a single value into one COPY TEXT field. `null`/`undefined` become
27
37
  * the NULL marker (`\N`); everything else is converted to text and escaped.
@@ -29,6 +39,14 @@
29
39
  * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates
30
40
  * `json`/`jsonb` columns; when omitted the value's runtime type is used (which
31
41
  * cannot tell a `jsonb` array from a SQL array).
42
+ *
43
+ * PUBLIC (re-exported from the package root) so an app that bulk-loads a table
44
+ * pgxsinkit does not manage writes the SAME COPY TEXT the applier does. The
45
+ * value contract is the one this module's header states: numbers/booleans/
46
+ * bigints as JS primitives, `json`/`jsonb` as **parsed** values (an object, an
47
+ * array, or a scalar — never pre-stringified JSON, which would land as a JSON
48
+ * string), a `Date` or its text for the temporal types, a JS array (or the
49
+ * Postgres array text) for an array column, and every other type as a `string`.
32
50
  */
33
51
  export declare function serializeCopyValue(value: unknown, udtName?: string): string;
34
52
  /**
@@ -38,6 +56,64 @@ export declare function serializeCopyValue(value: unknown, udtName?: string): st
38
56
  *
39
57
  * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass
40
58
  * it so `json`/`jsonb` columns serialize correctly.
59
+ *
60
+ * PUBLIC (re-exported from the package root) for an app-owned, pgxsinkit-unmanaged
61
+ * table. Two contracts bind the caller:
62
+ *
63
+ * - **`columns` IS the column list of the COPY statement.** The fields are
64
+ * emitted in exactly this order, so the same array must be named — in the
65
+ * same order — in the `COPY <table> (...)` that ingests the bytes.
66
+ * {@link buildCopyFromBlobStatement} renders both from one array so they
67
+ * cannot drift.
68
+ * - **`columnTypes` keys are DB column names, values are Postgres `udt_name`s**
69
+ * (`text`, `int4`, `jsonb`, `timestamptz`, `_text` for `text[]`, …). Only the
70
+ * json ones (`json`/`jsonb`/`_json`/`_jsonb`) change behaviour — everything
71
+ * else dispatches on the value's runtime type — but passing the full map is
72
+ * harmless. A `json`/`jsonb` value MUST be the parsed value, per
73
+ * {@link serializeCopyValue}.
41
74
  */
42
75
  export declare function generateCopyData(rows: ReadonlyArray<Record<string, unknown>>, columns: ReadonlyArray<string>, columnTypes?: Readonly<Record<string, string | undefined>>): string;
76
+ /** The inputs {@link buildCopyFromBlobStatement} renders a COPY-from-blob statement from. */
77
+ export interface CopyFromBlobStatementOptions {
78
+ /**
79
+ * The REAL Drizzle table object to load into — the identifier is read off it with `getTableConfig`,
80
+ * never taken as a hand-written string, so a rename can never leave a stale name in the SQL. A bare
81
+ * (schemaless) table renders unqualified and resolves through `search_path` (that is how the applier
82
+ * reaches an ephemeral relation in `pg_temp`).
83
+ */
84
+ table: AnyPgTable;
85
+ /**
86
+ * The DB column names to load, in order. ONE array drives both halves of the statement: the COPY
87
+ * column list and the field order of the serialized body, so they cannot drift.
88
+ */
89
+ columns: readonly string[];
90
+ /** The rows to load, keyed by DB column name (a key missing from a row is loaded as NULL). */
91
+ rows: ReadonlyArray<Record<string, unknown>>;
92
+ /**
93
+ * DB column name → Postgres `udt_name`, per {@link generateCopyData}. Needed for `json`/`jsonb`
94
+ * (and `_json`/`_jsonb`) columns; ignored for every other type.
95
+ */
96
+ udtNames?: Readonly<Record<string, string | undefined>>;
97
+ }
98
+ /**
99
+ * Render the `COPY <table> (<columns>) FROM '/dev/blob' WITH (FORMAT text)` statement for `rows`,
100
+ * together with the COPY TEXT bytes pgwasm must read for it — a {@link RawStatement} whose `blob`
101
+ * carries the body (narrowed to a non-optional `blob`: this builder ALWAYS produces one).
102
+ *
103
+ * This is the ONE implementation of the COPY-from-blob load: the sync applier's bulk path
104
+ * (`applyMessagesToTableWithCopy`) and the public raw seam both call it, so an app-owned table
105
+ * bulk-loads on exactly the contract the applier is tested against.
106
+ *
107
+ * Hand it to `rawTransaction` (to bulk-load inside one local transaction, e.g. delete-then-COPY) or
108
+ * to `rawQuery`'s `blob` option for a single statement. On a worker-attached client the bytes are
109
+ * TRANSFERRED, not copied — see {@link RawStatement.blob}: the buffer is detached after the call.
110
+ *
111
+ * Tier ③ (ADR-0028 allow-list), exactly as the applier's copy of this statement was: `COPY … FROM
112
+ * '/dev/blob'` is pgwasm's blob-ingest grammar and has NO Drizzle builder form, so the statement text
113
+ * stays a raw string. Every identifier in it is still derived — the table from `getTableConfig`, each
114
+ * column through `quoteIdentifier` — so nothing in the string is a hand-written identifier.
115
+ */
116
+ export declare function buildCopyFromBlobStatement({ table, columns, rows, udtNames, }: CopyFromBlobStatementOptions): RawStatement & {
117
+ blob: Uint8Array<ArrayBuffer>;
118
+ };
43
119
  //# sourceMappingURL=copy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"copy.d.ts","sourceRoot":"","sources":["../../src/sync/copy.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAkJH;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAO3E;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EAC5C,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,EAC9B,WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,GACzD,MAAM,CAIR"}
1
+ {"version":3,"file":"copy.d.ts","sourceRoot":"","sources":["../../src/sync/copy.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,KAAK,UAAU,EAAkB,MAAM,qBAAqB,CAAC;AAItE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAkJ7C;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAO3E;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EAC5C,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,EAC9B,WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,GACzD,MAAM,CAIR;AAKD,6FAA6F;AAC7F,MAAM,WAAW,4BAA4B;IAC3C;;;;;OAKG;IACH,KAAK,EAAE,UAAU,CAAC;IAClB;;;OAGG;IACH,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,8FAA8F;IAC9F,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC7C;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;CACzD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,KAAK,EACL,OAAO,EACP,IAAI,EACJ,QAAQ,GACT,EAAE,4BAA4B,GAAG,YAAY,GAAG;IAAE,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAA;CAAE,CAQjF"}
@@ -1,5 +1,5 @@
1
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
2
- import { type PgliteDatabase } from "drizzle-orm/pglite";
3
- /** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */
4
- export declare function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never>;
1
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
2
+ import { type PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
3
+ /** A (memoized) Drizzle handle over an open pgwasm connection or transaction — engine-internal. */
4
+ export declare function drizzleOverPg(pg: Pgwasm | Transaction): PgwasmDatabase<never>;
5
5
  //# sourceMappingURL=drizzle-executor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-executor.d.ts","sourceRoot":"","sources":["../../src/sync/drizzle-executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACjF,OAAO,EAAW,KAAK,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAsClE,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,EAAE,EAAE,eAAe,GAAG,WAAW,GAAG,cAAc,CAAC,KAAK,CAAC,CAOtF"}
1
+ {"version":3,"file":"drizzle-executor.d.ts","sourceRoot":"","sources":["../../src/sync/drizzle-executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAW,KAAK,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAqCzE,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,GAAG,cAAc,CAAC,KAAK,CAAC,CAO7E"}
@@ -1,5 +1,5 @@
1
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
2
1
  import { type PredicateValue } from "@pgxsinkit/contracts";
2
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
3
3
  import { type Lsn, type SubscriptionKey } from "./types";
4
4
  export interface SubscriptionState {
5
5
  key: SubscriptionKey;
@@ -30,7 +30,7 @@ export interface ShapeSubscriptionState {
30
30
  scope?: readonly PredicateValue[];
31
31
  }
32
32
  export interface GetSubscriptionStateOptions {
33
- readonly pg: PGliteInterface | Transaction;
33
+ readonly pg: Pgwasm | Transaction;
34
34
  readonly metadataSchema: string;
35
35
  readonly subscriptionKey: SubscriptionKey;
36
36
  /**
@@ -42,7 +42,7 @@ export interface GetSubscriptionStateOptions {
42
42
  }
43
43
  export declare function getSubscriptionState({ pg, metadataSchema, subscriptionKey, sessionScoped, }: GetSubscriptionStateOptions): Promise<SubscriptionState | null>;
44
44
  export interface UpdateSubscriptionStateOptions {
45
- pg: PGliteInterface | Transaction;
45
+ pg: Pgwasm | Transaction;
46
46
  metadataSchema: string;
47
47
  subscriptionKey: SubscriptionKey;
48
48
  shapeMetadata: Record<string, ShapeSubscriptionState>;
@@ -53,13 +53,13 @@ export interface UpdateSubscriptionStateOptions {
53
53
  }
54
54
  export declare function updateSubscriptionState({ pg, metadataSchema, subscriptionKey, shapeMetadata, lastLsn, debug, sessionScoped, }: UpdateSubscriptionStateOptions): Promise<void>;
55
55
  export interface DeleteSubscriptionStateOptions {
56
- pg: PGliteInterface | Transaction;
56
+ pg: Pgwasm | Transaction;
57
57
  metadataSchema: string;
58
58
  subscriptionKey: SubscriptionKey;
59
59
  }
60
60
  export declare function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions): Promise<void>;
61
61
  export interface MigrateSubscriptionMetadataTablesOptions {
62
- pg: PGliteInterface | Transaction;
62
+ pg: Pgwasm | Transaction;
63
63
  metadataSchema: string;
64
64
  }
65
65
  export declare function migrateSubscriptionMetadataTables({ pg, metadataSchema, }: MigrateSubscriptionMetadataTablesOptions): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/sync/subscription-state.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGzE,OAAO,EAAmB,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAK5E,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,eAAe,EAAE,M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;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;CAClC;AAED,wBAAsB,oBAAoB,CAAC,EACzC,EAAE,EACF,cAAc,EACd,eAAe,EACf,aAAqB,GACtB,EAAE,2BAA2B,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAiCjE;AAED,MAAM,WAAW,8BAA8B;IAC7C,EAAE,EAAE,MAAM,GAAG,WAAW,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,eAAe,CAAC;IACjC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;IACtD,OAAO,EAAE,GAAG,CAAC;IACb,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,4FAA4F;IAC5F,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,wBAAsB,uBAAuB,CAAC,EAC5C,EAAE,EACF,cAAc,EACd,eAAe,EACf,aAAa,EACb,OAAO,EACP,KAAK,EACL,aAAqB,GACtB,EAAE,8BAA8B,iBAchC;AAED,MAAM,WAAW,8BAA8B;IAC7C,EAAE,EAAE,MAAM,GAAG,WAAW,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,eAAe,CAAC;CAClC;AAED,wBAAsB,uBAAuB,CAAC,EAAE,EAAE,EAAE,cAAc,EAAE,eAAe,EAAE,EAAE,8BAA8B,iBAUpH;AAED,MAAM,WAAW,wCAAwC;IACvD,EAAE,EAAE,MAAM,GAAG,WAAW,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,wBAAsB,iCAAiC,CAAC,EACtD,EAAE,EACF,cAAc,GACf,EAAE,wCAAwC,iBAsB1C"}
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
- * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.
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
@@ -14,4 +15,4 @@ export {
14
15
  testStoreAcknowledgment
15
16
  };
16
17
 
17
- //# debugId=70F1E266BD33AAED64756E2164756E21
18
+ //# debugId=3C36F3E738F6693364756E2164756E21
@@ -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`/`createClientPGlite` 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(), pgliteInstance, 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 * PGlite via `pgliteInstance` / `precreatedPglite`. 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"
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 before the pgwasm switch — ADR-0062): memory selection is ALWAYS the\n * scheme-selected `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an\n * explicit-`fs` instance silently omits relation files created after initdb, so a restored clone raises \"relation\n * does not 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": ";;AAwFO,IAAM,qBAAoC,OAAO,IAAI,qCAAqC;;;ACrD1F,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": "70F1E266BD33AAED64756E2164756E21",
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
  }