@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
package/src/store-boot.ts CHANGED
@@ -26,13 +26,15 @@
26
26
  // 10b/11. The returned {@link StoreBootResolution.verdict} tells the caller a candidate is uncommitted and
27
27
  // needs that barrier.
28
28
 
29
- import { createOpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
29
+ import { createOpfsEffects, isOpfsRootUnavailableError, type OpfsEffectsDeps } from "./opfs-effects";
30
30
  import { beginFreshCandidate, resumeDeletion } from "./store-lifecycle";
31
31
  import {
32
32
  classifyStoreBoot,
33
+ clearOpfsDeletionPending,
33
34
  deleteStoreMetaRecord,
34
35
  idbStoreExists as defaultIdbStoreExists,
35
36
  META_STORE_UNAVAILABLE,
37
+ readOpfsDeletionPending,
36
38
  readStoreMetaRecord,
37
39
  type StoreBootVerdict,
38
40
  type StoreMetaDeps,
@@ -51,7 +53,7 @@ export type ResolvedStorageBackend = "opfs-repacked" | "idbfs" | "filesystem" |
51
53
 
52
54
  /** The outcome of {@link resolveStoreBoot}: the URL to open the store at, its backend, and the boot verdict. */
53
55
  export interface StoreBootResolution {
54
- /** The PGlite dataDir URL, always assembled by {@link resolveStoreDataDir} (the one URL assembler). */
56
+ /** The pgwasm dataDir URL, always assembled by {@link resolveStoreDataDir} (the one URL assembler). */
55
57
  dataDir: string;
56
58
  /** The resolved backend, for diagnostics. */
57
59
  storageBackend: ResolvedStorageBackend;
@@ -109,9 +111,9 @@ function resolveDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undefine
109
111
  }
110
112
 
111
113
  /**
112
- * Delete-if-present the PGlite idb database for a store (`indexedDB.deleteDatabase`), backend-agnostic and
114
+ * Delete-if-present the pgwasm idb database for a store (`indexedDB.deleteDatabase`), backend-agnostic and
113
115
  * idempotent: absent counts as deleted, while a real failure rejects. The database name comes
114
- * ONLY from {@link storeIndexedDbDatabaseName} (store-path's sole owner of PGlite's `/pglite/` naming).
116
+ * ONLY from {@link storeIndexedDbDatabaseName} (store-path's sole route to pgwasm's IndexedDB naming).
115
117
  */
116
118
  function deleteIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
117
119
  const idb = resolveDeleteSurface(meta);
@@ -221,6 +223,39 @@ export function committedStoreUnreachableFromWire(detail: unknown): CommittedSto
221
223
  return new CommittedStoreUnreachableError(candidate.storePath);
222
224
  }
223
225
 
226
+ /** The outcome of {@link settlePendingOpfsDeletion}. */
227
+ export type PendingOpfsDeletionOutcome = "none" | "settled" | "still-pending";
228
+
229
+ /**
230
+ * Settle an "OPFS deletion pending" marker (ADR-0036 amendment, 2026-09-28) — the FIRST thing every browser boot
231
+ * does, before any classification or open. A store destroyed in a context that could not open OPFS at all left
232
+ * its OPFS store directory and commitment sentinel (if it ever had them) behind, with the marker as the durable
233
+ * obligation. When this boot can reach OPFS it deletes the sentinel, then the store directory (under the
234
+ * store's ownership lock), and only then clears the marker — so a leftover sentinel never reaches the classifier
235
+ * as "no record + sentinel" (`repair-record-then-open-committed`, which would reopen destroyed data). When it
236
+ * still cannot reach OPFS (the namespace is unobservable, or the root rejects mid-settlement) the marker stays
237
+ * and the boot proceeds: such a context cannot open an OPFS store anyway.
238
+ *
239
+ * An unreadable marker propagates ({@link StoreMetaUnreadableError}) — never read as "no marker".
240
+ */
241
+ export async function settlePendingOpfsDeletion(
242
+ storePath: string,
243
+ deps?: ResolveStoreBootOptions["deps"],
244
+ ): Promise<PendingOpfsDeletionOutcome> {
245
+ if (!(await readOpfsDeletionPending(storePath, deps?.meta))) return "none";
246
+ const effects = createOpfsEffects(storePath, deps?.opfs);
247
+ if ((await effects.observeCommitmentNamespace()) === "unobservable") return "still-pending";
248
+ try {
249
+ await effects.deleteSentinel();
250
+ await effects.deleteStoreDirectory();
251
+ } catch (error) {
252
+ if (isOpfsRootUnavailableError(error)) return "still-pending";
253
+ throw error;
254
+ }
255
+ await clearOpfsDeletionPending(storePath, deps?.meta);
256
+ return "settled";
257
+ }
258
+
224
259
  /**
225
260
  * The PRE-MINT meta gate every probe-denied (no OPFS sync access) browser boot passes through — one bounded
226
261
  * meta read serving both of the record's claims such a boot must honour, before any replacement IDB store is
@@ -246,13 +281,27 @@ export function committedStoreUnreachableFromWire(detail: unknown): CommittedSto
246
281
  *
247
282
  * An UNREADABLE record propagates ({@link StoreMetaUnreadableError}) — a failed meta read is an error, never
248
283
  * "no record" (invariant 12).
284
+ *
285
+ * A pending OPFS deletion is settled first when this home can reach OPFS asynchronously
286
+ * ({@link settlePendingOpfsDeletion}; it runs alongside the record read, which it does not touch).
287
+ *
288
+ * **An interrupted destroy whose OPFS side is already pending** (ADR-0036 amendment, 2026-09-28): a `deleting`
289
+ * record in a scope whose commitment namespace is unobservable is normally refused (sentinel removal cannot be
290
+ * confirmed). When the "OPFS deletion pending" marker for this identity still stands, the destroy got past its
291
+ * marker step, so the OPFS side is already durably deferred to the next OPFS-capable boot: this boot finishes
292
+ * the IndexedDB side (the idb database, then the meta record — destroy's own order), leaves the marker, and
293
+ * proceeds as a fresh boot. Returns `false` (no authority is published; the fresh boot is recordless). Without
294
+ * the marker (interrupted before the marker step) the refusal stands.
249
295
  */
250
296
  export async function resolveDeniedBootAuthority(
251
297
  storePath: string,
252
298
  deps?: ResolveStoreBootOptions["deps"],
253
299
  ): Promise<boolean> {
254
300
  const meta = deps?.meta;
255
- const record = await readStoreMetaRecord(storePath, meta);
301
+ const [record, pendingOpfsDeletion] = await Promise.all([
302
+ readStoreMetaRecord(storePath, meta),
303
+ settlePendingOpfsDeletion(storePath, deps),
304
+ ]);
256
305
  if (record === META_STORE_UNAVAILABLE) return false;
257
306
  // The committed refusal rides THIS read — a no-grant boot never gets a second look at the record, and the
258
307
  // hazard (an empty idb sibling minted over a committed store) is decided by exactly this phase.
@@ -265,6 +314,14 @@ export async function resolveDeniedBootAuthority(
265
314
  // cannot be observed, sentinel deletion cannot be confirmed. Keep the recorded phase authoritative and fail
266
315
  // closed rather than publish a conflicting replacement.
267
316
  if ((await effects.observeCommitmentNamespace()) === "unobservable") {
317
+ // ADR-0036 amendment (2026-09-28): a `deleting` store whose marker still stands was interrupted AFTER the
318
+ // marker step, so its OPFS side is already recorded as pending — finish the IndexedDB side of the destroy
319
+ // (keeping the marker) and boot fresh. Without the marker the recorded phase stays authoritative.
320
+ if (phase === "deleting" && pendingOpfsDeletion === "still-pending") {
321
+ await deleteIdbDatabase(storePath, meta);
322
+ await deleteStoreMetaRecord(storePath, meta);
323
+ return false;
324
+ }
268
325
  throw new Error(
269
326
  `[pgxsinkit] cannot settle ${JSON.stringify(storePath)} for an IDB boot (record phase ` +
270
327
  `${JSON.stringify(phase)}): the OPFS commitment namespace is unobservable in this scope, so sentinel ` +
@@ -288,7 +345,9 @@ export async function resolveDeniedBootAuthority(
288
345
  * no meta machinery).
289
346
  * - **non-browser** (no idb, no opfs handles) → `file://` passthrough, no classification (the filesystem
290
347
  * backend has no meta machinery either).
291
- * - **browser** → read the meta record ({@link readStoreMetaRecord}; {@link StoreMetaUnreadableError}
348
+ * - **browser** → settle any pending OPFS deletion FIRST ({@link settlePendingOpfsDeletion} — alongside the first
349
+ * meta read, which it does not touch, and before any observation, classification or open), then read the meta
350
+ * record ({@link readStoreMetaRecord}; {@link StoreMetaUnreadableError}
292
351
  * propagates = fail closed, invariant 12), map {@link META_STORE_UNAVAILABLE} to a provable absence
293
352
  * (no idb ⇒ no record and no existing idb store), observe the commitment namespace and the recordless idb fact,
294
353
  * classify, and execute:
@@ -360,11 +419,16 @@ export async function resolveStoreBoot(storePath: string, opts: ResolveStoreBoot
360
419
  return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
361
420
  };
362
421
 
422
+ // ADR-0036 amendment (2026-09-28): a store destroyed where OPFS could not be opened has its OPFS side pending.
423
+ // Settle it before anything below observes, classifies or opens; it touches OPFS and the marker only, so it
424
+ // overlaps the first meta read instead of adding a serial IndexedDB round trip to every boot.
425
+ const pendingOpfsDeletion = settlePendingOpfsDeletion(storePath, opts.deps);
426
+
363
427
  // The two record-clearing verdicts loop; every other verdict returns. Cleared record → a terminal verdict.
364
428
  for (let iteration = 0; iteration < MAX_DELETION_RECLASSIFY; iteration += 1) {
365
429
  // A failed meta read is an ERROR, never "no record" (invariant 12): StoreMetaUnreadableError propagates
366
430
  // here and fails the boot closed.
367
- const metaResult = await readStoreMetaRecord(storePath, meta);
431
+ const [metaResult] = await Promise.all([readStoreMetaRecord(storePath, meta), pendingOpfsDeletion]);
368
432
  // META_STORE_UNAVAILABLE means IndexedDB is entirely absent — a no-idb scope cannot hold a record, so
369
433
  // absence is PROVABLE (record undefined) and there can be no existing idb store either (idbStoreExists
370
434
  // false). Faithful to store-meta's documented mapping.
@@ -0,0 +1,37 @@
1
+ import { type StorageBuild, StorageBuildMismatchError, type StoreBuildCheckSite } from "@pgxsinkit/contracts";
2
+ import type { BuildIdentity } from "@pgxsinkit/pgwasm";
3
+
4
+ /**
5
+ * The supplied-build check (ADR-0063). A store's Postgres build is code — a `PostgresBuild` a site supplies,
6
+ * or the build an adopted instance reports as `pg.build` — never the declared string. The registry's
7
+ * `storage.build` (default `"c"`) must name it:
8
+ *
9
+ * - before any mint, against the build the site supplies (the `createSyncClient` boot, the worker's
10
+ * provision and spare mints, a `createPgwasmClient` with a declaration threaded to it);
11
+ * - on every adopted instance, against `pg.build` (`pgwasmInstance`, `precreatedPgwasm`, a worker
12
+ * `createStore` result).
13
+ *
14
+ * A mismatch throws {@link StorageBuildMismatchError} before any store is touched. Declaring `pgrust` and
15
+ * supplying no build is a mismatch too: the default build is `cBuild`.
16
+ */
17
+ export function assertStoreBuild(declared: StorageBuild, supplied: BuildIdentity, site: StoreBuildCheckSite): void {
18
+ if (supplied.name !== declared) throw new StorageBuildMismatchError(declared, supplied.name, site);
19
+ }
20
+
21
+ /**
22
+ * The typed build refusals (ADR-0063): the declared build is not the supplied one, or the data directory or
23
+ * backup was made by another build or data format, or its marker is unreadable. Matched by `name`, which is
24
+ * stable across bundle copies and the worker bridge. None of them is transient, so an open that failed with
25
+ * one is never retried.
26
+ */
27
+ const STORE_BUILD_REFUSALS: ReadonlySet<string> = new Set([
28
+ "StorageBuildMismatchError",
29
+ "BuildMismatchError",
30
+ "DataFormatMismatchError",
31
+ "BuildMarkerUnreadableError",
32
+ ]);
33
+
34
+ /** Is `error` a typed build refusal ({@link STORE_BUILD_REFUSALS}), which a retry cannot change? */
35
+ export function isStoreBuildRefusal(error: unknown): boolean {
36
+ return error instanceof Error && STORE_BUILD_REFUSALS.has(error.name);
37
+ }
@@ -0,0 +1,94 @@
1
+ import type { PgwasmClient } from "./index";
2
+
3
+ // ── The DECLARED store engine (ADR-0050 addendum 2026-09-08) ─────────────────────────────────────
4
+ //
5
+ // A store's storage declaration may name an ENGINE: `storage.engine = { module: <module URL> }`. When it
6
+ // does, THAT module mints the store instead of the toolkit's own `createPgwasmClient` — so an application
7
+ // can drive a different PostgreSQL-shaped engine, one that lives outside this repo, without a line of
8
+ // engine-specific code in the toolkit. Nothing here knows, names or imports any particular engine: the
9
+ // module URL is the entire surface.
10
+ //
11
+ // The contract is the toolkit's own `createStore` seam (ADR-0036), unchanged and unextended — the module's
12
+ // DEFAULT export, or failing that a named `createStore`:
13
+ //
14
+ // (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>
15
+ //
16
+ // `storePath` is a plain store NAME, never a storage URL. The handle comes back and is used exactly as a
17
+ // `createPgwasmClient` one is, so it must carry the whole `PgwasmClient` surface the engine touches — `live`
18
+ // included. Everything the seam does not pass, the module owns: its own assets (derivable from
19
+ // `import.meta.url`; there is no asset base and there will not be one), its own storage layout under the
20
+ // store path, and its own environment requirements (a threaded engine that needs a cross-origin-isolated
21
+ // page, or a scope with no main thread, refuses to construct from inside the module, loudly).
22
+ //
23
+ // Both failure modes are LOUD and specific — an unloadable URL and a module with no callable export are the
24
+ // two ways a declared module goes wrong, and either one silently falling back to the built-in store would
25
+ // report a healthy engine for one that never ran.
26
+
27
+ /** The one function the declared engine trades in — the toolkit's `createStore` option (ADR-0036). */
28
+ export type StoreEngineFactory = (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>;
29
+
30
+ /** How a scope loads a module URL: the dynamic `import()` in a browser scope, a stub in a unit test. */
31
+ export type StoreEngineModuleLoader = (url: string) => Promise<unknown>;
32
+
33
+ /**
34
+ * The default loader: a runtime-valued dynamic `import()`.
35
+ *
36
+ * `@vite-ignore` because the URL is a value, naming a module OUTSIDE any bundle — a bundler that tried to
37
+ * resolve or pre-bundle it would either fail the build or, worse, inline a stale copy.
38
+ */
39
+ const importStoreEngineModule: StoreEngineModuleLoader = (url) => import(/* @vite-ignore */ url);
40
+
41
+ /**
42
+ * Import one store-engine module URL and take its factory: the default export, else a named `createStore`.
43
+ *
44
+ * @param module the declared `storage.engine.module` — an absolute or origin-relative module URL.
45
+ * @param load how to import it; defaults to a dynamic `import()` in the calling scope.
46
+ */
47
+ export async function loadStoreEngineFactory(
48
+ module: string,
49
+ load: StoreEngineModuleLoader = importStoreEngineModule,
50
+ ): Promise<StoreEngineFactory> {
51
+ let loaded: unknown;
52
+ try {
53
+ loaded = await load(module);
54
+ } catch (cause) {
55
+ throw new Error(
56
+ `[pgxsinkit] the declared store engine "${module}" could not be imported. \`storage.engine.module\` ` +
57
+ `must be a module URL THIS scope can import — same-origin, or cross-origin with CORS and (under ` +
58
+ `cross-origin isolation) Cross-Origin-Resource-Policy: cross-origin.`,
59
+ { cause },
60
+ );
61
+ }
62
+ const exports = (loaded ?? {}) as { default?: unknown; createStore?: unknown };
63
+ const factory = typeof exports.default === "function" ? exports.default : exports.createStore;
64
+ if (typeof factory !== "function") {
65
+ throw new Error(
66
+ `[pgxsinkit] the declared store engine "${module}" exports no store factory. Expected a default ` +
67
+ `export (or a named \`createStore\`) of ` +
68
+ `\`(storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>\`.`,
69
+ );
70
+ }
71
+ return factory as StoreEngineFactory;
72
+ }
73
+
74
+ /**
75
+ * A per-scope resolver that loads each declared engine module ONCE and reuses it for every later mint.
76
+ *
77
+ * The memo keeps the REJECTION too: a failed load stays failed for the scope's lifetime, so every later
78
+ * mint reports the same loud error instead of quietly succeeding on the built-in engine (a declared engine
79
+ * that half-ran is a worse outcome than one that never started). Keyed by module URL, so a scope that is
80
+ * somehow asked for two engines gets two loads and no cross-talk.
81
+ */
82
+ export function createStoreEngineResolver(
83
+ load: StoreEngineModuleLoader = importStoreEngineModule,
84
+ ): (module: string) => Promise<StoreEngineFactory> {
85
+ const loading = new Map<string, Promise<StoreEngineFactory>>();
86
+ return (module) => {
87
+ let pending = loading.get(module);
88
+ if (pending === undefined) {
89
+ pending = loadStoreEngineFactory(module, load);
90
+ loading.set(module, pending);
91
+ }
92
+ return pending;
93
+ };
94
+ }
@@ -3,7 +3,7 @@
3
3
  // over the plan's crash tables. CONTEXT § "Language — engine placement" terms used exactly: "Commitment
4
4
  // marker", "Destructive lifecycle".
5
5
  //
6
- // EFFECT-INJECTED BY CONSTRUCTION. None of these machines touches IndexedDB, OPFS, or PGlite: every side
6
+ // EFFECT-INJECTED BY CONSTRUCTION. None of these machines touches IndexedDB, OPFS, or pgwasm: every side
7
7
  // effect is a method on an injected effects object. Plan step 10 wires the REAL effects (the meta record IO
8
8
  // from `store-meta.ts`, the OPFS namespace builders from `store-path.ts`, the live engine's `strictSync()`);
9
9
  // unit tests inject fakes and simulate a crash by making one effect throw, then re-run the resume path from
package/src/store-meta.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  // the IndexedDB IO (part B — the record's own database) and the recordless-idb detection (part C — a non-creating
16
16
  // idb existence check). It deliberately carries NO DOM lib dependency: like `store-path.ts`, it reads the
17
17
  // IndexedDB surface STRUCTURALLY off `globalThis` and accepts an injectable deps object so Bun unit tests
18
- // (no browser IDB) can fake the whole surface. The store identity encoding and PGlite's idb database naming
18
+ // (no browser IDB) can fake the whole surface. The store identity encoding and pgwasm's idb database naming
19
19
  // are consumed from `store-path.ts` — this module never re-derives either.
20
20
 
21
21
  import { storeIdentityComponent, storeIndexedDbDatabaseName } from "./store-path";
@@ -137,7 +137,7 @@ export function classifyStoreBoot(obs: StoreBootObservations): StoreBootVerdict
137
137
  // B. Meta record IO (small dedicated IndexedDB database)
138
138
  // =========================================================================================================
139
139
 
140
- /** The dedicated IndexedDB database holding every store's meta record — SEPARATE from PGlite's own idb stores. */
140
+ /** The dedicated IndexedDB database holding every store's meta record — SEPARATE from pgwasm's own idb stores. */
141
141
  export const STORE_META_DATABASE = "pgxsinkit-store-meta";
142
142
 
143
143
  /** The single object store inside {@link STORE_META_DATABASE}; keyed by {@link storeIdentityComponent}. */
@@ -407,7 +407,7 @@ export async function deleteStoreMetaRecord(storePath: string, deps?: StoreMetaD
407
407
  // =========================================================================================================
408
408
 
409
409
  /**
410
- * Does PGlite's idb database for this store ALREADY exist, WITHOUT creating it? The recordless-idb recognition
410
+ * Does pgwasm's idb database for this store ALREADY exist, WITHOUT creating it? The recordless-idb recognition
411
411
  * check (invariant 14): no meta record + an existing idb store → `idb-authoritative`, never virgin. An
412
412
  * existing idb store's data is never overwritten by a fresh opfs mint — it is opened IN PLACE, whatever the
413
413
  * booting home's capabilities, because a store's storage backend is fixed at first mint.
@@ -419,7 +419,7 @@ export async function deleteStoreMetaRecord(storePath: string, deps?: StoreMetaD
419
419
  * the handle and resolve `true`. The `onerror` that follows an abort is the EXPECTED completion of the
420
420
  * non-exist path (the AbortError), not a failure — it resolves `false`. `indexedDB` absent → `false`
421
421
  * (no idb store can exist). The database name comes from `store-path.ts`'s {@link storeIndexedDbDatabaseName}
422
- * (the sole owner of PGlite's `/pglite/` naming) — never re-derived here.
422
+ * (the sole route to pgwasm's IndexedDB naming) — never re-derived here.
423
423
  */
424
424
  export function idbStoreExists(storePath: string, deps?: StoreMetaDeps): Promise<boolean> {
425
425
  const indexedDB = resolveIndexedDb(deps);
@@ -457,3 +457,154 @@ export function idbStoreExists(storePath: string, deps?: StoreMetaDeps): Promise
457
457
  };
458
458
  });
459
459
  }
460
+
461
+ // =========================================================================================================
462
+ // D. "OPFS deletion pending" marker (ADR-0036 amendment, 2026-09-28)
463
+ // =========================================================================================================
464
+
465
+ /**
466
+ * The dedicated IndexedDB database holding "OPFS deletion pending" markers — SEPARATE from the meta record
467
+ * database, so the meta record's schema and total phase machine are untouched. A marker says: this store was
468
+ * destroyed in a context that could not open OPFS at all (`navigator.storage.getDirectory()` rejected — WebKit's
469
+ * throwaway contexts, probably Safari private windows), so its OPFS store directory and commitment sentinel,
470
+ * if any, still have to go. The next boot of that store that CAN reach OPFS deletes both, clears the marker, and
471
+ * only then classifies/opens (`store-boot.ts`'s `settlePendingOpfsDeletion`). Keyed by
472
+ * {@link storeIdentityComponent}; PRESENCE is the whole signal.
473
+ */
474
+ export const OPFS_DELETION_PENDING_DATABASE = "pgxsinkit-opfs-deletion-pending";
475
+
476
+ /** The single object store inside {@link OPFS_DELETION_PENDING_DATABASE}. */
477
+ const PENDING_OBJECT_STORE = "stores";
478
+
479
+ /** Open (or create) the pending-marker database — the WRITE path only; reads never create it. */
480
+ function openPendingDatabase(indexedDB: IndexedDbLike): Promise<IdbDatabaseLike> {
481
+ return new Promise((resolve, reject) => {
482
+ let request: IdbOpenDbRequestLike;
483
+ try {
484
+ request = indexedDB.open(OPFS_DELETION_PENDING_DATABASE, 1);
485
+ } catch (error) {
486
+ reject(error);
487
+ return;
488
+ }
489
+ request.onupgradeneeded = () => {
490
+ const db = request.result;
491
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE)) db.createObjectStore(PENDING_OBJECT_STORE);
492
+ };
493
+ request.onsuccess = () => resolve(request.result);
494
+ request.onerror = () => reject(request.error ?? new Error("indexedDB open failed"));
495
+ });
496
+ }
497
+
498
+ /**
499
+ * Open the pending-marker database only if it ALREADY exists (the {@link idbStoreExists} technique: no version,
500
+ * abort the versionchange transaction when it would be created). Resolves `undefined` when it does not exist, so
501
+ * an origin that never destroyed a store without OPFS never gains the database just by booting.
502
+ */
503
+ function openExistingPendingDatabase(indexedDB: IndexedDbLike): Promise<IdbDatabaseLike | undefined> {
504
+ return new Promise((resolve, reject) => {
505
+ let existed = true;
506
+ let request: IdbOpenDbRequestLike;
507
+ try {
508
+ request = indexedDB.open(OPFS_DELETION_PENDING_DATABASE);
509
+ } catch (error) {
510
+ reject(error);
511
+ return;
512
+ }
513
+ request.onupgradeneeded = (event) => {
514
+ existed = false;
515
+ const transaction = event?.target?.transaction ?? request.transaction;
516
+ transaction?.abort();
517
+ };
518
+ request.onsuccess = () => {
519
+ if (existed) {
520
+ resolve(request.result);
521
+ return;
522
+ }
523
+ request.result.close();
524
+ resolve(undefined);
525
+ };
526
+ request.onerror = () => {
527
+ if (!existed) {
528
+ resolve(undefined);
529
+ return;
530
+ }
531
+ reject(request.error ?? new Error("indexedDB open failed"));
532
+ };
533
+ });
534
+ }
535
+
536
+ async function readPendingAttempt(indexedDB: IndexedDbLike, key: string): Promise<boolean> {
537
+ const db = await openExistingPendingDatabase(indexedDB);
538
+ if (db == null) return false;
539
+ try {
540
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE)) return false;
541
+ const store = db.transaction(PENDING_OBJECT_STORE, "readonly").objectStore(PENDING_OBJECT_STORE);
542
+ return (await awaitRequest(store.get(key))) !== undefined;
543
+ } finally {
544
+ db.close();
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Is an OPFS deletion pending for this store? `indexedDB` entirely absent → `false` (no marker can exist). The
550
+ * SAME failed-read policy as the meta record (invariant 12): a read that fails every one of
551
+ * {@link META_READ_ATTEMPTS} attempts throws {@link StoreMetaUnreadableError}, never "no marker" — reading an
552
+ * unreadable marker as absent would let a leftover sentinel classify as a committed store and reopen destroyed
553
+ * data.
554
+ */
555
+ export async function readOpfsDeletionPending(storePath: string, deps?: StoreMetaDeps): Promise<boolean> {
556
+ const indexedDB = resolveIndexedDb(deps);
557
+ if (indexedDB == null) return false;
558
+ const key = storeIdentityComponent(storePath);
559
+ const delay = deps?.delay ?? defaultDelay;
560
+ let lastError: unknown;
561
+ for (let attempt = 1; attempt <= META_READ_ATTEMPTS; attempt += 1) {
562
+ try {
563
+ return await readPendingAttempt(indexedDB, key);
564
+ } catch (error) {
565
+ lastError = error;
566
+ if (attempt < META_READ_ATTEMPTS) await delay(META_READ_RETRY_DELAY_MS);
567
+ }
568
+ }
569
+ throw new StoreMetaUnreadableError(
570
+ storePath,
571
+ new Error("the OPFS-deletion-pending marker could not be read", { cause: lastError }),
572
+ );
573
+ }
574
+
575
+ /**
576
+ * Durably record that this store's OPFS side still has to be deleted. Resolves `false` WITHOUT writing when
577
+ * `indexedDB` is entirely absent — there is nowhere to record it, so the caller must not treat the OPFS side as
578
+ * handled.
579
+ */
580
+ export async function writeOpfsDeletionPending(storePath: string, deps?: StoreMetaDeps): Promise<boolean> {
581
+ const indexedDB = resolveIndexedDb(deps);
582
+ if (indexedDB == null) return false;
583
+ const key = storeIdentityComponent(storePath);
584
+ const db = await openPendingDatabase(indexedDB);
585
+ try {
586
+ const transaction = db.transaction(PENDING_OBJECT_STORE, "readwrite", { durability: "strict" });
587
+ const store = transaction.objectStore(PENDING_OBJECT_STORE);
588
+ await awaitAuthorityMutation(transaction, store.put({ updatedAt: Date.now() }, key));
589
+ } finally {
590
+ db.close();
591
+ }
592
+ return true;
593
+ }
594
+
595
+ /** Clear the marker once the OPFS sentinel and store directory are provably gone. Absent counts as cleared. */
596
+ export async function clearOpfsDeletionPending(storePath: string, deps?: StoreMetaDeps): Promise<void> {
597
+ const indexedDB = resolveIndexedDb(deps);
598
+ if (indexedDB == null) return;
599
+ const key = storeIdentityComponent(storePath);
600
+ const db = await openExistingPendingDatabase(indexedDB);
601
+ if (db == null) return;
602
+ try {
603
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE)) return;
604
+ const transaction = db.transaction(PENDING_OBJECT_STORE, "readwrite", { durability: "strict" });
605
+ const store = transaction.objectStore(PENDING_OBJECT_STORE);
606
+ await awaitAuthorityMutation(transaction, store.delete(key));
607
+ } finally {
608
+ db.close();
609
+ }
610
+ }
@@ -0,0 +1,109 @@
1
+ // A store's OPFS OWNERSHIP LOCK — the ordering between the context that holds an opfs-repacked store's EXCLUSIVE
2
+ // sync-access handles and anything that deletes the store directory.
3
+ //
4
+ // The gap it closes: the VFS enforces single ownership with the handles themselves (`StoreOwnedError`), which a
5
+ // deleter cannot wait on — it can only fail. And a store's previous owner is routinely still dying when its
6
+ // successor deletes: a reload or a closed tab terminates the old elected engine worker ASYNCHRONOUSLY, so a
7
+ // `removeEntry` issued at the next boot can land while that worker still holds the handles. Chromium refuses it
8
+ // with `NoModificationAllowedError`, WebKit with `UnknownError`; a short blind retry only shrinks the window.
9
+ //
10
+ // The protocol: the opening context requests this Web Lock EXCLUSIVELY before it opens the handles and releases
11
+ // it only after it has closed them (`createPgwasmClient`'s opfs branch). A deleter takes the same lock around its
12
+ // `removeEntry` (`opfs-effects.ts`), so the delete runs only once the owner has provably let go. A worker that
13
+ // dies without closing loses the lock with its context, the same moment the browser reclaims its handles.
14
+ // Bounded: a LIVE owner never releases, so a wait longer than `waitMs` fails loudly with
15
+ // {@link StoreOwnershipWaitError} rather than hanging — the destruction stays re-runnable.
16
+ //
17
+ // Structural `navigator.locks` (no DOM lib), injectable for unit tests. A scope with no Web Locks API (Bun, Node)
18
+ // has no OPFS store to order against, so the lock degrades to a no-op there.
19
+
20
+ import { storeOwnershipLockName } from "./store-path";
21
+
22
+ /** The minimal `navigator.locks` shape this module needs: an exclusive, abortable `request`. */
23
+ export interface OwnershipLocks {
24
+ request(
25
+ name: string,
26
+ options: { mode: "exclusive"; signal: AbortSignal },
27
+ callback: (lock: unknown) => Promise<void>,
28
+ ): Promise<unknown>;
29
+ }
30
+
31
+ /** Options for {@link acquireStoreOwnership} / {@link withStoreOwnership}. */
32
+ export interface StoreOwnershipOptions {
33
+ /** The Web Locks surface. Omit in production: the default reads `navigator.locks` off `globalThis`. */
34
+ locks?: OwnershipLocks | null;
35
+ /** How long to wait for the current owner to release before failing. Default {@link STORE_OWNERSHIP_WAIT_MS}. */
36
+ waitMs?: number;
37
+ }
38
+
39
+ /**
40
+ * The default bound on waiting for a store's owner to let go. It covers a dying engine worker's teardown with a
41
+ * wide margin while still failing loudly (and re-runnably) under an owner that is alive and staying.
42
+ */
43
+ export const STORE_OWNERSHIP_WAIT_MS = 10_000;
44
+
45
+ /** The store is still owned by another live context after the bounded wait — the owner never released it. */
46
+ export class StoreOwnershipWaitError extends Error {
47
+ readonly storePath: string;
48
+ constructor(storePath: string, waitMs: number) {
49
+ super(
50
+ `[pgxsinkit] the OPFS store "${storePath}" is still owned by another live engine after ${waitMs} ms. ` +
51
+ "Stop the client (or close the tab) that holds it, then retry.",
52
+ );
53
+ this.name = "StoreOwnershipWaitError";
54
+ this.storePath = storePath;
55
+ }
56
+ }
57
+
58
+ function resolveDefaultLocks(): OwnershipLocks | null {
59
+ const locks = (globalThis as { navigator?: { locks?: OwnershipLocks } }).navigator?.locks;
60
+ return locks != null && typeof locks.request === "function" ? locks : null;
61
+ }
62
+
63
+ /**
64
+ * Take the store's ownership lock, waiting at most `waitMs` for the current holder to release it. Resolves with
65
+ * an idempotent `release` once granted; rejects with {@link StoreOwnershipWaitError} when the wait runs out.
66
+ * Without a Web Locks API the returned `release` is a no-op.
67
+ */
68
+ export function acquireStoreOwnership(storePath: string, options?: StoreOwnershipOptions): Promise<() => void> {
69
+ const locks = options?.locks === undefined ? resolveDefaultLocks() : options.locks;
70
+ if (locks == null) return Promise.resolve(() => undefined);
71
+ const waitMs = options?.waitMs ?? STORE_OWNERSHIP_WAIT_MS;
72
+ return new Promise<() => void>((resolve, reject) => {
73
+ const controller = new AbortController();
74
+ const timer = setTimeout(() => controller.abort(), waitMs);
75
+ let granted = false;
76
+ locks
77
+ .request(storeOwnershipLockName(storePath), { mode: "exclusive", signal: controller.signal }, () => {
78
+ granted = true;
79
+ clearTimeout(timer);
80
+ return new Promise<void>((releaseLock) => {
81
+ let released = false;
82
+ resolve(() => {
83
+ if (released) return;
84
+ released = true;
85
+ releaseLock();
86
+ });
87
+ });
88
+ })
89
+ .catch((error: unknown) => {
90
+ clearTimeout(timer);
91
+ // An abort before the grant is the bounded wait running out; anything else is the Locks API failing.
92
+ if (!granted) reject(controller.signal.aborted ? new StoreOwnershipWaitError(storePath, waitMs) : error);
93
+ });
94
+ });
95
+ }
96
+
97
+ /** Run `effect` while holding the store's ownership lock (see {@link acquireStoreOwnership}), then release it. */
98
+ export async function withStoreOwnership<T>(
99
+ storePath: string,
100
+ effect: () => Promise<T>,
101
+ options?: StoreOwnershipOptions,
102
+ ): Promise<T> {
103
+ const release = await acquireStoreOwnership(storePath, options);
104
+ try {
105
+ return await effect();
106
+ } finally {
107
+ release();
108
+ }
109
+ }