@pgxsinkit/client 0.5.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.
@@ -67,7 +67,7 @@ export interface MutationsApiDeps<TRegistry extends SyncTableRegistry> {
67
67
  initialRows: TRow[];
68
68
  unsubscribe: () => void;
69
69
  }>;
70
- /** One-shot query seam (in-process `pglite.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */
70
+ /** One-shot query seam (in-process `pgwasm.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */
71
71
  query: (sql: string, params?: unknown[]) => Promise<{
72
72
  rows: Record<string, unknown>[];
73
73
  }>;
@@ -98,10 +98,10 @@ export interface StoreEnv {
98
98
  * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is
99
99
  * internal plumbing; do not surface it to consumers as something to imitate.
100
100
  *
101
- * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
102
- * `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
103
- * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
104
- * 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`.
105
105
  *
106
106
  * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
107
107
  * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/store-path.ts", "../src/testing.ts"],
4
4
  "sourcesContent": [
5
- "import type { StorageDescription } from \"@pgxsinkit/pgwasm\";\nimport { idbDatabaseName } from \"@pgxsinkit/pgwasm-c\";\n\n// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createPgwasmClient`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// pgwasm storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by\n// the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the\n// filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` / `opfs://`\n// URLs (the export machinery's throwaway clone is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something a\n// consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old contract\n// loudly at the boundary rather than silently re-interpreting it.\n//\n// Under ADR-0049 (capability-driven engine placement) it also owns the browser-side STORE IDENTITY encoding\n// and the disjoint OPFS namespaces the placement probe, the commitment marker, and the store meta record all\n// key on. `storeIdentityComponent` is the one injective encoding for every browser-side identity surface\n// (OPFS namespace entries, leader lock, meta record key, communication-centre SharedWorker name; D11), and the\n// `pgxsinkit/stores|commitments|probe` namespace builders are the one place those names live (D6).\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned store handed to {@link CreateSyncClientOptions.pgwasmInstance} /\n * {@link CreateSyncClientOptions.precreatedPgwasm} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `storage` is memory (pgwasm's default — the bare `createPgwasm({ build })` a copy-paste reaches — or an\n * explicit `memory://`), or a filesystem that explicitly reports itself non-persistent. Names both the why (durability\n * semantics assume a persisted store) and the two exits, so a consumer is never left guessing which store to\n * hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: NonPersistentStorage) {\n const reason =\n observed === \"memory\"\n ? \"its storage is in memory (pgwasm's default without a `dataDir`, or `memory://`)\"\n : \"its storage is a filesystem that explicitly reports itself non-persistent\";\n super(\n `[pgxsinkit] refusing a non-persistent store: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createPgwasmClient} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createPgwasmClient(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: pgwasm's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n /**\n * ADR-0049 (D1): the PLACEMENT PROBE's injected result — whether a REAL `createSyncAccessHandle` open\n * succeeded in the executing scope (the bench phase-0 mechanism, performed by the async boot path — never\n * method-presence sniffing). Optional so every existing `StoreEnv` construction stays valid; `undefined`\n * means \"no OPFS sync access\" (false). {@link detectStoreEnv} ALWAYS reports `false` for it: there is no\n * synchronous ambient detection for handle grants, and method-presence sniffing is forbidden — only the\n * boot path's real probe open can flip it true.\n */\n hasOpfsSyncAccess?: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n // `hasOpfsSyncAccess` is deliberately absent (false): the placement probe (an async handle open) is the\n // only honest source, and this synchronous ambient detector must never guess it (ADR-0049 D1).\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * The shared plain-`storePath` boundary guard (ADR-0036 decision 1). A storePath is a PLAIN name, never a\n * storage URL: empty/whitespace-only or scheme-bearing (`://`) values fail loudly with\n * {@link InvalidStorePathError}. Factored so {@link resolveStoreDataDir} and {@link storeIdentityComponent}\n * share ONE message set (no drift between the two identity-surface entry points).\n */\nfunction assertPlainStorePath(storePath: string): void {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (capability-selected opfs-repacked ' +\n \"with IndexedDB fallback in a browser, or the filesystem on Bun/Node) is derived for you; drop the \" +\n \"scheme prefix (ADR-0036/ADR-0049).\",\n );\n }\n}\n\n/**\n * Resolve a plain {@link storePath} to the pgwasm dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves\n * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;\n * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`\n * is internal-only: `\"memory\"` selects a scheme-selected `memory://<storePath>` test/ephemeral store.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n *\n * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in\n * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:\n * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →\n * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — pgwasm does NOT accept it as a `dataDir`;\n * {@link createPgwasmClient} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace\n * builders below. Like every URL resolved here, it never leaks to consumers.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n assertPlainStorePath(storePath);\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n if (env.hasOpfsSyncAccess) return `opfs://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The per-component ENCODED length cap for {@link storeIdentityComponent}. A filesystem-safe bound for a\n * single OPFS name component; the fixed container/namespace names (`pgxsinkit`, `stores`, `commitments`,\n * `probe`) are SEPARATE path components and add nothing to this budget. Encoding is what is capped, not the\n * raw input — a short multi-byte name can expand past the bound.\n */\nconst STORE_IDENTITY_ENCODED_CAP = 128;\n\n/**\n * The ONE injective encoding for every browser-side identity surface (ADR-0049 D11, invariant 10): OPFS\n * namespace entries ({@link opfsStoreDirectoryPath} / {@link opfsCommitmentSentinelPath}), the leader lock\n * name, the store meta record key, and the communication-centre SharedWorker name all derive from this single\n * canonical component. Percent-encoding (`encodeURIComponent`) — injective, never lossy sanitising, so two\n * distinct store paths can never collapse to one identity (e.g. `\"foo/bar\"` → `foo%2Fbar` vs the literal\n * `\"foo%2Fbar\"` → `foo%252Fbar`).\n *\n * Domain (invariant 10):\n * - Same boundary guards as {@link resolveStoreDataDir}: empty/whitespace-only or scheme-bearing (`://`)\n * paths throw {@link InvalidStorePathError} (shared {@link assertPlainStorePath}).\n * - A lone UTF-16 surrogate makes `encodeURIComponent` raise a `URIError`; that is wrapped into\n * {@link InvalidStorePathError} so callers branch one error type at the boundary.\n * - `.` and `..` pass through `encodeURIComponent` UNCHANGED, but the File System Standard reserves them as\n * invalid file names, so both are rejected.\n * - The ENCODED length is capped at {@link STORE_IDENTITY_ENCODED_CAP} (a per-component filesystem-safe\n * bound); overflow is rejected.\n */\nexport function storeIdentityComponent(storePath: string): string {\n assertPlainStorePath(storePath);\n let identity: string;\n try {\n identity = encodeURIComponent(storePath);\n } catch (error) {\n // The only `encodeURIComponent` failure is a lone UTF-16 surrogate (`URIError`); rewrap it so the domain\n // presents ONE error type at the boundary (never a bare `URIError`).\n if (error instanceof URIError) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: it contains a lone UTF-16 surrogate, which has no ` +\n \"valid encoding as a store identity (ADR-0049).\",\n );\n }\n throw error;\n }\n if (identity === \".\" || identity === \"..\") {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: \".\" and \"..\" are reserved file names (File System ` +\n \"Standard) and cannot be a store identity (ADR-0049).\",\n );\n }\n if (identity.length > STORE_IDENTITY_ENCODED_CAP) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: its encoded store identity is ${identity.length} ` +\n `characters, over the ${STORE_IDENTITY_ENCODED_CAP}-character per-component cap (ADR-0049). Note the ` +\n \"cap is on the ENCODED form — a short multi-byte name can expand past it.\",\n );\n }\n return identity;\n}\n\n/**\n * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,\n * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `\"foo\"`'s\n * commitment sentinel vs a store literally named `\"foo.committed\"`). This module is the ONLY place that knows\n * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the client's sole route to the\n * IndexedDB database names.\n */\nexport const OPFS_TOOLKIT_CONTAINER = \"pgxsinkit\";\n\n/**\n * OPFS path (segment array) of a store's four-file VFS directory: `pgxsinkit/stores/<identity>` (ADR-0049 D6).\n * Returned as SEGMENTS, not a joined string, because consumers traverse OPFS via a `getDirectoryHandle` chain.\n */\nexport function opfsStoreDirectoryPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"stores\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of a store's commitment marker sentinel: `pgxsinkit/commitments/<identity>`\n * (ADR-0049 D6). Disjoint from {@link opfsStoreDirectoryPath} — the store directory holds exactly the four\n * VFS-owned files, and a suffix-sibling sentinel would collide across valid identities. Segments, not a joined\n * string, for the same `getDirectoryHandle`-chain reason.\n */\nexport function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"commitments\", storeIdentityComponent(storePath)];\n}\n\n/**\n * The Web Lock name of a store's OPFS OWNERSHIP (`store-ownership-lock.ts`): held EXCLUSIVELY by the context\n * that holds the store directory's sync-access handles, from before it opens them until after it closes them,\n * and taken by anything that deletes the directory. Keyed on the same injective identity as the OPFS paths, so\n * two valid identities never share a lock.\n */\nexport function storeOwnershipLockName(storePath: string): string {\n return `${OPFS_TOOLKIT_CONTAINER}:store-owner:${storeIdentityComponent(storePath)}`;\n}\n\n/**\n * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No\n * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.\n */\nexport function opfsProbeDirectoryPath(): readonly [string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"probe\"];\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. pgwasm\n * maps `idb://<storePath>` to the IndexedDB database `/pgwasm/<storePath>` (the IDBFS mount point: its root\n * `/pgwasm` joined with the path after the scheme), and the name comes from `@pgxsinkit/pgwasm-c`'s own\n * `idbDatabaseName`, never re-encoded here. Exposed so a consumer that GCs its own stores routes that\n * pgwasm-internal naming knowledge through the library rather than re-deriving the prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return idbDatabaseName(storePath);\n}\n\n/** The provably-non-persistent storage shapes {@link classifyNonPersistentStorage} reports. */\nexport type NonPersistentStorage = \"memory\" | \"non-persistent-vfs\";\n\n/**\n * Classify a store's own `pg.storage` for the BYO refusal (ADR-0036 decision 4). Returns the offending shape\n * when the store is PROVABLY non-persistent (`memory`, pgwasm's default or an explicit `memory://`; a `vfs`\n * filesystem explicitly reporting `persistent: false`), or `null` when it passes: `idb`, `file`, a persistent\n * `vfs` (the OPFS-repacked store) and a `vfs` that doesn't declare its persistence (a custom filesystem is\n * the caller's own call). The guard catches the accidental non-persistent shapes; it is not a\n * storage-backend whitelist.\n */\nexport function classifyNonPersistentStorage(storage: StorageDescription): NonPersistentStorage | null {\n if (storage.kind === \"memory\") return \"memory\";\n if (storage.kind === \"vfs\" && storage.persistent === false) return \"non-persistent-vfs\";\n return null;\n}\n\n/**\n * The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses — just the\n * never-creating `getDirectoryHandle` hop. Declared locally so the module carries no DOM lib dependency\n * (matching how the rest of it reads capabilities structurally off `globalThis`).\n */\ninterface OpfsDirectoryHandle {\n getDirectoryHandle(name: string, options: { create: false }): Promise<OpfsDirectoryHandle>;\n}\n\n/**\n * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target\n * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as pgwasm's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at\n * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via\n * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is\n * ONLY the fresh-target gate; it is emphatically NOT commitment authority — a store directory without a\n * commitment marker is an uncommitted CANDIDATE, and deciding that is the store meta record's phase machine\n * (plan step 2), never this function. `navigator.storage`/`getDirectory` absent → best-effort `false`\n * (mirrors the idb `databases()` stance — never fabricate a positive). A `NotFoundError` anywhere in the\n * chain → `false`; any OTHER error propagates (a genuine failure the restore caller must see).\n * A missing OPFS directory does not finish a granted browser check: IDB is also probed, because a predecessor\n * or fixed-placement store may still own the same public path.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * pgwasm-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to pgwasm's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n if (dataDir.startsWith(\"opfs://\")) {\n // Structural typing off `globalThis` — no DOM lib dependency (like the rest of the module).\n const storage = (\n globalThis as {\n navigator?: {\n storage?: { getDirectory?: () => Promise<OpfsDirectoryHandle> };\n };\n }\n ).navigator?.storage;\n // API absent → best-effort false (never a fabricated positive), same stance as idb `databases()`.\n if (storage?.getDirectory != null) {\n const segments = opfsStoreDirectoryPath(storePath);\n try {\n let handle = await storage.getDirectory();\n for (const segment of segments) {\n // Never-creating existence walk: `{ create: false }` at every hop — this is a gate, not a mkdir.\n handle = await handle.getDirectoryHandle(segment, { create: false });\n }\n return true;\n } catch (error) {\n // A missing entry anywhere in the chain proves OPFS absence; anything else is a real failure to surface.\n if ((error as { name?: string }).name !== \"NotFoundError\") throw error;\n }\n }\n // A granted browser must also reject an IDB predecessor at this path; fall through to the shared IDB probe.\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
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
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
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;",
@@ -385,7 +385,7 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
385
385
  * token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
386
386
  * (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker, and `isSynced`
387
387
  * is answered from the worker-pushed started-state snapshot (ADR-0059); the members that throw are the
388
- * structurally unproxiable ones — `pglite`, `dropReadCache`, and `drizzle.transaction()`.
388
+ * structurally unproxiable ones — `pgwasm`, `dropReadCache`, and `drizzle.transaction()`.
389
389
  */
390
390
  export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
391
391
  notifyAuthChanged: () => void;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Throw if `sql` + `params` would hit pgwasm bug #1055's broken param inlining (see the module header).
2
+ * Throw if `sql` + `params` would hit bug #1055's broken param inlining (see the module header).
3
3
  *
4
4
  * `params.length === 0` returns immediately: pgwasm skips `formatQuery` entirely in that case, so any `$N`
5
5
  * tokens are Postgres's own concern, not this guard's. Otherwise the SQL is scanned with the SAME regex
@@ -1 +1 @@
1
- {"version":3,"file":"live-query-params-guard.d.ts","sourceRoot":"","sources":["../../src/worker/live-query-params-guard.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,OAAO,EAAE,GAAG,IAAI,CAwBvF"}
1
+ {"version":3,"file":"live-query-params-guard.d.ts","sourceRoot":"","sources":["../../src/worker/live-query-params-guard.ts"],"names":[],"mappings":"AAqBA;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,OAAO,EAAE,GAAG,IAAI,CAwBvF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/client",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -37,10 +37,10 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@durable-streams/client": "0.2.7",
40
- "@pgxsinkit/contracts": "0.5.0",
41
- "@pgxsinkit/pgwasm": "0.5.0",
42
- "@pgxsinkit/pgwasm-c": "0.5.0",
43
- "@pgxsinkit/pgwasm-pg-dump": "0.5.0"
40
+ "@pgxsinkit/contracts": "0.5.1",
41
+ "@pgxsinkit/pgwasm": "0.5.1",
42
+ "@pgxsinkit/pgwasm-c": "0.5.1",
43
+ "@pgxsinkit/pgwasm-pg-dump": "0.5.1"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "drizzle-orm": "1.0.0-rc.4",
@@ -15,7 +15,7 @@ description: >-
15
15
  metadata:
16
16
  type: core
17
17
  library: "@pgxsinkit/client"
18
- library_version: "0.5.0"
18
+ library_version: "0.5.1"
19
19
  source: https://pgxsinkit.github.io/llms-full.txt
20
20
  ---
21
21
 
@@ -15,7 +15,7 @@ description: >-
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/client"
18
- library_version: "0.5.0"
18
+ library_version: "0.5.1"
19
19
  source: https://pgxsinkit.github.io/start/operating-in-production/
20
20
  ---
21
21
 
@@ -67,7 +67,7 @@ export interface BootReport {
67
67
  /** Boot start → `onInitialSync` (all eager groups caught up). */
68
68
  totalMs: number;
69
69
  /**
70
- * Boot start → `localReadReady` resolved (ADR-0041): PGlite open, durable schema compatible, store-version
70
+ * Boot start → `localReadReady` resolved (ADR-0041): pgwasm open, durable schema compatible, store-version
71
71
  * reconcile complete, and the drizzle read facade built — cached reads are safe with ZERO network. `null`
72
72
  * when the boot rejected before the stage. Additive field; `reportVersion` stays `1`.
73
73
  */
@@ -256,7 +256,7 @@ export interface BootReportBuilder extends BootStampCollector {
256
256
  fn: () => Promise<T>,
257
257
  data?: Record<string, unknown>,
258
258
  ) => Promise<T>;
259
- setPgliteCreateMs: (ms: number | null) => void;
259
+ setPgwasmCreateMs: (ms: number | null) => void;
260
260
  setProvision: (provision: BootReport["provision"]) => void;
261
261
  /**
262
262
  * Stamp `storageBackend` (ADR-0049 decision 12) at the client-owned mint seam, derived from the resolved dataDir
@@ -368,7 +368,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
368
368
  else durations.set(key, ms);
369
369
  }
370
370
  },
371
- setPgliteCreateMs: (ms) => {
371
+ setPgwasmCreateMs: (ms) => {
372
372
  pgwasmCreateMs = ms;
373
373
  },
374
374
  setProvision: (value) => {
@@ -45,7 +45,7 @@ export interface DiagnosticExportResult {
45
45
  /** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */
46
46
  export interface DiagnosticExportDeps {
47
47
  /** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
48
- pglite: Pick<PgwasmClient, "exec" | "dumpDataDir">;
48
+ pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">;
49
49
  /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
50
50
  readMutationStats: () => Promise<MutationDiagnostics>;
51
51
  /**
@@ -88,7 +88,7 @@ export interface CloneDumpPhases {
88
88
 
89
89
  /** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */
90
90
  export interface CloneDumpResult {
91
- /** The `pg_dump` output bytes (unwrapped from pglite-tools' `File` polyfill). */
91
+ /** The `pg_dump` output bytes (unwrapped from the `File` `pgDump` returns). */
92
92
  sqlBytes: Uint8Array<ArrayBuffer>;
93
93
  /** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */
94
94
  phases: CloneDumpPhases;
@@ -120,22 +120,22 @@ export interface CloneDumpOptions {
120
120
  }
121
121
 
122
122
  export async function runThrowawayCloneDump(
123
- pglite: Pick<PgwasmClient, "exec" | "dumpDataDir">,
123
+ pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">,
124
124
  startPerf: number,
125
125
  options: CloneDumpOptions = {},
126
126
  ): Promise<CloneDumpResult> {
127
127
  // Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).
128
128
  const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
129
- pglite,
129
+ pgwasm,
130
130
  "none",
131
131
  startPerf,
132
132
  );
133
133
 
134
134
  // Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036
135
- // decision 5: NEVER PGlite's explicit `fs: new MemoryFS()` — on 0.5.4 a `dumpDataDir` from an explicit-fs
136
- // instance silently omits post-initdb relation files). No extensions at all — not even `live` — and no
137
- // sync runtime: the clone exists only to be read out by `pg_dump`, and `DEALLOCATE ALL` has nothing
138
- // here to corrupt.
135
+ // decision 5: NEVER pgwasm's explicit `fs: new MemoryFS()` — as probed before the pgwasm switch (ADR-0062),
136
+ // a `dumpDataDir` from an explicit-fs instance silently omits post-initdb relation files). No extensions at
137
+ // all — not even `live` — and no sync runtime: the clone exists only to be read out by `pg_dump`, and
138
+ // `DEALLOCATE ALL` has nothing here to corrupt.
139
139
  const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
140
140
  const cloneBootStartedAtMs = nowMs() - startPerf;
141
141
  const cloneBootStartPerf = nowMs();
@@ -211,13 +211,13 @@ export async function performDiagnosticExport(
211
211
 
212
212
  // A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +
213
213
  // functions — everything a support engineer needs to read a misbehaving store.
214
- const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);
214
+ const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pgwasm, startPerf);
215
215
 
216
216
  const storeId = deriveStoreId(deps.storePath);
217
217
  const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;
218
- // Build the artefact `File` from the raw bytes, NOT by re-wrapping pglite-tools' `File`: it is a polyfill
219
- // in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name (the same bun
220
- // quirk the store backup hit) — the bytes-first path guarantees the store-scoped name/mime stick.
218
+ // Build the artefact `File` from the raw bytes, NOT by re-wrapping the `File` `pgDump` returned: a wrapped
219
+ // polyfilled `File` keeps its own name in non-browser hosts (the same bun quirk the store backup hit) — the
220
+ // bytes-first path guarantees the store-scoped name/mime stick whatever `File` the dump hands back.
221
221
  const file = new File([sqlBytes], fileName, { type: "application/sql" });
222
222
 
223
223
  // Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the
@@ -209,12 +209,12 @@ export const compactTimestamp = (): string => new Date().toISOString().replace(/
209
209
  * (the caller's export-start monotonic anchor) so the timings compose into either report.
210
210
  *
211
211
  * The `CHECKPOINT` is a utility statement — Drizzle has no builder for it, so a raw `exec` is the justified
212
- * tier-③ form here. Running it via `pglite.exec` serialises it behind any in-flight engine work on pgwasm's
212
+ * tier-③ form here. Running it via `pgwasm.exec` serialises it behind any in-flight engine work on pgwasm's
213
213
  * single connection, flushing dirty buffers to the datadir the dump then reads — so the tarball reflects
214
214
  * committed state, not a torn mid-write datadir.
215
215
  */
216
216
  export async function performDatadirDump(
217
- pglite: Pick<PgwasmClient, "exec" | "dumpDataDir">,
217
+ pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">,
218
218
  compression: "auto" | "gzip" | "none",
219
219
  startPerf: number,
220
220
  ): Promise<{
@@ -226,12 +226,12 @@ export async function performDatadirDump(
226
226
  }> {
227
227
  const checkpointStartedAtMs = nowMs() - startPerf;
228
228
  const checkpointStartPerf = nowMs();
229
- await pglite.exec("CHECKPOINT");
229
+ await pgwasm.exec("CHECKPOINT");
230
230
  const checkpointMs = nowMs() - checkpointStartPerf;
231
231
 
232
232
  const dumpStartedAtMs = nowMs() - startPerf;
233
233
  const dumpStartPerf = nowMs();
234
- const dumped = await pglite.dumpDataDir(compression);
234
+ const dumped = await pgwasm.dumpDataDir(compression);
235
235
  const dumpMs = nowMs() - dumpStartPerf;
236
236
 
237
237
  return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };
@@ -240,7 +240,7 @@ export async function performDatadirDump(
240
240
  /** The dependencies {@link performStoreExport} needs from the owning client — narrow, so it is unit-testable. */
241
241
  export interface StoreExportDeps {
242
242
  /** The live store to checkpoint and dump. */
243
- pglite: Pick<PgwasmClient, "exec" | "dumpDataDir">;
243
+ pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">;
244
244
  /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
245
245
  readMutationStats: () => Promise<MutationDiagnostics>;
246
246
  /**
@@ -268,7 +268,7 @@ export async function performStoreExport(
268
268
  // Live dump of the whole datadir (checkpoint → `dumpDataDir`, the shared core) — the journal and overlay
269
269
  // ride inside it (the lossless backup, ADR-0035).
270
270
  const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
271
- deps.pglite,
271
+ deps.pgwasm,
272
272
  compression,
273
273
  startPerf,
274
274
  );