@pgxsinkit/client 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
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
+ }
package/src/store-path.ts CHANGED
@@ -1,6 +1,9 @@
1
- // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker
1
+ import type { StorageDescription } from "@pgxsinkit/pgwasm";
2
+ import { idbDatabaseName } from "@pgxsinkit/pgwasm-c";
3
+
4
+ // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createPgwasmClient`, the worker
2
5
  // attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a
3
- // PGlite storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by
6
+ // pgwasm storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by
4
7
  // the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the
5
8
  // filesystem on Bun/Node. A memory-backed store is
6
9
  // not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic
@@ -34,20 +37,21 @@ export class InvalidStorePathError extends Error {
34
37
  }
35
38
 
36
39
  /**
37
- * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /
38
- * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its
39
- * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins
40
- * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a
41
- * consumer is never left guessing which store to hand us instead.
40
+ * Thrown when a caller-owned store handed to {@link CreateSyncClientOptions.pgwasmInstance} /
41
+ * {@link CreateSyncClientOptions.precreatedPgwasm} is PROVABLY non-persistent (ADR-0036 decision 4): its
42
+ * `storage` is memory (pgwasm's default — the bare `createPgwasm({ build })` a copy-paste reaches — or an
43
+ * explicit `memory://`), or a filesystem that explicitly reports itself non-persistent. Names both the why (durability
44
+ * semantics assume a persisted store) and the two exits, so a consumer is never left guessing which store to
45
+ * hand us instead.
42
46
  */
43
47
  export class NonPersistentStoreError extends Error {
44
- constructor(observed: "in-memory-default" | "memory-scheme") {
48
+ constructor(observed: NonPersistentStorage) {
45
49
  const reason =
46
- observed === "in-memory-default"
47
- ? "its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)"
48
- : "its dataDir is a memory-backed store";
50
+ observed === "memory"
51
+ ? "its storage is in memory (pgwasm's default without a `dataDir`, or `memory://`)"
52
+ : "its storage is a filesystem that explicitly reports itself non-persistent";
49
53
  super(
50
- `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +
54
+ `[pgxsinkit] refusing a non-persistent store: ${reason}. pgxsinkit's durability semantics ` +
51
55
  "(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store " +
52
56
  "would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a " +
53
57
  "plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with " +
@@ -107,10 +111,10 @@ export function readTestStoreMarker(options: unknown): TestStoreMarker | undefin
107
111
  }
108
112
 
109
113
  /**
110
- * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain
114
+ * What {@link createPgwasmClient} (and any store-opening seam) accepts as its store argument: a plain
111
115
  * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a
112
116
  * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing
113
- * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests("x"))` without a consumer ever
117
+ * helper's output flow STRAIGHT into `createPgwasmClient(memoryStoreForTests("x"))` without a consumer ever
114
118
  * naming a backend.
115
119
  */
116
120
  export type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);
@@ -126,7 +130,7 @@ export function normaliseStorePathInput(input: StorePathInput): { storePath: str
126
130
 
127
131
  /**
128
132
  * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in
129
- * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's
133
+ * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: pgwasm's
130
134
  * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but
131
135
  * Bun/Node do not — so it distinguishes "run in the browser" (idb) from "run on the server" (filesystem)
132
136
  * without a DOM-lib dependency.
@@ -174,7 +178,7 @@ function assertPlainStorePath(storePath: string): void {
174
178
  }
175
179
 
176
180
  /**
177
- * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
181
+ * Resolve a plain {@link storePath} to the pgwasm dataDir URL the store opens at — the ONE derivation point
178
182
  * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves
179
183
  * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;
180
184
  * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`
@@ -185,15 +189,15 @@ function assertPlainStorePath(storePath: string): void {
185
189
  * internal plumbing; do not surface it to consumers as something to imitate.
186
190
  *
187
191
  * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
188
- * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
192
+ * `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
189
193
  * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
190
194
  * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
191
195
  *
192
196
  * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
193
197
  * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
194
198
  * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →
195
- * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;
196
- * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
199
+ * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — pgwasm does NOT accept it as a `dataDir`;
200
+ * {@link createPgwasmClient} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
197
201
  * builders below. Like every URL resolved here, it never leaks to consumers.
198
202
  */
199
203
  export function resolveStoreDataDir(
@@ -269,8 +273,8 @@ export function storeIdentityComponent(storePath: string): string {
269
273
  * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,
270
274
  * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `"foo"`'s
271
275
  * commitment sentinel vs a store literally named `"foo.committed"`). This module is the ONLY place that knows
272
- * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`
273
- * prefix.
276
+ * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the client's sole route to the
277
+ * IndexedDB database names.
274
278
  */
275
279
  export const OPFS_TOOLKIT_CONTAINER = "pgxsinkit";
276
280
 
@@ -292,6 +296,16 @@ export function opfsCommitmentSentinelPath(storePath: string): readonly [string,
292
296
  return [OPFS_TOOLKIT_CONTAINER, "commitments", storeIdentityComponent(storePath)];
293
297
  }
294
298
 
299
+ /**
300
+ * The Web Lock name of a store's OPFS OWNERSHIP (`store-ownership-lock.ts`): held EXCLUSIVELY by the context
301
+ * that holds the store directory's sync-access handles, from before it opens them until after it closes them,
302
+ * and taken by anything that deletes the directory. Keyed on the same injective identity as the OPFS paths, so
303
+ * two valid identities never share a lock.
304
+ */
305
+ export function storeOwnershipLockName(storePath: string): string {
306
+ return `${OPFS_TOOLKIT_CONTAINER}:store-owner:${storeIdentityComponent(storePath)}`;
307
+ }
308
+
295
309
  /**
296
310
  * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No
297
311
  * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.
@@ -302,11 +316,11 @@ export function opfsProbeDirectoryPath(): readonly [string, string] {
302
316
 
303
317
  /**
304
318
  * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for
305
- * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite
306
- * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`
307
- * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a
308
- * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather
309
- * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as
319
+ * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. pgwasm
320
+ * maps `idb://<storePath>` to the IndexedDB database `/pgwasm/<storePath>` (the IDBFS mount point: its root
321
+ * `/pgwasm` joined with the path after the scheme), and the name comes from `@pgxsinkit/pgwasm-c`'s own
322
+ * `idbDatabaseName`, never re-encoded here. Exposed so a consumer that GCs its own stores routes that
323
+ * pgwasm-internal naming knowledge through the library rather than re-deriving the prefix itself. Rejects a scheme-bearing/empty path exactly as
310
324
  * {@link resolveStoreDataDir} does, so the two stay in lockstep.
311
325
  */
312
326
  export function storeIndexedDbDatabaseName(storePath: string): string {
@@ -320,21 +334,23 @@ export function storeIndexedDbDatabaseName(storePath: string): string {
320
334
  `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,
321
335
  );
322
336
  }
323
- return `/pglite/${storePath}`;
337
+ return idbDatabaseName(storePath);
324
338
  }
325
339
 
340
+ /** The provably-non-persistent storage shapes {@link classifyNonPersistentStorage} reports. */
341
+ export type NonPersistentStorage = "memory" | "non-persistent-vfs";
342
+
326
343
  /**
327
- * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending
328
- * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a
329
- * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,
330
- * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the
331
- * two accidental non-persistent shapes, it is not a storage-backend whitelist).
344
+ * Classify a store's own `pg.storage` for the BYO refusal (ADR-0036 decision 4). Returns the offending shape
345
+ * when the store is PROVABLY non-persistent (`memory`, pgwasm's default or an explicit `memory://`; a `vfs`
346
+ * filesystem explicitly reporting `persistent: false`), or `null` when it passes: `idb`, `file`, a persistent
347
+ * `vfs` (the OPFS-repacked store) and a `vfs` that doesn't declare its persistence (a custom filesystem is
348
+ * the caller's own call). The guard catches the accidental non-persistent shapes; it is not a
349
+ * storage-backend whitelist.
332
350
  */
333
- export function classifyNonPersistentDataDir(
334
- dataDir: string | undefined,
335
- ): "in-memory-default" | "memory-scheme" | null {
336
- if (dataDir == null) return "in-memory-default";
337
- if (dataDir.startsWith("memory://")) return "memory-scheme";
351
+ export function classifyNonPersistentStorage(storage: StorageDescription): NonPersistentStorage | null {
352
+ if (storage.kind === "memory") return "memory";
353
+ if (storage.kind === "vfs" && storage.persistent === false) return "non-persistent-vfs";
338
354
  return null;
339
355
  }
340
356
 
@@ -357,7 +373,7 @@ interface OpfsDirectoryHandle {
357
373
  * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported
358
374
  * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
359
375
  * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
360
- * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
376
+ * exactly as pgwasm's filesystem backend and {@link resolveStoreDataDir} do.
361
377
  * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at
362
378
  * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via
363
379
  * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is
@@ -372,7 +388,7 @@ interface OpfsDirectoryHandle {
372
388
  * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
373
389
  * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
374
390
  * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a
375
- * PGlite-level boot failure. We never fake a positive.
391
+ * pgwasm-level boot failure. We never fake a positive.
376
392
  */
377
393
  export async function storeTargetExists(
378
394
  storePath: string,
@@ -383,7 +399,7 @@ export async function storeTargetExists(
383
399
  if (dataDir.startsWith("memory://")) return false;
384
400
  if (dataDir.startsWith("file://")) {
385
401
  // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and
386
- // cwd-relative paths identically to PGlite's own filesystem backend.
402
+ // cwd-relative paths identically to pgwasm's own filesystem backend.
387
403
  const path = dataDir.slice("file://".length);
388
404
  const { existsSync } = await import("node:fs");
389
405
  return existsSync(path);