@pgxsinkit/pgwasm-c 0.5.2 → 0.6.0-rc.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.
package/dist/index.js.map CHANGED
@@ -1,26 +1,27 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/artefacts.ts", "../src/artefact-pins.ts", "../src/host/artefact-loader.ts", "../src/host/paths.ts", "../src/host/data-dir.ts", "../src/host/extensions.ts", "../src/host/command-line.ts", "../src/host/exit-code.ts", "../src/host/initdb.ts", "../src/host/mounts/file.ts", "../src/host/mounts/idb.ts", "../src/host/mounts/memory.ts", "../src/host/vfs-mount.ts", "../src/host/mounts/vfs.ts", "../src/host/mounts/index.ts", "../src/host/postgres-instance.ts", "../src/build.ts"],
3
+ "sources": ["../src/artefacts.ts", "../src/artefact-pins.ts", "../src/host/artefact-loader.ts", "../src/host/paths.ts", "../src/host/data-dir.ts", "../src/host/extensions.ts", "../src/host/command-line.ts", "../src/host/exit-code.ts", "../src/host/initdb.ts", "../src/host/mounts/file.ts", "../src/host/mounts/idb.ts", "../src/host/mounts/memory.ts", "../src/host/vfs-mount.ts", "../src/host/mounts/vfs.ts", "../src/host/mounts/index.ts", "../src/host/postgres-instance.ts", "../src/postgres-version.ts", "../src/build.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * The C build's artefacts, referenced relative to this module so bundlers copy and fingerprint them.\n *\n * This is the ONLY module at `src/`'s depth that names `../artefacts/`: Bun.build rewrites neither a\n * relative external import nor `new URL(\"…\", import.meta.url)` when it bundles a module into a\n * shallower output, and this file is bundled into `dist/index.js`, one level below the package root\n * like itself (tests/unit/pgwasm-c-artefacts.test.ts enforces the rule). Each `new URL` stays a literal\n * so bundlers can see it.\n */\n\nimport createInitdbModule from \"../artefacts/initdb.js\";\nimport createPostgresModule from \"../artefacts/postgres.js\";\nimport { ARTEFACT_FILES } from \"./artefact-pins\";\n\n/** The URLs of the files the C build loads, for fetching and compiling them ahead of a boot. */\nexport const cBuildArtefacts = {\n /** The Postgres WebAssembly module. */\n postgresWasm: new URL(\"../artefacts/postgres.wasm\", import.meta.url),\n /** The filesystem bundle (share/, lib/, the ICU data) the Postgres module mounts. */\n fsBundle: new URL(\"../artefacts/postgres.data\", import.meta.url),\n /** The initdb WebAssembly module, used when a data directory is created. */\n initdbWasm: new URL(\"../artefacts/initdb.wasm\", import.meta.url),\n} as const;\n\n/**\n * @internal One C build's artefacts as the host runs them: the two Emscripten glue factories, the files\n * they load, and the size of the filesystem bundle the Postgres glue was packaged with. The pinned build's\n * are {@link pinnedCBuildArtefacts}; the IndexedDB browser lane assembles an earlier release's from its own\n * files, to open stores that release wrote (the build seam stays one implementation).\n */\nexport interface CBuildArtefactSet {\n readonly createPostgresModule: typeof createPostgresModule;\n readonly createInitdbModule: typeof createInitdbModule;\n readonly postgresWasm: URL;\n readonly fsBundle: URL;\n readonly initdbWasm: URL;\n readonly fsBundleBytes: number;\n}\n\n/** @internal The pinned release's artefacts (`artefact-pins.ts`). */\nexport const pinnedCBuildArtefacts: CBuildArtefactSet = {\n createPostgresModule,\n createInitdbModule,\n ...cBuildArtefacts,\n fsBundleBytes: ARTEFACT_FILES[\"postgres.data\"].bytes,\n};\n",
6
- "/**\n * The C build's artefacts, pinned by release and checksum (ADR-0062 decision 9, ADR-0064).\n *\n * Written by `bun run pgwasm:pin <tag>`; never edit it by hand. The files are the assets of one\n * pgxsinkit/pgwasm-postgres GitHub release, built from PostgreSQL plus patches derived from ElectricSQL's\n * postgres-pglite (PostgreSQL License). They are not in git: `scripts/pgwasm-artefacts.ts` (the root\n * `postinstall`) downloads each asset into `packages/pgwasm-c/artefacts/` and checks it against its bytes\n * and sha256 below. The published package carries the files themselves. `C_BUILD_IDENTITY` takes its\n * `release` and `dataFormat` from `ARTEFACT_RELEASE`.\n */\n\n/** The release the files are assets of. */\nexport const ARTEFACT_RELEASE = {\n repository: \"pgxsinkit/pgwasm-postgres\",\n tag: \"18.6.2\",\n name: \"pgwasm-postgres 18.6.2\",\n commit: \"bf7938ad6acd51e1f68a9cb14fee9fea879a3b48\",\n upstream: { tag: \"REL_18_6\", commit: \"724edf9bde9d356724ad384a2e196edc3c9f80f7\" },\n dataFormat: 1,\n builderImage:\n \"ghcr.io/pgxsinkit/pgwasm-builder@sha256:0c4d5255c5f1824216d1eb347cc231a6f881574c3d5b8172796a8cbe5f9f63c8\",\n manifestSha256: \"571b72a31003f89510f1bcbb37b5f70c142a5271cfdf24b7229423f9975d621d\",\n} as const;\n\n/** Every pinned file, by its name in `artefacts/` (the release asset of the same name). */\nexport const ARTEFACT_FILES = {\n \"amcheck.tar.gz\": { bytes: 21850, sha256: \"6151f1f4ff507dd4401dc3dff9e5ad769727c2eb3d510e9fe75329bf52667c3f\" },\n \"initdb.js\": { bytes: 106390, sha256: \"a402bd734fda0faf36696b68324471f853d52bd248ab8219893a6344386f6fac\" },\n \"initdb.wasm\": { bytes: 298938, sha256: \"0fdc9cb46e2efe6dc1fc957c47c0c7364022c98d327eb8072af3f7fb75237d3e\" },\n \"postgres.data\": { bytes: 6246509, sha256: \"012a2ed052fc0a05d50b9920afb5cb1692b3fbf9e09d486da61e4a59bb8f249a\" },\n \"postgres.js\": { bytes: 335115, sha256: \"1bfb5740bd836121c0444d058593bbc7fa0de625596214a8e4805414191a23b2\" },\n \"postgres.wasm\": { bytes: 9140085, sha256: \"f2d217be96e05dd01c02a6b62e89110d3658ac5be6032fe1d28effc9348b15ac\" },\n \"prepopulated.tar.gz\": { bytes: 4404457, sha256: \"f5228a3690329edf675f630bedad6a4f6196f40c277f34aec3ac4d1ee426e0b3\" },\n} as const;\n\nexport type ArtefactName = keyof typeof ARTEFACT_FILES;\n",
6
+ "/**\n * The C build's artefacts, pinned by release and checksum (ADR-0062 decision 9, ADR-0064).\n *\n * Written by `bun run pgwasm:pin <tag>`; never edit it by hand. The files are the assets of one\n * pgxsinkit/pgwasm-postgres GitHub release, built from PostgreSQL plus patches derived from ElectricSQL's\n * postgres-pglite (PostgreSQL License). They are not in git: `scripts/pgwasm-artefacts.ts` (the root\n * `postinstall`) downloads each asset into `packages/pgwasm-c/artefacts/` and checks it against its bytes\n * and sha256 below. The published package carries the files themselves. `C_BUILD_IDENTITY` takes its\n * `release` and `dataFormat` from `ARTEFACT_RELEASE`.\n */\n\n/** The release the files are assets of. */\nexport const ARTEFACT_RELEASE = {\n repository: \"pgxsinkit/pgwasm-postgres\",\n tag: \"19.0.0-rc.1\",\n name: \"pgwasm-postgres 19.0.0-rc.1\",\n commit: \"df4458a4fd3c0a546af29eb399bdfaa54eee70dd\",\n upstream: { tag: \"REL_19_RC1\", commit: \"0b8bff042a997fe50fcd1c4c83b9ef1cc9ed8a89\" },\n dataFormat: 2,\n builderImage:\n \"ghcr.io/pgxsinkit/pgwasm-builder@sha256:cbb378a50de43cd2fbd8718b72ce4c7595ffe421148a3c32435906f096bc5130\",\n manifestSha256: \"3451d5f8c0cc67c9dc8dd7d69862bebf81c700907f0a7d42860acc7a7548222a\",\n} as const;\n\n/** Every pinned file, by its name in `artefacts/` (the release asset of the same name). */\nexport const ARTEFACT_FILES = {\n \"amcheck.tar.gz\": { bytes: 21881, sha256: \"200978d0b73e9d5b254088625f9975a61bbbfd584558d4b53acb8bc667f26a02\" },\n \"initdb.js\": { bytes: 105130, sha256: \"cf3fff4109879f3be1ba321f19b126c4f8d518d9909846927d3104b1ec0a8129\" },\n \"initdb.wasm\": { bytes: 308968, sha256: \"71b468843c8b75dea04a5c3775606ca8d0612f0d3240953159b44132d29e0015\" },\n \"postgres.data\": { bytes: 6330058, sha256: \"be7b9fd708ddffcc627aefaff8fdc35310978d8f274a87046cfd232e306a861b\" },\n \"postgres.js\": { bytes: 336823, sha256: \"49f427bd890b89ba5b29cf96e3032dcc13cbaf5aadf62b782290480317ea0178\" },\n \"postgres.wasm\": { bytes: 9451369, sha256: \"3caccc979114e3ac7177a77bdc4511dab775738ea397bcdde04e6959ce682eb3\" },\n \"prepopulated.tar.gz\": { bytes: 4443562, sha256: \"7542c86ecdb058aa18553087b28ebf155b6270773abfb206ddcb05a446266052\" },\n} as const;\n\nexport type ArtefactName = keyof typeof ARTEFACT_FILES;\n",
7
7
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\n/**\n * Fetching and compiling the artefacts. One path for Bun and browsers: Bun's `fetch` reads `file://`\n * URLs and serves `.wasm` as `application/wasm`, so neither needs a Node `fs` branch.\n */\n\nconst downloads = new Map<string, Promise<Response>>();\nconst compiled = new Map<string, Promise<WebAssembly.Module>>();\nconst bundles = new Map<string, Promise<ArrayBuffer>>();\n\nfunction download(url: URL): Promise<Response> {\n const key = url.href;\n let pending = downloads.get(key);\n if (pending === undefined) {\n pending = fetch(url).then((response) => {\n if (!response.ok) {\n throw new Error(`Could not load ${key}: HTTP ${response.status} ${response.statusText}`);\n }\n return response;\n });\n downloads.set(key, pending);\n // A failed download is retried on the next boot rather than cached.\n pending.catch(() => downloads.delete(key));\n }\n return pending;\n}\n\n/** Start downloading an artefact now, so it is on its way when the boot needs it. */\nexport function prefetch(url: URL): void {\n download(url).catch(() => undefined);\n}\n\n/** The compiled module at `url`, compiled once per URL. */\nexport function compileModule(url: URL): Promise<WebAssembly.Module> {\n const key = url.href;\n let pending = compiled.get(key);\n if (pending === undefined) {\n pending = download(url).then(async (response) => {\n try {\n // Bun's Response and the WebAssembly typings' Response are distinct declarations of one type.\n return await WebAssembly.compileStreaming(\n response.clone() as unknown as Parameters<typeof WebAssembly.compileStreaming>[0],\n );\n } catch (error) {\n // A server that sends the wrong MIME type defeats streaming compilation; compile the bytes.\n if (error instanceof TypeError) return await WebAssembly.compile(await response.clone().arrayBuffer());\n throw error;\n }\n });\n compiled.set(key, pending);\n pending.catch(() => compiled.delete(key));\n }\n return pending;\n}\n\n/** The filesystem bundle's bytes, fetched once per URL; every caller gets its own copy. */\nexport async function loadBundle(url: URL): Promise<ArrayBuffer> {\n const key = url.href;\n let pending = bundles.get(key);\n if (pending === undefined) {\n pending = download(url).then((response) => response.clone().arrayBuffer());\n bundles.set(key, pending);\n pending.catch(() => bundles.delete(key));\n }\n // A module may keep views into the buffer it was given and write through them, so no two modules\n // share one.\n return (await pending).slice(0);\n}\n\n/** A Blob or its promise, as bytes. */\nexport async function bytesOf(source: Blob | Promise<Blob>): Promise<ArrayBuffer> {\n return await (await source).arrayBuffer();\n}\n",
8
8
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\n// The C build's filesystem layout. The root is a fact of the compiled artefacts, not a choice: the wasm\n// and its filesystem bundle hardcode `/pgwasm` as the filesystem root and install prefix (bin/, share/,\n// lib/, icu/) since pgwasm-postgres 18.6.2, so PG_ROOT must match the release it runs. An IndexedDB\n// store's database is named after its mount point `/pgwasm/<name>` (see mounts/idb.ts), so the root is\n// also part of every IndexedDB store's identity: changing it leaves the stores under the old root behind.\n\nexport const PG_ROOT = \"/pgwasm\";\nexport const PGDATA = `${PG_ROOT}/data`;\nexport const ICU_DATA_PATH = `${PG_ROOT}/icu`;\nexport const INITDB_EXE_PATH = `${PG_ROOT}/bin/initdb`;\nexport const POSTGRES_EXE_PATH = `${PG_ROOT}/bin/postgres`;\nexport const PG_STDOUT_PATH = `${PG_ROOT}/pgstdout`;\nexport const PG_STDIN_PATH = `${PG_ROOT}/pgstdin`;\n/** The file `locale -a` output is served from. */\nexport const LOCALE_LIST_PATH = `${PG_ROOT}/locale-a`;\n",
9
9
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { DataDirEntry } from \"@pgxsinkit/pgwasm/build\";\n\nimport type { EmscriptenFS } from \"./emscripten\";\nimport { PGDATA } from \"./paths\";\n\nfunction mtimeSeconds(mtime: Date | number): number {\n return Math.floor((typeof mtime === \"number\" ? mtime : mtime.getTime()) / 1000);\n}\n\n/** Every entry under the data directory, a directory before its contents. */\nexport function readDataDirEntries(FS: EmscriptenFS, root = PGDATA): DataDirEntry[] {\n const entries: DataDirEntry[] = [];\n const walk = (directory: string) => {\n for (const name of FS.readdir(directory)) {\n if (name === \".\" || name === \"..\") continue;\n const fullPath = `${directory}/${name}`;\n const stats = FS.stat(fullPath);\n const isFile = FS.isFile(stats.mode);\n entries.push({\n path: fullPath.slice(root.length),\n type: isFile ? \"file\" : \"directory\",\n mode: stats.mode & 0o7777,\n mtimeSeconds: mtimeSeconds(stats.mtime),\n data: isFile ? FS.readFile(fullPath, { encoding: \"binary\" }) : new Uint8Array(0),\n });\n if (FS.isDir(stats.mode)) walk(fullPath);\n }\n };\n walk(root);\n return entries;\n}\n\nfunction ensureDirectory(FS: EmscriptenFS, path: string): void {\n if (!FS.analyzePath(path).exists) FS.mkdirTree(path);\n}\n\n/** Write entries into the data directory, creating it and any missing parents. */\nexport function writeDataDirEntries(FS: EmscriptenFS, entries: readonly DataDirEntry[], root = PGDATA): void {\n ensureDirectory(FS, root);\n for (const entry of entries) {\n const path = `${root}${entry.path}`;\n if (entry.type === \"directory\") {\n ensureDirectory(FS, path);\n continue;\n }\n ensureDirectory(FS, path.slice(0, path.lastIndexOf(\"/\")));\n FS.writeFile(path, entry.data);\n const mtimeMs = entry.mtimeSeconds * 1000;\n FS.utime(path, mtimeMs, mtimeMs);\n }\n}\n\n/** Write one file, creating its directory. */\nexport function writeDataDirFile(FS: EmscriptenFS, path: string, data: Uint8Array, root = PGDATA): void {\n const target = `${root}${path}`;\n ensureDirectory(FS, target.slice(0, target.lastIndexOf(\"/\")));\n FS.writeFile(target, data);\n}\n\n/** A file in the data directory, or `undefined` when it does not exist. */\nexport function readDataDirFile(FS: EmscriptenFS, path: string, root = PGDATA): Uint8Array | undefined {\n const target = `${root}${path}`;\n if (!FS.analyzePath(target).exists) return undefined;\n const stats = FS.stat(target);\n if (!FS.isFile(stats.mode)) return undefined;\n return FS.readFile(target, { encoding: \"binary\" });\n}\n",
10
10
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport { gunzipIfCompressed, readTar, type ServerExtension, type TarEntry } from \"@pgxsinkit/pgwasm/build\";\n\nimport type { EmscriptenFS, PostgresModule } from \"./emscripten\";\nimport { PG_ROOT } from \"./paths\";\n\n/**\n * An extension bundle's files, fetched now so the download overlaps the boot. The bundle is a gzipped\n * tar; a server that already decompressed it (Content-Encoding) hands over the plain tar, which is\n * recognised by its missing gzip magic.\n */\nexport async function fetchExtensionBundle(extension: ServerExtension): Promise<TarEntry[]> {\n const response = await fetch(extension.bundle);\n if (!response.ok) {\n throw new Error(\n `Could not load the \"${extension.name}\" extension bundle ${extension.bundle.href}: HTTP ${response.status}`,\n );\n }\n const bytes = await gunzipIfCompressed(new Uint8Array(await response.arrayBuffer()));\n return readTar(bytes);\n}\n\nfunction writeFile(FS: EmscriptenFS, path: string, data: Uint8Array): void {\n const directory = path.slice(0, path.lastIndexOf(\"/\"));\n if (!FS.analyzePath(directory).exists) FS.mkdirTree(directory);\n FS.writeFile(path, data);\n}\n\n/**\n * Install extension files under `/pgwasm` (`lib/postgresql/*.so`, `share/postgresql/extension/*`).\n * Shared objects go through the runtime's preload plugin, which compiles them ahead of `dlopen`; a\n * preload that fails leaves the plain file, and `dlopen` compiles it when it is first needed.\n */\nexport async function installExtensionFiles(\n module: PostgresModule,\n bundles: readonly TarEntry[][],\n log: (...args: unknown[]) => void,\n): Promise<void> {\n const FS = module.FS;\n const preloads: Promise<void>[] = [];\n for (const bundle of bundles) {\n // Sorted so a library preloads before the ones that link against it (e.g. postgis-3.so before\n // postgis_topology-3.so).\n const entries = [...bundle].sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0));\n for (const entry of entries) {\n const path = `${PG_ROOT}/${entry.name}`.replace(/\\/+$/, \"\");\n if (entry.type === \"directory\") {\n if (!FS.analyzePath(path).exists) FS.mkdirTree(path);\n continue;\n }\n if (entry.name.startsWith(\".\")) continue;\n if (entry.name.endsWith(\".so\")) {\n const directory = path.slice(0, path.lastIndexOf(\"/\"));\n const soName = path.slice(path.lastIndexOf(\"/\") + 1);\n if (!FS.analyzePath(directory).exists) FS.mkdirTree(directory);\n log(`pgwasm-c: preloading ${path}`);\n preloads.push(\n new Promise<void>((resolve) => {\n FS.createPreloadedFile(\n directory,\n soName,\n entry.data,\n true,\n true,\n () => resolve(),\n () => {\n log(`pgwasm-c: preloading ${path} failed; installing the plain file`);\n writeFile(FS, path, entry.data);\n resolve();\n },\n false,\n );\n }),\n );\n } else {\n writeFile(FS, path, entry.data);\n }\n }\n }\n await Promise.all(preloads);\n}\n",
11
11
  "/**\n * The words of a command line initdb hands to `system()` / `popen()`, up to the first shell operator.\n *\n * initdb runs its backend through a shell command (`\"/pgwasm/bin/postgres\" --boot -X 1048576 …`, or\n * `… template1 >\"/dev/null\"`); the host runs that backend itself, so it needs the argument words, not a\n * shell. Quoting is honoured (`'…'`, `\"…\"` with `\\` escaping `\"`, `\\`, `$` and backtick, and a bare\n * `\\`); the first redirection or control operator (`< > | & ; ( )`) ends the words, as a shell would\n * end the command there.\n */\nexport function commandWords(command: string): string[] {\n const words: string[] = [];\n let current = \"\";\n let inWord = false;\n let index = 0;\n const end = command.length;\n const finishWord = () => {\n if (inWord) words.push(current);\n current = \"\";\n inWord = false;\n };\n\n while (index < end) {\n const char = command[index] ?? \"\";\n if (char === \"'\") {\n const close = command.indexOf(\"'\", index + 1);\n if (close === -1) throw new SyntaxError(`unterminated ' in command line: ${command}`);\n current += command.slice(index + 1, close);\n inWord = true;\n index = close + 1;\n } else if (char === '\"') {\n inWord = true;\n index++;\n while (index < end && command[index] !== '\"') {\n const inner = command[index] ?? \"\";\n const next = command[index + 1];\n if (inner === \"\\\\\" && next !== undefined && '\"\\\\$`'.includes(next)) {\n current += next;\n index += 2;\n } else {\n current += inner;\n index++;\n }\n }\n if (index >= end) throw new SyntaxError(`unterminated \" in command line: ${command}`);\n index++;\n } else if (char === \"\\\\\") {\n const next = command[index + 1];\n if (next !== undefined) current += next;\n inWord = true;\n index += 2;\n } else if (/\\s/.test(char)) {\n finishWord();\n index++;\n } else if (\"<>|&;()\".includes(char)) {\n break;\n } else {\n current += char;\n inWord = true;\n index++;\n }\n }\n finishWord();\n return words;\n}\n",
12
12
  "/**\n * Emscripten's runtime writes an exit status onto the host's `process.exitCode` when the program\n * exits, and Postgres' single-user mode reports a successful start by exiting with 99. Under Bun that\n * sentinel would survive to the end of the process and fail an otherwise green run. Every glue call that\n * can exit is wrapped so the host's own exit code is left as it was.\n */\n\ninterface ProcessWithExitCode {\n exitCode?: number | string | undefined;\n}\n\nfunction hostProcess(): ProcessWithExitCode | undefined {\n return (globalThis as { process?: ProcessWithExitCode }).process;\n}\n\n/**\n * Run `fn`, restoring `process.exitCode` (where there is a process) to its value before. Bun ignores an\n * assignment of `undefined`, so an exit code that was unset is restored as 0 — only when `fn` changed it.\n */\nexport function preservingExitCode<T>(fn: () => T): T {\n const proc = hostProcess();\n if (proc === undefined) return fn();\n const before = proc.exitCode;\n try {\n return fn();\n } finally {\n if (proc.exitCode !== before) proc.exitCode = before ?? 0;\n }\n}\n",
13
- "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { CBuildArtefactSet } from \"../artefacts\";\nimport { commandWords } from \"./command-line\";\nimport type { InitdbModule } from \"./emscripten\";\nimport { preservingExitCode } from \"./exit-code\";\nimport {\n ICU_DATA_PATH,\n INITDB_EXE_PATH,\n PG_ROOT,\n PG_STDIN_PATH,\n PG_STDOUT_PATH,\n PGDATA,\n POSTGRES_EXE_PATH,\n} from \"./paths\";\nimport type { PostgresInstance } from \"./postgres-instance\";\n\nexport interface InitdbResult {\n readonly exitCode: number;\n readonly stderr: string;\n readonly stdout: string;\n}\n\n/** The arguments every initdb run starts with. */\nexport const INITDB_ARGS: readonly string[] = [\n \"--allow-group-access\",\n \"--encoding\",\n \"UTF8\",\n \"--locale=C.UTF-8\",\n \"--locale-provider=libc\",\n \"--auth=trust\",\n];\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) throw new Error(message);\n}\n\n/**\n * Run initdb against a scratch Postgres instance. initdb is its own wasm module; the backend commands it\n * shells out to (`postgres --boot`, `postgres --single`) are run on the scratch instance, whose heap is\n * reset to its pristine state before each. initdb sees the instance's filesystem through PROXYFS, so the\n * cluster it creates lands in the instance's `/pgwasm/data`.\n */\nexport async function runInitdb({\n createInitdbModule,\n postgres,\n initdbWasm,\n debug,\n onCommand,\n}: {\n /** The initdb glue (`initdb.js`) of the build whose `initdbWasm` this is. */\n readonly createInitdbModule: CBuildArtefactSet[\"createInitdbModule\"];\n readonly postgres: PostgresInstance;\n readonly initdbWasm: WebAssembly.Module;\n readonly debug: number;\n /** @internal Every command line initdb hands to the host (the tokenizer's test pins these). */\n readonly onCommand?: (command: string) => void;\n}): Promise<InitdbResult> {\n const log = (...args: unknown[]) => {\n if (debug > 0) console.log(\"initdb:\", ...args);\n };\n const pg = postgres.module;\n let needToCallPgMain = false;\n let postgresArgs: string[] = [];\n let pgMainResult = 0;\n let initdbStdinFd = -1;\n let initdbStdoutFd = -1;\n let stderr = \"\";\n let stdout = \"\";\n\n const pristineHeap = pg.HEAPU8.slice();\n const callPgMain = (args: string[]): number => {\n const [program, ...rest] = args;\n assert(program === POSTGRES_EXE_PATH, `initdb tried to execute ${String(program)}`);\n pg.HEAPU8.set(pristineHeap);\n log(\"executing postgres with\", rest);\n const result = postgres.callMain(rest);\n postgresArgs = [];\n return result;\n };\n const commandArgs = (module: InitdbModule, pointer: number): string[] => {\n const command = module.UTF8ToString(pointer);\n onCommand?.(command);\n return commandWords(command);\n };\n\n let rejectInstantiation: (error: unknown) => void = () => undefined;\n const instantiationFailed = new Promise<never>((_, reject) => {\n rejectInstantiation = reject;\n });\n\n const initdb = await Promise.race([\n createInitdbModule({\n thisProgram: INITDB_EXE_PATH,\n arguments: [...INITDB_ARGS],\n noExitRuntime: false,\n stdin: () => null,\n print: (text) => {\n stdout += text;\n log(\"stdout\", text);\n },\n printErr: (text) => {\n stderr += text;\n log(\"stderr\", text);\n },\n instantiateWasm: (imports, successCallback) => {\n WebAssembly.instantiate(initdbWasm, imports).then(\n (instance) => successCallback(instance, initdbWasm),\n (error: unknown) => rejectInstantiation(error),\n );\n return {};\n },\n // Run in the order listed, after the filesystem bundle loads (see PostgresInstance.create): the\n // environment, then the runtime callbacks, then the PROXYFS mount of the backend's /pgwasm.\n preRun: [\n (module) => {\n const env = module.ENV;\n env[\"PGDATA\"] = PGDATA;\n env[\"HOME\"] = \"/home/postgres\";\n env[\"USER\"] = \"postgres\";\n env[\"LOGNAME\"] = \"postgres\";\n env[\"ICU_DATA\"] = ICU_DATA_PATH;\n },\n (module) => {\n module.onRuntimeInitialized = () => {\n module._pgl_set_system_fn(\n module.addFunction((command: number) => {\n postgresArgs = commandArgs(module, command);\n return callPgMain(postgresArgs);\n }, \"pi\"),\n );\n module._pgl_set_popen_fn(\n module.addFunction((command: number, mode: number) => {\n const openMode = module.UTF8ToString(mode);\n postgresArgs = commandArgs(module, command);\n if (openMode === \"r\") {\n pgMainResult = callPgMain(postgresArgs);\n return initdbStdinFd;\n }\n if (openMode === \"w\") {\n needToCallPgMain = true;\n return initdbStdoutFd;\n }\n throw new Error(`Unexpected popen mode ${openMode}`);\n }, \"ppi\"),\n );\n module._pgl_set_pclose_fn(\n module.addFunction((stream: number) => {\n if (stream === initdbStdinFd || stream === initdbStdoutFd) {\n // A popen in \"w\" mode runs postgres' main once initdb has written its input.\n if (needToCallPgMain) {\n needToCallPgMain = false;\n pgMainResult = callPgMain(postgresArgs);\n }\n return pgMainResult;\n }\n return module._pclose(stream);\n }, \"pi\"),\n );\n // The backend reads initdb's output and writes initdb's input through two files.\n pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack(\"r\"), 0);\n pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack(\"w\"), 1);\n initdbStdinFd = module._fopen(module.stringToUTF8OnStack(PG_STDOUT_PATH), module.stringToUTF8OnStack(\"r\"));\n initdbStdoutFd = module._fopen(module.stringToUTF8OnStack(PG_STDIN_PATH), module.stringToUTF8OnStack(\"w\"));\n };\n },\n (module) => {\n module.FS.mkdir(PG_ROOT);\n module.FS.mount(module.PROXYFS, { root: PG_ROOT, fs: pg.FS }, PG_ROOT);\n },\n ],\n }),\n instantiationFailed,\n ]);\n\n log(\"running initdb with\", INITDB_ARGS);\n const exitCode = preservingExitCode(() => initdb.callMain([...INITDB_ARGS]));\n return { exitCode, stderr, stdout };\n}\n",
13
+ "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { CBuildArtefactSet } from \"../artefacts\";\nimport { commandWords } from \"./command-line\";\nimport type { InitdbModule } from \"./emscripten\";\nimport { preservingExitCode } from \"./exit-code\";\nimport {\n ICU_DATA_PATH,\n INITDB_EXE_PATH,\n PG_ROOT,\n PG_STDIN_PATH,\n PG_STDOUT_PATH,\n PGDATA,\n POSTGRES_EXE_PATH,\n} from \"./paths\";\nimport type { PostgresInstance } from \"./postgres-instance\";\n\nexport interface InitdbResult {\n readonly exitCode: number;\n readonly stderr: string;\n readonly stdout: string;\n}\n\n/** The arguments every initdb run starts with. */\nexport const INITDB_ARGS: readonly string[] = [\n \"--allow-group-access\",\n \"--encoding\",\n \"UTF8\",\n \"--locale=C.UTF-8\",\n \"--locale-provider=libc\",\n \"--auth=trust\",\n];\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) throw new Error(message);\n}\n\n/**\n * Run initdb against a scratch Postgres instance. initdb is its own wasm module; the backend commands it\n * shells out to (`postgres --boot`, `postgres --single`) are run on the scratch instance, whose heap is\n * reset to its pristine state before each. initdb sees the instance's filesystem through PROXYFS, so the\n * cluster it creates lands in the instance's `/pgwasm/data`.\n */\nexport async function runInitdb({\n createInitdbModule,\n postgres,\n initdbWasm,\n debug,\n onCommand,\n}: {\n /** The initdb glue (`initdb.js`) of the build whose `initdbWasm` this is. */\n readonly createInitdbModule: CBuildArtefactSet[\"createInitdbModule\"];\n readonly postgres: PostgresInstance;\n readonly initdbWasm: WebAssembly.Module;\n readonly debug: number;\n /** @internal Every command line initdb hands to the host (the tokenizer's test pins these). */\n readonly onCommand?: (command: string) => void;\n}): Promise<InitdbResult> {\n const log = (...args: unknown[]) => {\n if (debug > 0) console.log(\"initdb:\", ...args);\n };\n const pg = postgres.module;\n let needToCallPgMain = false;\n let postgresArgs: string[] = [];\n let pgMainResult = 0;\n let initdbStdinFd = -1;\n let initdbStdoutFd = -1;\n let stderr = \"\";\n let stdout = \"\";\n\n const pristineHeap = pg.HEAPU8.slice();\n const callPgMain = (args: string[]): number => {\n const [program, ...rest] = args;\n assert(program === POSTGRES_EXE_PATH, `initdb tried to execute ${String(program)}`);\n pg.HEAPU8.set(pristineHeap);\n log(\"executing postgres with\", rest);\n const result = postgres.callMain(rest);\n postgresArgs = [];\n return result;\n };\n const commandArgs = (module: InitdbModule, pointer: number): string[] => {\n const command = module.UTF8ToString(pointer);\n onCommand?.(command);\n return commandWords(command);\n };\n\n let rejectInstantiation: (error: unknown) => void = () => undefined;\n const instantiationFailed = new Promise<never>((_, reject) => {\n rejectInstantiation = reject;\n });\n\n const initdb = await Promise.race([\n createInitdbModule({\n thisProgram: INITDB_EXE_PATH,\n arguments: [...INITDB_ARGS],\n noExitRuntime: false,\n stdin: () => null,\n print: (text) => {\n stdout += text;\n log(\"stdout\", text);\n },\n printErr: (text) => {\n stderr += text;\n log(\"stderr\", text);\n },\n instantiateWasm: (imports, successCallback) => {\n WebAssembly.instantiate(initdbWasm, imports).then(\n (instance) => successCallback(instance, initdbWasm),\n (error: unknown) => rejectInstantiation(error),\n );\n return {};\n },\n // Run in the order listed, after the filesystem bundle loads (see PostgresInstance.create): the\n // environment, then the runtime callbacks, then the PROXYFS mount of the backend's /pgwasm.\n preRun: [\n (module) => {\n const env = module.ENV;\n env[\"PGDATA\"] = PGDATA;\n env[\"HOME\"] = \"/home/postgres\";\n env[\"USER\"] = \"postgres\";\n env[\"LOGNAME\"] = \"postgres\";\n // initdb writes the cluster's timezone defaults; match the backend even on a non-UTC host.\n env[\"TZ\"] = \"UTC\";\n env[\"ICU_DATA\"] = ICU_DATA_PATH;\n },\n (module) => {\n module.onRuntimeInitialized = () => {\n module._pgwasm_set_system_fn(\n module.addFunction((command: number) => {\n postgresArgs = commandArgs(module, command);\n return callPgMain(postgresArgs);\n }, \"pi\"),\n );\n module._pgwasm_set_popen_fn(\n module.addFunction((command: number, mode: number) => {\n const openMode = module.UTF8ToString(mode);\n postgresArgs = commandArgs(module, command);\n if (openMode === \"r\") {\n pgMainResult = callPgMain(postgresArgs);\n return initdbStdinFd;\n }\n if (openMode === \"w\") {\n needToCallPgMain = true;\n return initdbStdoutFd;\n }\n throw new Error(`Unexpected popen mode ${openMode}`);\n }, \"ppi\"),\n );\n module._pgwasm_set_pclose_fn(\n module.addFunction((stream: number) => {\n if (stream === initdbStdinFd || stream === initdbStdoutFd) {\n // A popen in \"w\" mode runs postgres' main once initdb has written its input.\n if (needToCallPgMain) {\n needToCallPgMain = false;\n pgMainResult = callPgMain(postgresArgs);\n }\n return pgMainResult;\n }\n return module._pclose(stream);\n }, \"pi\"),\n );\n // The backend reads initdb's output and writes initdb's input through two files.\n pg._pgwasm_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack(\"r\"), 0);\n pg._pgwasm_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack(\"w\"), 1);\n initdbStdinFd = module._fopen(module.stringToUTF8OnStack(PG_STDOUT_PATH), module.stringToUTF8OnStack(\"r\"));\n initdbStdoutFd = module._fopen(module.stringToUTF8OnStack(PG_STDIN_PATH), module.stringToUTF8OnStack(\"w\"));\n };\n },\n (module) => {\n module.FS.mkdir(PG_ROOT);\n module.FS.mount(module.PROXYFS, { root: PG_ROOT, fs: pg.FS }, PG_ROOT);\n },\n ],\n }),\n instantiationFailed,\n ]);\n\n log(\"running initdb with\", INITDB_ARGS);\n const exitCode = preservingExitCode(() => initdb.callMain([...INITDB_ARGS]));\n return { exitCode, stderr, stdout };\n}\n",
14
14
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PGDATA } from \"../paths\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/**\n * The data directory as a directory on disk, through Emscripten's NODEFS (Bun). Writes go straight to\n * the host filesystem, so there is nothing to persist; closing flushes the runtime's streams.\n */\nexport class FileMount implements StorageMount {\n readonly #path: string;\n #root: string | undefined;\n\n constructor(path: string) {\n this.#path = path;\n }\n\n async acquire(): Promise<void> {\n // Loaded lazily so the browser bundle carries no static `node:` import; this storage is Bun's.\n const [{ mkdirSync }, { resolve }] = await Promise.all([import(\"node:fs\"), import(\"node:path\")]);\n this.#root = resolve(this.#path);\n mkdirSync(this.#root, { recursive: true });\n }\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n if (this.#root === undefined) throw new Error(\"the file mount was not acquired\");\n module.FS.mkdir(PGDATA);\n module.FS.mount(module.FS.filesystems.NODEFS, { root: this.#root }, PGDATA);\n };\n }\n\n async initialSync(): Promise<void> {}\n\n async persist(): Promise<void> {}\n\n async close(module: PostgresModule | undefined): Promise<void> {\n module?.FS.quit();\n }\n\n async cleanupFailedInit(): Promise<void> {}\n}\n",
15
15
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport { StorageInUseError, UnsupportedFeatureError } from \"@pgxsinkit/pgwasm\";\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PG_ROOT, PGDATA } from \"../paths\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/**\n * The IndexedDB database behind `idb://<name>`: `/pgwasm/<name>`. IDBFS names the database after its\n * mount point, so this is both. It is a store's identity: a change to it (as the root rename in 18.6.2)\n * opens a new, empty store and leaves the old database behind, never deleted here.\n */\nexport function idbDatabaseName(name: string): string {\n return `${PG_ROOT}/${name}`;\n}\n\n/** The Web Lock that guards `idb://<name>` against a second open: `pgwasm-idbfs:/pgwasm/<name>`. */\nexport function idbLockName(name: string): string {\n return `pgwasm-idbfs:${idbDatabaseName(name)}`;\n}\n\n/** The slice of the Web Locks API this mount uses. */\ninterface LockManagerLike {\n request(\n name: string,\n options: { mode: \"exclusive\"; ifAvailable: boolean },\n callback: (lock: unknown) => Promise<void>,\n ): Promise<void>;\n}\n\n/**\n * The data directory in IndexedDB, through Emscripten's IDBFS: the whole directory lives in memory and\n * is synced to an IndexedDB database named after its mount point, `/pgwasm/<name>`.\n *\n * One open per database: a Web Lock named after the database guards it, so a second open fails with\n * {@link StorageInUseError}. Both names come from {@link idbDatabaseName} and {@link idbLockName} only.\n *\n * Deliberately no exclusive persist: a relaxed persist is a background snapshot that statements run\n * beside (measured: an exclusive lane made relaxed as slow as strict, ~80 ms per statement). A crash\n * during a snapshot can lose its tail, which is relaxed durability's documented loss window.\n */\nexport class IdbMount implements StorageMount {\n readonly #name: string;\n #releaseHeldLock: (() => void) | undefined;\n #lockRequest: Promise<void> | undefined;\n\n constructor(name: string) {\n this.#name = name;\n }\n\n get #mountPoint(): string {\n return idbDatabaseName(this.#name);\n }\n\n async acquire(): Promise<void> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n if (!locks) {\n throw new UnsupportedFeatureError(\"IndexedDB storage needs the Web Locks API, which this context lacks.\");\n }\n let resolveAcquired!: (acquired: boolean) => void;\n let rejectAcquired!: (reason: unknown) => void;\n const acquired = new Promise<boolean>((resolve, reject) => {\n resolveAcquired = resolve;\n rejectAcquired = reject;\n });\n let releaseLock!: () => void;\n const held = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n const lockRequest = locks.request(\n idbLockName(this.#name),\n { mode: \"exclusive\", ifAvailable: true },\n async (lock) => {\n resolveAcquired(lock !== null);\n if (lock !== null) await held;\n },\n );\n this.#lockRequest = lockRequest;\n lockRequest.catch(rejectAcquired);\n if (!(await acquired)) {\n await lockRequest;\n this.#lockRequest = undefined;\n throw new StorageInUseError(`The IndexedDB store \"${this.#name}\" is already open.`);\n }\n this.#releaseHeldLock = releaseLock;\n }\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n const FS = module.FS;\n if (!FS.analyzePath(this.#mountPoint).exists) FS.mkdirTree(this.#mountPoint);\n FS.mount(FS.filesystems.IDBFS, {}, this.#mountPoint);\n FS.symlink(this.#mountPoint, PGDATA);\n };\n }\n\n async initialSync(module: PostgresModule): Promise<void> {\n await this.#syncfs(module, true);\n }\n\n async persist(module: PostgresModule): Promise<void> {\n await this.#syncfs(module, false);\n }\n\n async close(module: PostgresModule | undefined): Promise<void> {\n await this.#closeAndRelease(module);\n }\n\n async cleanupFailedInit(module: PostgresModule | undefined): Promise<void> {\n await this.#closeAndRelease(module);\n }\n\n async #closeAndRelease(module: PostgresModule | undefined): Promise<void> {\n try {\n if (module) {\n // IDBDatabase.close() returns at once; the database closes when its transactions finish. Deleting\n // it right after needs the caller to wait for that.\n module.FS.filesystems.IDBFS.dbs[this.#mountPoint]?.close();\n module.FS.quit();\n }\n } finally {\n const release = this.#releaseHeldLock;\n const request = this.#lockRequest;\n this.#releaseHeldLock = undefined;\n this.#lockRequest = undefined;\n release?.();\n await request;\n }\n }\n\n async #syncfs(module: PostgresModule, populate: boolean): Promise<void> {\n const timestampFloor = Date.now();\n await new Promise<void>((resolve, reject) => {\n module.FS.syncfs(populate, (error) => {\n if (error) {\n reject(error instanceof Error ? error : new Error(`IDBFS sync failed: ${JSON.stringify(error)}`));\n } else resolve();\n });\n });\n // IDBFS compares millisecond mtimes only: a later write must not reuse a timestamp this sync may have\n // persisted. This spins only when the whole sync fit inside one clock millisecond.\n const waitStartedAt = performance.now();\n while (Date.now() === timestampFloor) {\n if (performance.now() - waitStartedAt >= 1000) {\n throw new Error(\"IDBFS cannot guarantee a distinct MEMFS timestamp\");\n }\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n }\n}\n",
16
16
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { PostgresModule } from \"../emscripten\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/** The data directory in the module's own memory (MEMFS): gone when the database closes. */\nexport class MemoryMount implements StorageMount {\n readonly preRun = undefined;\n\n async acquire(): Promise<void> {}\n\n async initialSync(): Promise<void> {}\n\n async persist(): Promise<void> {}\n\n async close(module: PostgresModule | undefined): Promise<void> {\n module?.FS.quit();\n }\n\n async cleanupFailedInit(): Promise<void> {}\n}\n",
17
17
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport { ERRNO_CODES, type BaseFilesystem } from \"@pgxsinkit/pgwasm/fs\";\n\nimport type { EmscriptenFilesystemType, EmscriptenNode, EmscriptenStream, PostgresModule } from \"./emscripten\";\n\n/** The node attributes Emscripten passes to `setattr`. */\ninterface NodeAttributes {\n mode?: number;\n size?: number;\n timestamp?: number;\n}\n\n/** A Uint8Array over exactly the bytes of `buffer` (Emscripten hands the heap as an Int8Array). */\nfunction asBytes(buffer: ArrayBufferView): Uint8Array {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n}\n\n/**\n * An Emscripten filesystem over a pgwasm {@link BaseFilesystem}: each node and stream operation becomes a\n * call on the filesystem, by path relative to the mount. A thrown error becomes an errno for Postgres —\n * its `code` when it has one, `EIO` when it does not (a DOMException, a plain Error from the storage):\n * rethrown, it would unwind the engine mid-syscall instead of failing that syscall.\n */\nexport function createVfsFilesystem(module: PostgresModule, vfs: BaseFilesystem): EmscriptenFilesystemType {\n const FS = module.FS;\n const log = vfs.debug ? console.log : undefined;\n\n const tryOperation = <T>(fn: () => T, op: string, path: string | (() => string)): T => {\n try {\n return fn();\n } catch (error) {\n // Already an errno (a filesystem may throw Emscripten's own error).\n if (error instanceof FS.ErrnoError) throw error;\n const code = (error as { code?: unknown } | null)?.code;\n const errno = !code ? ERRNO_CODES.EIO : code === \"UNKNOWN\" ? ERRNO_CODES.EINVAL : code;\n const message = (error as { message?: unknown } | null)?.message;\n vfs.recordSyscallError(\n op,\n typeof path === \"function\" ? path() : path,\n typeof errno === \"number\" ? errno : -1,\n typeof message === \"string\" ? message : String(code ?? error),\n );\n throw new FS.ErrnoError(typeof errno === \"number\" ? errno : ERRNO_CODES.EIO);\n }\n };\n\n const realPath = (node: EmscriptenNode): string => {\n const parts: string[] = [];\n let current = node;\n while (current.parent !== current) {\n parts.push(current.name);\n current = current.parent;\n }\n parts.push(current.mount.opts.root ?? \"\");\n parts.reverse();\n return parts.join(\"/\");\n };\n\n const createNode = (parent: EmscriptenNode | null, name: string, mode: number): EmscriptenNode => {\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(ERRNO_CODES.EINVAL);\n }\n const node = FS.createNode(parent, name, mode);\n node.node_ops = nodeOps;\n node.stream_ops = streamOps;\n return node;\n };\n\n const getMode = (path: string): number => tryOperation(() => vfs.lstat(path).mode, \"getMode\", path);\n\n const nodeOps = {\n getattr(node: EmscriptenNode) {\n const path = realPath(node);\n log?.(\"getattr\", path);\n return tryOperation(\n () => {\n const stats = vfs.lstat(path);\n return {\n ...stats,\n dev: 0,\n ino: node.id,\n nlink: 1,\n rdev: node.rdev,\n atime: new Date(stats.atime),\n mtime: new Date(stats.mtime),\n ctime: new Date(stats.ctime),\n };\n },\n \"getattr\",\n path,\n );\n },\n setattr(node: EmscriptenNode, attr: NodeAttributes): void {\n const path = realPath(node);\n log?.(\"setattr\", path, attr);\n tryOperation(\n () => {\n if (attr.mode !== undefined) vfs.chmod(path, attr.mode);\n if (attr.size !== undefined) vfs.truncate(path, attr.size);\n if (attr.timestamp !== undefined) vfs.utimes(path, attr.timestamp, attr.timestamp);\n },\n \"setattr\",\n path,\n );\n },\n lookup(parent: EmscriptenNode, name: string): EmscriptenNode {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"lookup\", path);\n return createNode(parent, name, getMode(path));\n },\n mknod(parent: EmscriptenNode, name: string, mode: number): EmscriptenNode {\n const node = createNode(parent, name, mode);\n const path = realPath(node);\n log?.(\"mknod\", path, mode);\n return tryOperation(\n () => {\n if (FS.isDir(node.mode)) {\n vfs.mkdir(path, { mode });\n } else {\n vfs.writeFile(path, \"\", { mode });\n }\n return node;\n },\n \"mknod\",\n path,\n );\n },\n rename(oldNode: EmscriptenNode, newDir: EmscriptenNode, newName: string): void {\n const oldPath = realPath(oldNode);\n const newPath = `${realPath(newDir)}/${newName}`;\n log?.(\"rename\", oldPath, newPath);\n tryOperation(() => vfs.rename(oldPath, newPath), \"rename\", oldPath);\n oldNode.name = newName;\n },\n unlink(parent: EmscriptenNode, name: string): void {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"unlink\", path);\n try {\n vfs.unlink(path);\n } catch (error) {\n // An unlink failure is not reported to Postgres, only recorded.\n const code = (error as { code?: unknown } | null)?.code;\n if (code) {\n const message = (error as { message?: unknown } | null)?.message;\n vfs.recordSyscallError(\n \"unlink\",\n path,\n typeof code === \"number\" ? code : -1,\n typeof message === \"string\" ? message : JSON.stringify(code),\n );\n }\n }\n },\n rmdir(parent: EmscriptenNode, name: string): void {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"rmdir\", path);\n tryOperation(() => vfs.rmdir(path), \"rmdir\", path);\n },\n readdir(node: EmscriptenNode): string[] {\n const path = realPath(node);\n log?.(\"readdir\", path);\n return tryOperation(() => vfs.readdir(path), \"readdir\", path);\n },\n symlink(): never {\n throw new FS.ErrnoError(63); // EPERM: not supported\n },\n readlink(): never {\n throw new FS.ErrnoError(63);\n },\n };\n\n const streamOps = {\n open(stream: EmscriptenStream): void {\n const path = realPath(stream.node);\n log?.(\"open\", path);\n tryOperation(\n () => {\n if (FS.isFile(stream.node.mode)) {\n stream.shared.refcount = 1;\n stream.nfd = vfs.open(path);\n }\n },\n \"open\",\n path,\n );\n },\n close(stream: EmscriptenStream): void {\n log?.(\"close\", realPath(stream.node));\n tryOperation(\n () => {\n if (FS.isFile(stream.node.mode) && stream.nfd !== undefined && --stream.shared.refcount === 0) {\n vfs.close(stream.nfd);\n }\n },\n \"close\",\n () => realPath(stream.node),\n );\n },\n dup(stream: EmscriptenStream): void {\n stream.shared.refcount++;\n },\n read(stream: EmscriptenStream, buffer: ArrayBufferView, offset: number, length: number, position: number): number {\n if (length === 0) return 0;\n const fd = stream.nfd ?? -1;\n return tryOperation(\n () => vfs.read(fd, asBytes(buffer), offset, length, position),\n \"read\",\n () => realPath(stream.node),\n );\n },\n write(stream: EmscriptenStream, buffer: ArrayBufferView, offset: number, length: number, position: number): number {\n const fd = stream.nfd ?? -1;\n return tryOperation(\n () => vfs.write(fd, asBytes(buffer), offset, length, position),\n \"write\",\n () => realPath(stream.node),\n );\n },\n llseek(stream: EmscriptenStream, offset: number, whence: number): number {\n let position = offset;\n if (whence === 1) {\n position += stream.position;\n } else if (whence === 2 && FS.isFile(stream.node.mode)) {\n const fd = stream.nfd ?? -1;\n tryOperation(\n () => {\n position += vfs.fstat(fd).size;\n },\n \"llseek\",\n () => realPath(stream.node),\n );\n }\n if (position < 0) throw new FS.ErrnoError(ERRNO_CODES.EINVAL);\n return position;\n },\n mmap(): never {\n // The runtime exports no mmapAlloc; Postgres does not map data-directory files.\n throw new FS.ErrnoError(ERRNO_CODES.ENODEV);\n },\n msync(): number {\n return 0;\n },\n };\n\n return {\n mount(): EmscriptenNode {\n return createNode(null, \"/\", 0o40000 | 0o777);\n },\n syncfs(_mount: unknown, _populate: unknown, done: (error: unknown) => void): void {\n done(null);\n },\n createNode,\n node_ops: nodeOps,\n stream_ops: streamOps,\n };\n}\n",
18
18
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { BaseFilesystem } from \"@pgxsinkit/pgwasm/fs\";\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PGDATA } from \"../paths\";\nimport { createVfsFilesystem } from \"../vfs-mount\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/** The data directory on a pgwasm filesystem (`createPgwasm({ fs })`), mounted through an adapter. */\nexport class VfsMount implements StorageMount {\n readonly #vfs: BaseFilesystem;\n\n constructor(vfs: BaseFilesystem) {\n this.#vfs = vfs;\n }\n\n async acquire(): Promise<void> {}\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n module.FS.mkdir(PGDATA);\n module.FS.mount(createVfsFilesystem(module, this.#vfs), {}, PGDATA);\n };\n }\n\n async initialSync(): Promise<void> {\n await this.#vfs.initialSyncFs();\n }\n\n async persist(_module: PostgresModule, relaxed: boolean): Promise<void> {\n await this.#vfs.syncToFs(relaxed);\n }\n\n async close(): Promise<void> {\n await this.#vfs.closeFs();\n }\n\n async cleanupFailedInit(): Promise<void> {\n await this.#vfs.cleanupFailedInit();\n }\n}\n",
19
19
  "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { StorageRequest } from \"@pgxsinkit/pgwasm/build\";\n\nimport { FileMount } from \"./file\";\nimport { IdbMount } from \"./idb\";\nimport { MemoryMount } from \"./memory\";\nimport type { StorageMount } from \"./storage-mount\";\nimport { VfsMount } from \"./vfs\";\n\nexport type { StorageMount } from \"./storage-mount\";\n\n/** The mount for a storage request. */\nexport function mountFor(storage: StorageRequest): StorageMount {\n switch (storage.kind) {\n case \"memory\":\n return new MemoryMount();\n case \"idb\":\n return new IdbMount(storage.name);\n case \"file\":\n return new FileMount(storage.path);\n case \"vfs\":\n return new VfsMount(storage.vfs);\n }\n}\n",
20
- "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { DebugLevel } from \"@pgxsinkit/pgwasm/build\";\n\nimport type { CBuildArtefactSet } from \"../artefacts\";\nimport type { EmscriptenStream, ModuleOverrides, PostgresModule } from \"./emscripten\";\nimport { preservingExitCode } from \"./exit-code\";\nimport { ICU_DATA_PATH, INITDB_EXE_PATH, LOCALE_LIST_PATH, PGDATA, POSTGRES_EXE_PATH } from \"./paths\";\n\n/** Postgres' error longjmp, intercepted by the host: keep in sync with pglitec.c's POSTGRES_MAIN_LONGJMP. */\nconst POSTGRES_MAIN_LONGJMP = 100;\n/** The exit status single-user mode reports when it started and stays alive: the C build's `PGLITE_EXIT_ALIVE`. */\nconst PGWASM_EXIT_ALIVE = 99;\nconst INITIAL_MEMORY_PAGES = 2048;\nconst MAXIMUM_MEMORY_PAGES = 32768;\n\n/** The single-user-mode arguments every start begins with. */\nexport const DEFAULT_START_PARAMS: readonly string[] = [\n \"--single\", // single-user mode (must come first)\n \"-F\", // fsync off: the host persists storage itself\n \"-O\", // allow system table structure changes\n \"-j\", // no newline as the interactive query delimiter\n \"-c\",\n \"search_path=public\",\n \"-c\",\n \"exit_on_error=false\",\n \"-c\",\n \"log_checkpoints=false\",\n \"-c\",\n \"max_worker_processes=0\",\n \"-c\",\n \"max_parallel_workers=0\",\n \"-c\",\n \"max_parallel_workers_per_gather=0\",\n \"-c\",\n \"io_method=sync\",\n \"-c\",\n \"max_parallel_maintenance_workers=0\",\n];\n\n/**\n * Whether `error` is one of the exceptions the Emscripten runtime throws on purpose to unwind the wasm\n * stack back to the main loop, which handles them:\n * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgl_longjmp (pglitec.c) delivers Postgres'\n * siglongjmp to its main-loop error handler, and how a Terminate message ends the loop;\n * - what an emscripten-mode longjmp throws, should one pass every invoke_* frame: an instance of the\n * glue's (unexported) `EmscriptenSjLj` class on Emscripten 6.0.10 (pgwasm-postgres 18.6.1 onwards), a\n * number on Emscripten 3.1.74 (18.3.0 and 18.6.0). Both are recognised, so the host works with either.\n *\n * An `ExitStatus` (from exit()/proc_exit(): a FATAL error) is not: the backend's exit callbacks have\n * already torn its session down, so the loop cannot resume on it (see {@link exitStatusOf}).\n */\nexport function isEmscriptenUnwind(error: unknown): boolean {\n if (error === \"unwind\" || typeof error === \"number\") return true;\n if (typeof error !== \"object\" || error === null) return false;\n return (error as { constructor?: { name?: unknown } }).constructor?.name === \"EmscriptenSjLj\";\n}\n\nconst invalidBundleSize = (actual: number, expected: number): Error =>\n new Error(`Invalid filesystem bundle size: ${actual} !== ${expected}`);\n\n/** The status of the `ExitStatus` the runtime throws from exit()/proc_exit(), or undefined for anything else. */\nexport function exitStatusOf(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || (error as { name?: unknown }).name !== \"ExitStatus\") {\n return undefined;\n }\n const status = (error as { status?: unknown }).status;\n return typeof status === \"number\" ? status : -1;\n}\n\n/**\n * The wasm's shadow stack pointer: the C stack in linear memory, which the glue exports neither\n * `stackSave` nor `stackRestore` for. A throw that unwinds wasm frames (an ERROR's intercepted\n * siglongjmp, a FATAL's exit) skips their epilogues, so the pointer stays where the deepest of them left\n * it. Unrestored, every ERROR leaked that much stack (about 1.2 kB for `SELECT 1/0`), until\n * `max_stack_depth` refused every statement (from about the 1,700th error in one instance). The host\n * restores it to where the call started, as Postgres' own siglongjmp to PostgresMain would.\n */\ninterface ShadowStack {\n save(): number;\n restore(pointer: number): void;\n}\n\nfunction shadowStackOf(instance: WebAssembly.Instance): ShadowStack {\n const current = instance.exports[\"emscripten_stack_get_current\"];\n const restore = instance.exports[\"_emscripten_stack_restore\"];\n if (typeof current !== \"function\" || typeof restore !== \"function\") {\n throw new Error(\n \"The Postgres module exports no emscripten_stack_get_current or _emscripten_stack_restore: the host cannot restore its stack after an error\",\n );\n }\n return {\n save: () => (current as () => number)(),\n restore: (pointer) => (restore as (pointer: number) => void)(pointer),\n };\n}\n\nexport interface PostgresInstanceConfig {\n /** The Postgres glue (`postgres.js`) and the size of the filesystem bundle it was packaged with. */\n readonly glue: Pick<CBuildArtefactSet, \"createPostgresModule\" | \"fsBundleBytes\">;\n readonly wasmModule: Promise<WebAssembly.Module>;\n /** The filesystem bundle, a copy of its own for this instance. */\n readonly fsBundle: Promise<ArrayBuffer>;\n readonly user: string;\n readonly database: string;\n readonly debug: DebugLevel;\n /** preRun steps that mount storage over the data directory; run after the filesystem bundle loads. */\n readonly mountPreRun?: (module: PostgresModule) => void;\n /** @internal A test's view of the module. */\n readonly onModule?: (module: PostgresModule) => void;\n}\n\n/**\n * One Emscripten instance of the Postgres module and the host state around it: the socket callbacks\n * the wire goes through, the `/dev/blob` device, and the external-command hooks.\n */\nexport class PostgresInstance {\n readonly module: PostgresModule;\n readonly #debug: DebugLevel;\n readonly #stack: ShadowStack;\n // Frontend bytes being fed to Postgres, and how far it has read them.\n #input: Uint8Array = new Uint8Array(0);\n #readOffset = 0;\n // Where backend bytes go during an exchange.\n #sink: ((chunk: Uint8Array) => void) | undefined;\n #blobReadSource: Uint8Array | undefined;\n #blobWritten: Uint8Array<ArrayBuffer>[] | undefined;\n #externalCommandStream: number | null = null;\n #functionPointers: number[] = [];\n #failed = false;\n #exited = false;\n // The last lines Postgres wrote to stderr (since the exchange began, during one), for the error when it\n // fails to start or exits.\n readonly #stderr: string[] = [];\n\n private constructor(module: PostgresModule, debug: DebugLevel, stack: ShadowStack) {\n this.module = module;\n this.#debug = debug;\n this.#stack = stack;\n }\n\n static async create(config: PostgresInstanceConfig): Promise<PostgresInstance> {\n const [wasmModule, fsBundle] = await Promise.all([config.wasmModule, config.fsBundle]);\n // Checked before the glue runs. Emscripten 6's file packager (pgwasm-postgres 18.6.1 onwards) loads the\n // bundle in an async function it never awaits, so a throw from getPreloadedPackage no longer rejects the\n // factory: it is an unhandled rejection, and the boot fails later on a missing bundle file with an\n // unrelated filesystem error.\n const { createPostgresModule, fsBundleBytes } = config.glue;\n if (fsBundle.byteLength !== fsBundleBytes) throw invalidBundleSize(fsBundle.byteLength, fsBundleBytes);\n let host: PostgresInstance | undefined;\n let stack: ShadowStack | undefined;\n const pendingHost = (module: PostgresModule): PostgresInstance => {\n // The runtime runs no preRun step before the instance it waits on (instantiateWasm) is ready.\n if (stack === undefined) throw new Error(\"The Postgres module initialised before its wasm instance\");\n host ??= new PostgresInstance(module, config.debug, stack);\n return host;\n };\n let rejectInstantiation: (error: unknown) => void = () => undefined;\n const instantiationFailed = new Promise<never>((_, reject) => {\n rejectInstantiation = reject;\n });\n\n const log = (text: string) => {\n if (config.debug > 0) console.debug(text);\n };\n const logError = (text: string) => {\n if (host) host.#recordStderr(text);\n if (config.debug > 0) console.error(text);\n };\n\n // Emscripten runs preRun callbacks in the order listed (3.1.74, before pgwasm-postgres 18.6.1, ran them\n // in reverse). The build's pre-js loads the filesystem bundle before the first of them, so every one\n // sees the bundle's files. They touch disjoint state (the runtime hook, /dev/blob, the environment, the\n // bundle's files outside the data directory, then the storage mount over the data directory), so none\n // depends on the order of the others.\n const preRun: ((module: PostgresModule) => void)[] = [\n (module) => {\n module.onRuntimeInitialized = () => pendingHost(module).#onRuntimeInitialized();\n },\n (module) => pendingHost(module).#registerBlobDevice(),\n (module) => {\n const env = module.ENV;\n env[\"HOME\"] = \"/home/postgres\";\n env[\"USER\"] = \"postgres\";\n env[\"LOGNAME\"] = \"postgres\";\n env[\"PGDATA\"] = PGDATA;\n env[\"PGUSER\"] = config.user;\n env[\"PGDATABASE\"] = config.database;\n env[\"LANG\"] = \"en_US.UTF-8\";\n env[\"LC_COLLATE\"] = \"en_US.UTF-8\";\n env[\"LC_CTYPE\"] = \"en_US.UTF-8\";\n env[\"TZ\"] = \"UTC\";\n env[\"PGTZ\"] = \"UTC\";\n env[\"PGCLIENTENCODING\"] = \"UTF8\";\n env[\"ICU_DATA\"] = ICU_DATA_PATH;\n },\n (module) => {\n module.FS.chmod(\"/home/postgres/.pgpass\", 0o600); // libpq ignores a .pgpass others can read\n module.FS.chmod(INITDB_EXE_PATH, 0o555);\n module.FS.chmod(POSTGRES_EXE_PATH, 0o555);\n },\n ];\n if (config.mountPreRun) preRun.push(config.mountPreRun);\n\n const overrides: ModuleOverrides<PostgresModule> = {\n thisProgram: POSTGRES_EXE_PATH,\n arguments: config.debug > 0 ? [\"-d\", String(config.debug)] : [],\n noExitRuntime: true,\n wasmMemory: new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: MAXIMUM_MEMORY_PAGES }),\n // A stdin that is always at EOF, so a browser never prompts.\n stdin: () => null,\n print: log,\n printErr: logError,\n instantiateWasm: (imports, successCallback) => {\n WebAssembly.instantiate(wasmModule, imports).then(\n (instance) => {\n try {\n stack = shadowStackOf(instance);\n } catch (error) {\n rejectInstantiation(error);\n return;\n }\n successCallback(instance, wasmModule);\n },\n (error: unknown) => rejectInstantiation(error),\n );\n return {};\n },\n getPreloadedPackage: (name, size) => {\n if (name !== \"postgres.data\") throw new Error(`Unknown filesystem package: ${name}`);\n if (fsBundle.byteLength !== size) {\n // Unreachable while the glue and the pins agree; if they ever do not, fail the boot with this error.\n const error = invalidBundleSize(fsBundle.byteLength, size);\n rejectInstantiation(error);\n throw error;\n }\n return fsBundle;\n },\n preRun,\n };\n\n const module = await Promise.race([createPostgresModule(overrides), instantiationFailed]);\n const instance = pendingHost(module);\n config.onModule?.(module);\n return instance;\n }\n\n #recordStderr(text: string): void {\n this.#stderr.push(text);\n if (this.#stderr.length > 20) this.#stderr.shift();\n }\n\n #log(...args: unknown[]): void {\n if (this.#debug > 0) console.log(...args);\n }\n\n #addFunction(fn: (...args: number[]) => number | void, signature: string): number {\n const pointer = this.module.addFunction(fn, signature);\n this.#functionPointers.push(pointer);\n return pointer;\n }\n\n #onRuntimeInitialized(): void {\n const mod = this.module;\n // system() never runs a command: it is logged and fails.\n mod._pgl_set_system_fn(\n this.#addFunction((command: number) => {\n this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);\n return 1;\n }, \"pi\"),\n );\n mod._pgl_set_popen_fn(\n this.#addFunction((command: number, mode: number) => {\n this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));\n return this.#externalCommandStream;\n }, \"ppp\"),\n );\n mod._pgl_set_pclose_fn(\n this.#addFunction((stream: number) => {\n if (stream !== this.#externalCommandStream) throw new Error(`Unhandled pclose ${stream}`);\n mod._fclose(stream);\n this.#externalCommandStream = null;\n }, \"pi\"),\n );\n // Backend bytes: handed to the exchange's sink as a view of the heap, valid during the call.\n const write = this.#addFunction((pointer: number, length: number) => {\n this.#sink?.(this.module.HEAPU8.subarray(pointer, pointer + length));\n return length;\n }, \"iii\");\n // Frontend bytes: copied into the heap from the message being exchanged.\n const read = this.#addFunction((pointer: number, maxLength: number) => {\n const length = Math.min(this.#input.length - this.#readOffset, maxLength);\n this.module.HEAPU8.set(this.#input.subarray(this.#readOffset, this.#readOffset + length), pointer);\n this.#readOffset += length;\n return length;\n }, \"iii\");\n mod._pgl_set_rw_cbs(read, write);\n }\n\n #handleExternalCommand(command: string, mode: string): number {\n if (command.startsWith(\"locale -a\") && mode === \"r\") {\n return this.module._fopen(\n this.module.stringToUTF8OnStack(LOCALE_LIST_PATH),\n this.module.stringToUTF8OnStack(mode),\n );\n }\n throw new Error(`Unhandled external command: ${command}`);\n }\n\n /** `/dev/blob`: what `COPY … FROM '/dev/blob'` reads and `COPY … TO '/dev/blob'` writes. */\n #registerBlobDevice(): void {\n const FS = this.module.FS;\n const device = FS.makedev(64, 0);\n FS.registerDevice(device, {\n open: () => undefined,\n close: () => undefined,\n read: (_stream, buffer, offset, length, position) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to read from\");\n if (position >= contents.length) return 0;\n const size = Math.min(contents.length - position, length);\n buffer.set(contents.subarray(position, position + size), offset);\n return size;\n },\n write: (_stream, buffer, offset, length) => {\n this.#blobWritten ??= [];\n this.#blobWritten.push(new Uint8Array(buffer.subarray(offset, offset + length)));\n return length;\n },\n llseek: (stream: EmscriptenStream, offset: number, whence: number) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to llseek\");\n let position = offset;\n if (whence === 1) position += stream.position;\n else if (whence === 2) position = contents.length;\n if (position < 0) throw new FS.ErrnoError(28);\n return position;\n },\n });\n FS.mkdev(\"/dev/blob\", device);\n }\n\n setBlobReadSource(data: Uint8Array | undefined): void {\n this.#blobReadSource = data;\n }\n\n takeBlobWritten(): Uint8Array<ArrayBuffer>[] | undefined {\n const written = this.#blobWritten;\n this.#blobWritten = undefined;\n return written;\n }\n\n /** Run `callMain`, leaving the host's exit code as it was. */\n callMain(args: string[]): number {\n return preservingExitCode(() => this.module.callMain(args));\n }\n\n /** Start Postgres in single-user mode on the data directory. */\n startSingleMode(startParams: readonly string[]): void {\n const mod = this.module;\n mod._pgl_setPGliteActive(1);\n this.callMain([...startParams, \"-D\", PGDATA, mod.ENV[\"PGDATABASE\"] ?? \"postgres\"]);\n const exitStatus = mod._pgl_setPGliteExitStatus(-3);\n if (exitStatus !== PGWASM_EXIT_ALIVE) {\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:\\n${output}` : \"\"}`,\n );\n }\n mod._pgl_startPGlite();\n }\n\n /**\n * One exchange on the single session: feed `message` to Postgres and hand every backend byte it\n * produces to `onData`, synchronously. A startup packet (first byte 0) is processed as one; a\n * Terminate (`X`) is ignored, as the session ends with the instance. A throw that is not Postgres'\n * own error unwind means the wasm stack was abandoned mid-function, and an exit (a FATAL error) means\n * the backend tore its session down: either fails the session, which refuses every later exchange.\n */\n exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void {\n if (this.#failed) throw new Error(\"The C build's session failed and cannot be used again\");\n if (message[0] === 0x58) return; // Terminate\n this.#sink = onData;\n this.#input = message;\n this.#readOffset = 0;\n this.#stderr.length = 0;\n try {\n if (message[0] === 0) {\n this.#processStartupPacket();\n return;\n }\n this.#runMainLoop(message);\n } catch (error) {\n const status = exitStatusOf(error);\n if (status === undefined) throw error;\n this.#failed = true;\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres exited with status ${status} during an exchange: a FATAL error ended the C build's session${output ? `:\\n${output}` : \"\"}`,\n { cause: error },\n );\n } finally {\n this.#sink = undefined;\n this.#input = new Uint8Array(0);\n }\n }\n\n /**\n * A call into the backend that may unwind (an ERROR's intercepted siglongjmp, a FATAL's exit):\n * should it throw, the shadow stack pointer is restored to where it began (see {@link ShadowStack}).\n */\n #call<T>(call: () => T): T {\n const stack = this.#stack.save();\n try {\n return call();\n } catch (error) {\n this.#stack.restore(stack);\n throw error;\n }\n }\n\n #processStartupPacket(): void {\n const mod = this.module;\n const result = this.#call(() => mod._ProcessStartupPacket(mod._pgl_getMyProcPort(), true, true));\n if (result !== 0) throw new Error(\"Cannot process the startup packet\");\n this.#call(() => {\n mod._pgl_sendConnData();\n mod._pgl_pq_flush();\n });\n }\n\n #runMainLoop(message: Uint8Array): void {\n const mod = this.module;\n try {\n // One message may carry several batched statements; the loop returns after each.\n while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {\n const stack = this.#stack.save();\n try {\n mod._PostgresMainLoopOnce();\n } catch (error) {\n // First, as Postgres' own siglongjmp to PostgresMain would: the throw skipped the epilogues of\n // every frame it abandoned (see ShadowStack).\n this.#stack.restore(stack);\n if (!isEmscriptenUnwind(error)) throw error;\n if (mod._pgl_setPGliteExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {\n // Postgres raised an error: its siglongjmp into main was intercepted, and its error handling\n // runs here before the loop resumes with the rest of the batch.\n this.#call(() => mod._PostgresMainLongJmp());\n }\n }\n }\n this.#call(() => {\n mod._PostgresSendReadyForQueryIfNecessary();\n mod._pgl_pq_flush();\n });\n } catch (error) {\n this.#failed = true;\n throw error;\n }\n }\n\n /** Postgres' clean exit: its atexit callbacks. An exit status of 0 is the normal outcome. */\n shutdown(): void {\n const mod = this.module;\n try {\n preservingExitCode(() => {\n mod._pgl_setPGliteActive(0);\n this.#call(() => mod._pgl_run_atexit_funcs());\n });\n } catch (error) {\n const exit = error as { name?: unknown; status?: unknown };\n if (!(exit.name === \"ExitStatus\" && exit.status === 0)) throw error;\n }\n }\n\n /** Release the callbacks and exit the runtime, which `noExitRuntime` otherwise keeps alive. */\n dispose(exitStatus: number): void {\n if (this.#exited) return;\n this.#exited = true;\n for (const pointer of this.#functionPointers) {\n try {\n this.module.removeFunction(pointer);\n } catch {\n // continue releasing\n }\n }\n this.#functionPointers = [];\n try {\n preservingExitCode(() => this.module._emscripten_force_exit(exitStatus));\n } catch {\n // The runtime reports a forced exit by throwing ExitStatus.\n }\n }\n}\n",
21
- "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type {\n BlobDevice,\n BootRequest,\n BuildCapabilities,\n BuildIdentity,\n DataDirEntry,\n MountedDataDirectory,\n PostgresBuild,\n RunningPostgres,\n StartOptions,\n TarEntry,\n WireSession,\n} from \"@pgxsinkit/pgwasm/build\";\n\nimport { ARTEFACT_RELEASE } from \"./artefact-pins\";\nimport { type CBuildArtefactSet, pinnedCBuildArtefacts } from \"./artefacts\";\nimport { bytesOf, compileModule, loadBundle, prefetch } from \"./host/artefact-loader\";\nimport { readDataDirEntries, readDataDirFile, writeDataDirEntries, writeDataDirFile } from \"./host/data-dir\";\nimport type { PostgresModule } from \"./host/emscripten\";\nimport { fetchExtensionBundle, installExtensionFiles } from \"./host/extensions\";\nimport { runInitdb } from \"./host/initdb\";\nimport { mountFor, type StorageMount } from \"./host/mounts\";\nimport { DEFAULT_START_PARAMS, PostgresInstance } from \"./host/postgres-instance\";\n\n/**\n * The C build's identity, recorded in every data directory it creates (ADR-0063). Its release and data\n * format are the pinned pgwasm-postgres release's (`bun run pgwasm:pin` writes both; ADR-0064): the\n * release is the build's name in version(), and `pgwasm:pin` refuses a release of another data format.\n */\nexport const C_BUILD_IDENTITY: BuildIdentity = {\n name: \"c\",\n dataFormat: ARTEFACT_RELEASE.dataFormat,\n // Every data directory made before builds were recorded was made by this build.\n claimsUnmarkedDirectories: true,\n release: ARTEFACT_RELEASE.name,\n};\n\nconst C_BUILD_CAPABILITIES: BuildCapabilities = {\n sessions: 1,\n requiresCrossOriginIsolation: false,\n filesystems: [\"memory\", \"idb\", \"file\", \"vfs\"],\n synchronousExchange: true,\n blobDevice: true,\n};\n\n/**\n * The C build's artefacts, fetched and compiled ahead of a boot (e.g. by an app's warm module on an earlier\n * screen, from the URLs in `cBuildArtefacts`). A field left out is loaded by the build itself.\n */\nexport interface CBuildAssets {\n readonly postgresWasmModule?: WebAssembly.Module;\n readonly initdbWasmModule?: WebAssembly.Module;\n readonly fsBundle?: Blob;\n}\n\nexport interface CBuildOptions {\n /** The Postgres module, compiled ahead (e.g. on an earlier screen). */\n readonly postgresWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;\n /** The initdb module, compiled ahead; used only when a data directory is created. */\n readonly initdbWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;\n /** The filesystem bundle, fetched ahead. */\n readonly fsBundle?: Blob | Promise<Blob>;\n /**\n * The artefacts being warmed ahead. A boot waits for the promise to settle and uses each asset it\n * resolves with in place of that artefact's own load. The warm-up is only an accelerator: a rejected\n * promise never fails a boot, the build loads the artefacts itself instead. An explicit\n * `postgresWasmModule`, `initdbWasmModule` or `fsBundle` wins over the same asset.\n */\n readonly assets?: Promise<CBuildAssets>;\n /** @internal A test's view of each Postgres module the build instantiates. */\n readonly onPostgresModule?: (module: PostgresModule) => void;\n /** @internal Every command line initdb runs through the host. */\n readonly onInitdbCommand?: (command: string) => void;\n}\n\ninterface Resolved {\n readonly artefacts: CBuildArtefactSet;\n readonly postgresWasm: () => Promise<WebAssembly.Module>;\n readonly initdbWasm: () => Promise<WebAssembly.Module>;\n readonly fsBundle: () => Promise<ArrayBuffer>;\n readonly options: CBuildOptions;\n}\n\nclass CRunningPostgres implements RunningPostgres {\n readonly #instance: PostgresInstance;\n readonly #mount: StorageMount;\n #sessionOpened = false;\n readonly blob: BlobDevice;\n\n constructor(instance: PostgresInstance, mount: StorageMount) {\n this.#instance = instance;\n this.#mount = mount;\n this.blob = {\n setReadSource: (data) => instance.setBlobReadSource(data),\n takeWritten: () => instance.takeBlobWritten(),\n };\n }\n\n async openSession(): Promise<WireSession> {\n if (this.#sessionOpened) throw new Error(\"The C build holds a single session, and it is open.\");\n this.#sessionOpened = true;\n const instance = this.#instance;\n return {\n exchange: (message, onData) => instance.exchange(message, onData),\n onUnsolicited: undefined,\n close: async () => {},\n };\n }\n\n async persist(relaxed: boolean): Promise<void> {\n await this.#mount.persist(this.#instance.module, relaxed);\n }\n\n async readEntries(): Promise<DataDirEntry[]> {\n return readDataDirEntries(this.#instance.module.FS);\n }\n\n async shutdown(): Promise<void> {\n this.#instance.shutdown();\n }\n\n async release(options: { readonly afterFailedBoot?: boolean } = {}): Promise<void> {\n try {\n if (options.afterFailedBoot) await this.#mount.cleanupFailedInit(this.#instance.module);\n else await this.#mount.close(this.#instance.module);\n } finally {\n this.#instance.dispose(options.afterFailedBoot ? 1 : 0);\n }\n }\n}\n\nclass CMountedDataDirectory implements MountedDataDirectory {\n readonly #instance: PostgresInstance;\n readonly #mount: StorageMount;\n readonly #request: BootRequest;\n readonly #resolved: Resolved;\n readonly #extensionBundles: Promise<TarEntry[][]>;\n\n constructor(\n instance: PostgresInstance,\n mount: StorageMount,\n request: BootRequest,\n resolved: Resolved,\n extensionBundles: Promise<TarEntry[][]>,\n ) {\n this.#instance = instance;\n this.#mount = mount;\n this.#request = request;\n this.#resolved = resolved;\n this.#extensionBundles = extensionBundles;\n }\n\n get #FS() {\n return this.#instance.module.FS;\n }\n\n async readFile(path: string): Promise<Uint8Array | undefined> {\n return readDataDirFile(this.#FS, path);\n }\n\n async createCluster(): Promise<void> {\n // initdb runs on a scratch instance of its own, never on the mounted storage: its backend\n // invocations reset the instance's heap between runs, and a filesystem holding exclusive resources\n // (an OPFS store's handles) must not be initialised twice.\n const scratch = await PostgresInstance.create({\n glue: this.#resolved.artefacts,\n wasmModule: this.#resolved.postgresWasm(),\n fsBundle: this.#resolved.fsBundle(),\n user: this.#request.user,\n database: this.#request.database,\n debug: this.#request.debug,\n });\n try {\n const result = await runInitdb({\n createInitdbModule: this.#resolved.artefacts.createInitdbModule,\n postgres: scratch,\n initdbWasm: await this.#resolved.initdbWasm(),\n debug: this.#request.debug,\n ...(this.#resolved.options.onInitdbCommand ? { onCommand: this.#resolved.options.onInitdbCommand } : {}),\n });\n if (result.exitCode !== 0 && !result.stderr.includes(\"exists but is not empty\")) {\n throw new Error(`initdb failed to create the data directory (exit ${result.exitCode}): ${result.stderr}`);\n }\n writeDataDirEntries(this.#FS, readDataDirEntries(scratch.module.FS));\n } finally {\n scratch.dispose(0);\n }\n }\n\n async writeEntries(entries: readonly DataDirEntry[]): Promise<void> {\n writeDataDirEntries(this.#FS, entries);\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n writeDataDirFile(this.#FS, path, data);\n }\n\n async persist(): Promise<void> {\n await this.#mount.persist(this.#instance.module, false);\n }\n\n async start(options: StartOptions): Promise<RunningPostgres> {\n const log = (...args: unknown[]) => {\n if (this.#request.debug > 0) console.log(...args);\n };\n await installExtensionFiles(this.#instance.module, await this.#extensionBundles, log);\n this.#instance.startSingleMode([\n ...DEFAULT_START_PARAMS,\n ...(this.#request.debug > 0 ? [\"-d\", String(this.#request.debug)] : []),\n ...Object.entries(options.settings).flatMap(([name, value]) => [\"-c\", `${name}=${value}`]),\n ]);\n return new CRunningPostgres(this.#instance, this.#mount);\n }\n\n async release(): Promise<void> {\n try {\n await this.#mount.cleanupFailedInit(this.#instance.module);\n } finally {\n this.#instance.dispose(1);\n }\n }\n}\n\n/**\n * A C build, optionally with its artefacts fetched and compiled ahead. `cBuild` is the build with\n * defaults; a build object can boot any number of databases.\n */\nexport function createCBuild(options: CBuildOptions = {}): PostgresBuild {\n return createCBuildFrom(C_BUILD_IDENTITY, pinnedCBuildArtefacts, options);\n}\n\n/**\n * @internal A C build on the given artefacts, recording the given identity: what {@link createCBuild}\n * builds on the pinned release's. Not exported from the package; the IndexedDB browser lane reaches it\n * from source to boot an earlier release's glue and files, so the stores that release wrote can be opened\n * by the current build (tests/e2e/pgwasm-idb/continuity-builds.ts). That list starts empty at 18.6.2: its\n * filesystem root changed, so no earlier release's stores open under it; 18.6.2 is the first entry.\n */\nexport function createCBuildFrom(\n identity: BuildIdentity,\n artefacts: CBuildArtefactSet,\n options: CBuildOptions = {},\n): PostgresBuild {\n // Settled once, and handled here: a failed warm-up means the lazy load, never an unhandled rejection.\n const warmed: Promise<CBuildAssets | undefined> =\n options.assets === undefined\n ? Promise.resolve(undefined)\n : options.assets.then(\n (assets) => assets,\n () => undefined,\n );\n const resolved: Resolved = {\n artefacts,\n postgresWasm: async () => {\n const module = options.postgresWasmModule ?? (await warmed)?.postgresWasmModule;\n return module === undefined ? compileModule(artefacts.postgresWasm) : module;\n },\n initdbWasm: async () => {\n const module = options.initdbWasmModule ?? (await warmed)?.initdbWasmModule;\n return module === undefined ? compileModule(artefacts.initdbWasm) : module;\n },\n fsBundle: async () => {\n const bundle = options.fsBundle ?? (await warmed)?.fsBundle;\n return bundle === undefined ? loadBundle(artefacts.fsBundle) : bytesOf(bundle);\n },\n options,\n };\n\n // Everything a boot waits on before its own work: the warm-up, and the explicit Postgres module and\n // filesystem bundle when given as promises. Settled, never rejected: a rejected one fails (or falls back in)\n // the boot itself, which is where that belongs.\n const prepared: Promise<void> = Promise.allSettled([warmed, options.postgresWasmModule, options.fsBundle]).then(\n () => undefined,\n );\n\n return {\n identity,\n capabilities: C_BUILD_CAPABILITIES,\n prepare: () => prepared,\n async boot(request: BootRequest): Promise<MountedDataDirectory> {\n const extensionBundles = Promise.all(request.extensions.map((extension) => fetchExtensionBundle(extension)));\n // Awaited in start(); a failure before then must not surface as unhandled.\n extensionBundles.catch(() => undefined);\n // Start the downloads the warm-up did not cover now; the boot needs them in turn.\n const assets = await warmed;\n if (options.postgresWasmModule === undefined && assets?.postgresWasmModule === undefined) {\n prefetch(artefacts.postgresWasm);\n }\n if (options.initdbWasmModule === undefined && assets?.initdbWasmModule === undefined) {\n prefetch(artefacts.initdbWasm);\n }\n\n const mount = mountFor(request.storage);\n await mount.acquire();\n let instance: PostgresInstance | undefined;\n try {\n instance = await PostgresInstance.create({\n glue: artefacts,\n wasmModule: resolved.postgresWasm(),\n fsBundle: resolved.fsBundle(),\n user: request.user,\n database: request.database,\n debug: request.debug,\n ...(mount.preRun ? { mountPreRun: mount.preRun } : {}),\n ...(options.onPostgresModule ? { onModule: options.onPostgresModule } : {}),\n });\n await mount.initialSync(instance.module);\n } catch (error) {\n try {\n await mount.cleanupFailedInit(instance?.module);\n } catch {\n // The boot already failed; keep its cause.\n }\n instance?.dispose(1);\n throw error;\n }\n return new CMountedDataDirectory(instance, mount, request, resolved, extensionBundles);\n },\n };\n}\n\n/** The C build with its defaults: the artefacts load from next to this module when first booted. */\nexport const cBuild: PostgresBuild = createCBuild();\n"
20
+ "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { DebugLevel } from \"@pgxsinkit/pgwasm/build\";\n\nimport type { CBuildArtefactSet } from \"../artefacts\";\nimport type { EmscriptenStream, ModuleOverrides, PostgresModule } from \"./emscripten\";\nimport { preservingExitCode } from \"./exit-code\";\nimport { ICU_DATA_PATH, INITDB_EXE_PATH, LOCALE_LIST_PATH, PGDATA, POSTGRES_EXE_PATH } from \"./paths\";\n\n/** Postgres' error longjmp, intercepted by the host: keep in sync with pgwasmc.c's POSTGRES_MAIN_LONGJMP. */\nconst POSTGRES_MAIN_LONGJMP = 100;\n/** The exit status single-user mode reports when it started and stays alive: the C build's `PGWASM_EXIT_ALIVE`. */\nconst PGWASM_EXIT_ALIVE = 99;\nconst INITIAL_MEMORY_PAGES = 2048;\nconst MAXIMUM_MEMORY_PAGES = 32768;\n\n/** The single-user-mode arguments every start begins with. */\nexport const DEFAULT_START_PARAMS: readonly string[] = [\n \"--single\", // single-user mode (must come first)\n \"-F\", // fsync off: the host persists storage itself\n \"-O\", // allow system table structure changes\n \"-j\", // no newline as the interactive query delimiter\n \"-c\",\n \"search_path=public\",\n \"-c\",\n \"exit_on_error=false\",\n \"-c\",\n \"log_checkpoints=false\",\n \"-c\",\n \"max_worker_processes=0\",\n \"-c\",\n \"max_parallel_workers=0\",\n \"-c\",\n \"max_parallel_workers_per_gather=0\",\n \"-c\",\n \"io_method=sync\",\n \"-c\",\n \"max_parallel_maintenance_workers=0\",\n];\n\n/**\n * Whether `error` is one of the exceptions the Emscripten runtime throws on purpose to unwind the wasm\n * stack back to the main loop, which handles them:\n * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgwasm_longjmp (pgwasmc.c) delivers Postgres'\n * siglongjmp to its main-loop error handler, and how a Terminate message ends the loop;\n * - what an emscripten-mode longjmp throws, should one pass every invoke_* frame: an instance of the\n * glue's (unexported) `EmscriptenSjLj` class on Emscripten 6.0.10 (pgwasm-postgres 18.6.1 onwards), a\n * number on Emscripten 3.1.74 (18.3.0 and 18.6.0). Both are recognised, so the host works with either.\n *\n * An `ExitStatus` (from exit()/proc_exit(): a FATAL error) is not: the backend's exit callbacks have\n * already torn its session down, so the loop cannot resume on it (see {@link exitStatusOf}).\n */\nexport function isEmscriptenUnwind(error: unknown): boolean {\n if (error === \"unwind\" || typeof error === \"number\") return true;\n if (typeof error !== \"object\" || error === null) return false;\n return (error as { constructor?: { name?: unknown } }).constructor?.name === \"EmscriptenSjLj\";\n}\n\nconst invalidBundleSize = (actual: number, expected: number): Error =>\n new Error(`Invalid filesystem bundle size: ${actual} !== ${expected}`);\n\n/** The status of the `ExitStatus` the runtime throws from exit()/proc_exit(), or undefined for anything else. */\nexport function exitStatusOf(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || (error as { name?: unknown }).name !== \"ExitStatus\") {\n return undefined;\n }\n const status = (error as { status?: unknown }).status;\n return typeof status === \"number\" ? status : -1;\n}\n\n/**\n * The wasm's shadow stack pointer: the C stack in linear memory, which the glue exports neither\n * `stackSave` nor `stackRestore` for. A throw that unwinds wasm frames (an ERROR's intercepted\n * siglongjmp, a FATAL's exit) skips their epilogues, so the pointer stays where the deepest of them left\n * it. Unrestored, every ERROR leaked that much stack (about 1.2 kB for `SELECT 1/0`), until\n * `max_stack_depth` refused every statement (from about the 1,700th error in one instance). The host\n * restores it to where the call started, as Postgres' own siglongjmp to PostgresMain would.\n */\ninterface ShadowStack {\n save(): number;\n restore(pointer: number): void;\n}\n\nfunction shadowStackOf(instance: WebAssembly.Instance): ShadowStack {\n const current = instance.exports[\"emscripten_stack_get_current\"];\n const restore = instance.exports[\"_emscripten_stack_restore\"];\n if (typeof current !== \"function\" || typeof restore !== \"function\") {\n throw new Error(\n \"The Postgres module exports no emscripten_stack_get_current or _emscripten_stack_restore: the host cannot restore its stack after an error\",\n );\n }\n return {\n save: () => (current as () => number)(),\n restore: (pointer) => (restore as (pointer: number) => void)(pointer),\n };\n}\n\nexport interface PostgresInstanceConfig {\n /** The Postgres glue (`postgres.js`) and the size of the filesystem bundle it was packaged with. */\n readonly glue: Pick<CBuildArtefactSet, \"createPostgresModule\" | \"fsBundleBytes\">;\n readonly wasmModule: Promise<WebAssembly.Module>;\n /** The filesystem bundle, a copy of its own for this instance. */\n readonly fsBundle: Promise<ArrayBuffer>;\n readonly user: string;\n readonly database: string;\n readonly debug: DebugLevel;\n /** preRun steps that mount storage over the data directory; run after the filesystem bundle loads. */\n readonly mountPreRun?: (module: PostgresModule) => void;\n /** @internal A test's view of the module. */\n readonly onModule?: (module: PostgresModule) => void;\n}\n\n/**\n * One Emscripten instance of the Postgres module and the host state around it: the socket callbacks\n * the wire goes through, the `/dev/blob` device, and the external-command hooks.\n */\nexport class PostgresInstance {\n readonly module: PostgresModule;\n readonly #debug: DebugLevel;\n readonly #stack: ShadowStack;\n // Frontend bytes being fed to Postgres, and how far it has read them.\n #input: Uint8Array = new Uint8Array(0);\n #readOffset = 0;\n // Where backend bytes go during an exchange.\n #sink: ((chunk: Uint8Array) => void) | undefined;\n #blobReadSource: Uint8Array | undefined;\n #blobWritten: Uint8Array<ArrayBuffer>[] | undefined;\n #externalCommandStream: number | null = null;\n #functionPointers: number[] = [];\n #failed = false;\n #exited = false;\n // The last lines Postgres wrote to stderr (since the exchange began, during one), for the error when it\n // fails to start or exits.\n readonly #stderr: string[] = [];\n\n private constructor(module: PostgresModule, debug: DebugLevel, stack: ShadowStack) {\n this.module = module;\n this.#debug = debug;\n this.#stack = stack;\n }\n\n static async create(config: PostgresInstanceConfig): Promise<PostgresInstance> {\n const [wasmModule, fsBundle] = await Promise.all([config.wasmModule, config.fsBundle]);\n // Checked before the glue runs. Emscripten 6's file packager (pgwasm-postgres 18.6.1 onwards) loads the\n // bundle in an async function it never awaits, so a throw from getPreloadedPackage no longer rejects the\n // factory: it is an unhandled rejection, and the boot fails later on a missing bundle file with an\n // unrelated filesystem error.\n const { createPostgresModule, fsBundleBytes } = config.glue;\n if (fsBundle.byteLength !== fsBundleBytes) throw invalidBundleSize(fsBundle.byteLength, fsBundleBytes);\n let host: PostgresInstance | undefined;\n let stack: ShadowStack | undefined;\n const pendingHost = (module: PostgresModule): PostgresInstance => {\n // The runtime runs no preRun step before the instance it waits on (instantiateWasm) is ready.\n if (stack === undefined) throw new Error(\"The Postgres module initialised before its wasm instance\");\n host ??= new PostgresInstance(module, config.debug, stack);\n return host;\n };\n let rejectInstantiation: (error: unknown) => void = () => undefined;\n const instantiationFailed = new Promise<never>((_, reject) => {\n rejectInstantiation = reject;\n });\n\n const log = (text: string) => {\n if (config.debug > 0) console.debug(text);\n };\n const logError = (text: string) => {\n if (host) host.#recordStderr(text);\n if (config.debug > 0) console.error(text);\n };\n\n // Emscripten runs preRun callbacks in the order listed (3.1.74, before pgwasm-postgres 18.6.1, ran them\n // in reverse). The build's pre-js loads the filesystem bundle before the first of them, so every one\n // sees the bundle's files. They touch disjoint state (the runtime hook, /dev/blob, the environment, the\n // bundle's files outside the data directory, then the storage mount over the data directory), so none\n // depends on the order of the others.\n const preRun: ((module: PostgresModule) => void)[] = [\n (module) => {\n module.onRuntimeInitialized = () => pendingHost(module).#onRuntimeInitialized();\n },\n (module) => pendingHost(module).#registerBlobDevice(),\n (module) => {\n const env = module.ENV;\n env[\"HOME\"] = \"/home/postgres\";\n env[\"USER\"] = \"postgres\";\n env[\"LOGNAME\"] = \"postgres\";\n env[\"PGDATA\"] = PGDATA;\n env[\"PGUSER\"] = config.user;\n env[\"PGDATABASE\"] = config.database;\n env[\"LANG\"] = \"en_US.UTF-8\";\n env[\"LC_COLLATE\"] = \"en_US.UTF-8\";\n env[\"LC_CTYPE\"] = \"en_US.UTF-8\";\n env[\"TZ\"] = \"UTC\";\n env[\"PGTZ\"] = \"UTC\";\n env[\"PGCLIENTENCODING\"] = \"UTF8\";\n env[\"ICU_DATA\"] = ICU_DATA_PATH;\n },\n (module) => {\n module.FS.chmod(\"/home/postgres/.pgpass\", 0o600); // libpq ignores a .pgpass others can read\n module.FS.chmod(INITDB_EXE_PATH, 0o555);\n module.FS.chmod(POSTGRES_EXE_PATH, 0o555);\n },\n ];\n if (config.mountPreRun) preRun.push(config.mountPreRun);\n\n const overrides: ModuleOverrides<PostgresModule> = {\n thisProgram: POSTGRES_EXE_PATH,\n arguments: config.debug > 0 ? [\"-d\", String(config.debug)] : [],\n noExitRuntime: true,\n wasmMemory: new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: MAXIMUM_MEMORY_PAGES }),\n // A stdin that is always at EOF, so a browser never prompts.\n stdin: () => null,\n print: log,\n printErr: logError,\n instantiateWasm: (imports, successCallback) => {\n WebAssembly.instantiate(wasmModule, imports).then(\n (instance) => {\n try {\n stack = shadowStackOf(instance);\n } catch (error) {\n rejectInstantiation(error);\n return;\n }\n successCallback(instance, wasmModule);\n },\n (error: unknown) => rejectInstantiation(error),\n );\n return {};\n },\n getPreloadedPackage: (name, size) => {\n if (name !== \"postgres.data\") throw new Error(`Unknown filesystem package: ${name}`);\n if (fsBundle.byteLength !== size) {\n // Unreachable while the glue and the pins agree; if they ever do not, fail the boot with this error.\n const error = invalidBundleSize(fsBundle.byteLength, size);\n rejectInstantiation(error);\n throw error;\n }\n return fsBundle;\n },\n preRun,\n };\n\n const module = await Promise.race([createPostgresModule(overrides), instantiationFailed]);\n const instance = pendingHost(module);\n config.onModule?.(module);\n return instance;\n }\n\n #recordStderr(text: string): void {\n this.#stderr.push(text);\n if (this.#stderr.length > 20) this.#stderr.shift();\n }\n\n #log(...args: unknown[]): void {\n if (this.#debug > 0) console.log(...args);\n }\n\n #addFunction(fn: (...args: number[]) => number | void, signature: string): number {\n const pointer = this.module.addFunction(fn, signature);\n this.#functionPointers.push(pointer);\n return pointer;\n }\n\n #onRuntimeInitialized(): void {\n const mod = this.module;\n // system() never runs a command: it is logged and fails.\n mod._pgwasm_set_system_fn(\n this.#addFunction((command: number) => {\n this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);\n return 1;\n }, \"pi\"),\n );\n mod._pgwasm_set_popen_fn(\n this.#addFunction((command: number, mode: number) => {\n this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));\n return this.#externalCommandStream;\n }, \"ppp\"),\n );\n mod._pgwasm_set_pclose_fn(\n this.#addFunction((stream: number) => {\n if (stream !== this.#externalCommandStream) throw new Error(`Unhandled pclose ${stream}`);\n mod._fclose(stream);\n this.#externalCommandStream = null;\n }, \"pi\"),\n );\n // Backend bytes: handed to the exchange's sink as a view of the heap, valid during the call.\n const write = this.#addFunction((pointer: number, length: number) => {\n this.#sink?.(this.module.HEAPU8.subarray(pointer, pointer + length));\n return length;\n }, \"iii\");\n // Frontend bytes: copied into the heap from the message being exchanged.\n const read = this.#addFunction((pointer: number, maxLength: number) => {\n const length = Math.min(this.#input.length - this.#readOffset, maxLength);\n this.module.HEAPU8.set(this.#input.subarray(this.#readOffset, this.#readOffset + length), pointer);\n this.#readOffset += length;\n return length;\n }, \"iii\");\n mod._pgwasm_set_rw_cbs(read, write);\n }\n\n #handleExternalCommand(command: string, mode: string): number {\n if (command.startsWith(\"locale -a\") && mode === \"r\") {\n return this.module._fopen(\n this.module.stringToUTF8OnStack(LOCALE_LIST_PATH),\n this.module.stringToUTF8OnStack(mode),\n );\n }\n throw new Error(`Unhandled external command: ${command}`);\n }\n\n /** `/dev/blob`: what `COPY … FROM '/dev/blob'` reads and `COPY … TO '/dev/blob'` writes. */\n #registerBlobDevice(): void {\n const FS = this.module.FS;\n const device = FS.makedev(64, 0);\n FS.registerDevice(device, {\n open: () => undefined,\n close: () => undefined,\n read: (_stream, buffer, offset, length, position) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to read from\");\n if (position >= contents.length) return 0;\n const size = Math.min(contents.length - position, length);\n buffer.set(contents.subarray(position, position + size), offset);\n return size;\n },\n write: (_stream, buffer, offset, length) => {\n this.#blobWritten ??= [];\n this.#blobWritten.push(new Uint8Array(buffer.subarray(offset, offset + length)));\n return length;\n },\n llseek: (stream: EmscriptenStream, offset: number, whence: number) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to llseek\");\n let position = offset;\n if (whence === 1) position += stream.position;\n else if (whence === 2) position = contents.length;\n if (position < 0) throw new FS.ErrnoError(28);\n return position;\n },\n });\n FS.mkdev(\"/dev/blob\", device);\n }\n\n setBlobReadSource(data: Uint8Array | undefined): void {\n this.#blobReadSource = data;\n }\n\n takeBlobWritten(): Uint8Array<ArrayBuffer>[] | undefined {\n const written = this.#blobWritten;\n this.#blobWritten = undefined;\n return written;\n }\n\n /** Run `callMain`, leaving the host's exit code as it was. */\n callMain(args: string[]): number {\n return preservingExitCode(() => this.module.callMain(args));\n }\n\n /** Start Postgres in single-user mode on the data directory. */\n startSingleMode(startParams: readonly string[]): void {\n const mod = this.module;\n mod._pgwasm_setPostgresActive(1);\n this.callMain([...startParams, \"-D\", PGDATA, mod.ENV[\"PGDATABASE\"] ?? \"postgres\"]);\n const exitStatus = mod._pgwasm_setPostgresExitStatus(-3);\n if (exitStatus !== PGWASM_EXIT_ALIVE) {\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:\\n${output}` : \"\"}`,\n );\n }\n mod._pgwasm_startPostgres();\n }\n\n /**\n * One exchange on the single session: feed `message` to Postgres and hand every backend byte it\n * produces to `onData`, synchronously. A startup packet (first byte 0) is processed as one; a\n * Terminate (`X`) is ignored, as the session ends with the instance. A throw that is not Postgres'\n * own error unwind means the wasm stack was abandoned mid-function, and an exit (a FATAL error) means\n * the backend tore its session down: either fails the session, which refuses every later exchange.\n */\n exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void {\n if (this.#failed) throw new Error(\"The C build's session failed and cannot be used again\");\n if (message[0] === 0x58) return; // Terminate\n this.#sink = onData;\n this.#input = message;\n this.#readOffset = 0;\n this.#stderr.length = 0;\n try {\n if (message[0] === 0) {\n this.#processStartupPacket();\n return;\n }\n this.#runMainLoop(message);\n } catch (error) {\n const status = exitStatusOf(error);\n if (status === undefined) throw error;\n this.#failed = true;\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres exited with status ${status} during an exchange: a FATAL error ended the C build's session${output ? `:\\n${output}` : \"\"}`,\n { cause: error },\n );\n } finally {\n this.#sink = undefined;\n this.#input = new Uint8Array(0);\n }\n }\n\n /**\n * A call into the backend that may unwind (an ERROR's intercepted siglongjmp, a FATAL's exit):\n * should it throw, the shadow stack pointer is restored to where it began (see {@link ShadowStack}).\n */\n #call<T>(call: () => T): T {\n const stack = this.#stack.save();\n try {\n return call();\n } catch (error) {\n this.#stack.restore(stack);\n throw error;\n }\n }\n\n #processStartupPacket(): void {\n const mod = this.module;\n const result = this.#call(() => mod._ProcessStartupPacket(mod._pgwasm_getMyProcPort()));\n if (result !== 0) throw new Error(\"Cannot process the startup packet\");\n this.#call(() => {\n mod._pgwasm_sendConnData();\n mod._pgwasm_pq_flush();\n });\n }\n\n #runMainLoop(message: Uint8Array): void {\n const mod = this.module;\n try {\n // One message may carry several batched statements; the loop returns after each.\n while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {\n const stack = this.#stack.save();\n try {\n mod._PostgresMainLoopOnce();\n } catch (error) {\n // First, as Postgres' own siglongjmp to PostgresMain would: the throw skipped the epilogues of\n // every frame it abandoned (see ShadowStack).\n this.#stack.restore(stack);\n if (!isEmscriptenUnwind(error)) throw error;\n if (mod._pgwasm_setPostgresExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {\n // Postgres raised an error: its siglongjmp into main was intercepted, and its error handling\n // runs here before the loop resumes with the rest of the batch.\n this.#call(() => mod._PostgresMainLongJmp());\n }\n }\n }\n this.#call(() => {\n mod._PostgresSendReadyForQueryIfNecessary();\n mod._pgwasm_pq_flush();\n });\n } catch (error) {\n this.#failed = true;\n throw error;\n }\n }\n\n /** Postgres' clean exit: its atexit callbacks. An exit status of 0 is the normal outcome. */\n shutdown(): void {\n const mod = this.module;\n try {\n preservingExitCode(() => {\n mod._pgwasm_setPostgresActive(0);\n this.#call(() => mod._pgwasm_run_atexit_funcs());\n });\n } catch (error) {\n const exit = error as { name?: unknown; status?: unknown };\n if (!(exit.name === \"ExitStatus\" && exit.status === 0)) throw error;\n }\n }\n\n /** Release the callbacks and exit the runtime, which `noExitRuntime` otherwise keeps alive. */\n dispose(exitStatus: number): void {\n if (this.#exited) return;\n this.#exited = true;\n for (const pointer of this.#functionPointers) {\n try {\n this.module.removeFunction(pointer);\n } catch {\n // continue releasing\n }\n }\n this.#functionPointers = [];\n try {\n preservingExitCode(() => this.module._emscripten_force_exit(exitStatus));\n } catch {\n // The runtime reports a forced exit by throwing ExitStatus.\n }\n }\n}\n",
21
+ "import { PgwasmError } from \"@pgxsinkit/pgwasm\";\n\nimport { ARTEFACT_RELEASE } from \"./artefact-pins\";\n\n/** PostgreSQL's major data-directory version, independent of pgwasm's build-marker format. */\nexport const C_POSTGRES_MAJOR = /^REL_(\\d+)_/.exec(ARTEFACT_RELEASE.upstream.tag)?.[1];\n\n/** The C host cannot open this PostgreSQL major; retrying cannot make the directory compatible. */\nexport class PostgresVersionMismatchError extends PgwasmError {\n override name = \"PostgresVersionMismatchError\";\n readonly expected: string;\n readonly found: string | undefined;\n /** Structured fields retained alongside the stable error name by the worker bridge. */\n readonly detail: { readonly expected: string; readonly found: string | undefined };\n\n constructor(expected: string, found: string | undefined) {\n super(\n `This C build requires PostgreSQL ${expected}, but the data directory's PG_VERSION is ` +\n `${found === undefined ? \"missing\" : JSON.stringify(found)}. Use a separately named fresh PostgreSQL ${expected} store; ` +\n \"the existing directory is not migrated or replaced.\",\n );\n this.expected = expected;\n this.found = found;\n this.detail = { expected, found };\n }\n}\n\n/** Refuse another major before the C host writes a restored image or starts a mounted cluster. */\nexport function checkPostgresVersion(bytes: Uint8Array | undefined): void {\n if (C_POSTGRES_MAJOR === undefined) throw new Error(\"The pinned C build has no PostgreSQL major version.\");\n const found = bytes === undefined ? undefined : new TextDecoder().decode(bytes).trim();\n if (found === C_POSTGRES_MAJOR) return;\n throw new PostgresVersionMismatchError(C_POSTGRES_MAJOR, found);\n}\n",
22
+ "// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type {\n BlobDevice,\n BootRequest,\n BuildCapabilities,\n BuildIdentity,\n DataDirEntry,\n MountedDataDirectory,\n PostgresBuild,\n RunningPostgres,\n StartOptions,\n TarEntry,\n WireSession,\n} from \"@pgxsinkit/pgwasm/build\";\n\nimport { ARTEFACT_RELEASE } from \"./artefact-pins\";\nimport { type CBuildArtefactSet, pinnedCBuildArtefacts } from \"./artefacts\";\nimport { bytesOf, compileModule, loadBundle, prefetch } from \"./host/artefact-loader\";\nimport { readDataDirEntries, readDataDirFile, writeDataDirEntries, writeDataDirFile } from \"./host/data-dir\";\nimport type { PostgresModule } from \"./host/emscripten\";\nimport { fetchExtensionBundle, installExtensionFiles } from \"./host/extensions\";\nimport { runInitdb } from \"./host/initdb\";\nimport { mountFor, type StorageMount } from \"./host/mounts\";\nimport { DEFAULT_START_PARAMS, PostgresInstance } from \"./host/postgres-instance\";\nimport { checkPostgresVersion } from \"./postgres-version\";\n\n/**\n * The C build's identity, recorded in every data directory it creates (ADR-0063). Its release and data\n * format are the pinned pgwasm-postgres release's (`bun run pgwasm:pin` writes both; ADR-0064): the\n * release is the build's name in version(). Changing formats is an explicit fresh-store adoption;\n * existing directories and backups still have to match this build's format and PostgreSQL major.\n */\nexport const C_BUILD_IDENTITY: BuildIdentity = {\n name: \"c\",\n dataFormat: ARTEFACT_RELEASE.dataFormat,\n // Unmarked directories are the C build's only when their PG_VERSION also matches (checked below).\n claimsUnmarkedDirectories: true,\n release: ARTEFACT_RELEASE.name,\n};\n\nconst C_BUILD_CAPABILITIES: BuildCapabilities = {\n sessions: 1,\n requiresCrossOriginIsolation: false,\n filesystems: [\"memory\", \"idb\", \"file\", \"vfs\"],\n synchronousExchange: true,\n blobDevice: true,\n};\n\n/**\n * The C build's artefacts, fetched and compiled ahead of a boot (e.g. by an app's warm module on an earlier\n * screen, from the URLs in `cBuildArtefacts`). A field left out is loaded by the build itself.\n */\nexport interface CBuildAssets {\n readonly postgresWasmModule?: WebAssembly.Module;\n readonly initdbWasmModule?: WebAssembly.Module;\n readonly fsBundle?: Blob;\n}\n\nexport interface CBuildOptions {\n /** The Postgres module, compiled ahead (e.g. on an earlier screen). */\n readonly postgresWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;\n /** The initdb module, compiled ahead; used only when a data directory is created. */\n readonly initdbWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;\n /** The filesystem bundle, fetched ahead. */\n readonly fsBundle?: Blob | Promise<Blob>;\n /**\n * The artefacts being warmed ahead. A boot waits for the promise to settle and uses each asset it\n * resolves with in place of that artefact's own load. The warm-up is only an accelerator: a rejected\n * promise never fails a boot, the build loads the artefacts itself instead. An explicit\n * `postgresWasmModule`, `initdbWasmModule` or `fsBundle` wins over the same asset.\n */\n readonly assets?: Promise<CBuildAssets>;\n /** @internal A test's view of each Postgres module the build instantiates. */\n readonly onPostgresModule?: (module: PostgresModule) => void;\n /** @internal Every command line initdb runs through the host. */\n readonly onInitdbCommand?: (command: string) => void;\n}\n\ninterface Resolved {\n readonly artefacts: CBuildArtefactSet;\n readonly postgresWasm: () => Promise<WebAssembly.Module>;\n readonly initdbWasm: () => Promise<WebAssembly.Module>;\n readonly fsBundle: () => Promise<ArrayBuffer>;\n readonly options: CBuildOptions;\n}\n\nclass CRunningPostgres implements RunningPostgres {\n readonly #instance: PostgresInstance;\n readonly #mount: StorageMount;\n #sessionOpened = false;\n readonly blob: BlobDevice;\n\n constructor(instance: PostgresInstance, mount: StorageMount) {\n this.#instance = instance;\n this.#mount = mount;\n this.blob = {\n setReadSource: (data) => instance.setBlobReadSource(data),\n takeWritten: () => instance.takeBlobWritten(),\n };\n }\n\n async openSession(): Promise<WireSession> {\n if (this.#sessionOpened) throw new Error(\"The C build holds a single session, and it is open.\");\n this.#sessionOpened = true;\n const instance = this.#instance;\n return {\n exchange: (message, onData) => instance.exchange(message, onData),\n onUnsolicited: undefined,\n close: async () => {},\n };\n }\n\n async persist(relaxed: boolean): Promise<void> {\n await this.#mount.persist(this.#instance.module, relaxed);\n }\n\n async readEntries(): Promise<DataDirEntry[]> {\n return readDataDirEntries(this.#instance.module.FS);\n }\n\n async shutdown(): Promise<void> {\n this.#instance.shutdown();\n }\n\n async release(options: { readonly afterFailedBoot?: boolean } = {}): Promise<void> {\n try {\n if (options.afterFailedBoot) await this.#mount.cleanupFailedInit(this.#instance.module);\n else await this.#mount.close(this.#instance.module);\n } finally {\n this.#instance.dispose(options.afterFailedBoot ? 1 : 0);\n }\n }\n}\n\nclass CMountedDataDirectory implements MountedDataDirectory {\n readonly #instance: PostgresInstance;\n readonly #mount: StorageMount;\n readonly #request: BootRequest;\n readonly #resolved: Resolved;\n readonly #extensionBundles: Promise<TarEntry[][]>;\n\n constructor(\n instance: PostgresInstance,\n mount: StorageMount,\n request: BootRequest,\n resolved: Resolved,\n extensionBundles: Promise<TarEntry[][]>,\n ) {\n this.#instance = instance;\n this.#mount = mount;\n this.#request = request;\n this.#resolved = resolved;\n this.#extensionBundles = extensionBundles;\n }\n\n get #FS() {\n return this.#instance.module.FS;\n }\n\n async readFile(path: string): Promise<Uint8Array | undefined> {\n const bytes = readDataDirFile(this.#FS, path);\n // Shared boot checks a marked directory's build/format itself. Old unmarked directories have no\n // such guard, so refuse another PostgreSQL major before they can reach startup or any write.\n if (path === \"/PG_VERSION\" && bytes !== undefined && readDataDirFile(this.#FS, \"/PGWASM_BUILD\") === undefined) {\n checkPostgresVersion(bytes);\n }\n return bytes;\n }\n\n async createCluster(): Promise<void> {\n // initdb runs on a scratch instance of its own, never on the mounted storage: its backend\n // invocations reset the instance's heap between runs, and a filesystem holding exclusive resources\n // (an OPFS store's handles) must not be initialised twice.\n const scratch = await PostgresInstance.create({\n glue: this.#resolved.artefacts,\n wasmModule: this.#resolved.postgresWasm(),\n fsBundle: this.#resolved.fsBundle(),\n user: this.#request.user,\n database: this.#request.database,\n debug: this.#request.debug,\n });\n try {\n const result = await runInitdb({\n createInitdbModule: this.#resolved.artefacts.createInitdbModule,\n postgres: scratch,\n initdbWasm: await this.#resolved.initdbWasm(),\n debug: this.#request.debug,\n ...(this.#resolved.options.onInitdbCommand ? { onCommand: this.#resolved.options.onInitdbCommand } : {}),\n });\n if (result.exitCode !== 0 && !result.stderr.includes(\"exists but is not empty\")) {\n throw new Error(`initdb failed to create the data directory (exit ${result.exitCode}): ${result.stderr}`);\n }\n writeDataDirEntries(this.#FS, readDataDirEntries(scratch.module.FS));\n } finally {\n scratch.dispose(0);\n }\n }\n\n async writeEntries(entries: readonly DataDirEntry[]): Promise<void> {\n // A legacy backup can have no build marker. Check its PostgreSQL version before writing even its\n // first member: NODEFS writes immediately, and a later startup refusal cannot undo a partial restore.\n const versions = entries.filter((entry) => entry.path === \"/PG_VERSION\" && entry.type === \"file\");\n if (versions.length === 0) checkPostgresVersion(undefined);\n for (const version of versions) checkPostgresVersion(version.data);\n writeDataDirEntries(this.#FS, entries);\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n writeDataDirFile(this.#FS, path, data);\n }\n\n async persist(): Promise<void> {\n await this.#mount.persist(this.#instance.module, false);\n }\n\n async start(options: StartOptions): Promise<RunningPostgres> {\n checkPostgresVersion(readDataDirFile(this.#FS, \"/PG_VERSION\"));\n const log = (...args: unknown[]) => {\n if (this.#request.debug > 0) console.log(...args);\n };\n await installExtensionFiles(this.#instance.module, await this.#extensionBundles, log);\n this.#instance.startSingleMode([\n ...DEFAULT_START_PARAMS,\n ...(this.#request.debug > 0 ? [\"-d\", String(this.#request.debug)] : []),\n ...Object.entries(options.settings).flatMap(([name, value]) => [\"-c\", `${name}=${value}`]),\n ]);\n return new CRunningPostgres(this.#instance, this.#mount);\n }\n\n async release(): Promise<void> {\n try {\n await this.#mount.cleanupFailedInit(this.#instance.module);\n } finally {\n this.#instance.dispose(1);\n }\n }\n}\n\n/**\n * A C build, optionally with its artefacts fetched and compiled ahead. `cBuild` is the build with\n * defaults; a build object can boot any number of databases.\n */\nexport function createCBuild(options: CBuildOptions = {}): PostgresBuild {\n return createCBuildFrom(C_BUILD_IDENTITY, pinnedCBuildArtefacts, options);\n}\n\n/**\n * @internal A C build on the given artefacts, recording the given identity: what {@link createCBuild}\n * builds on the pinned release's. Not exported from the package; the IndexedDB browser lane reaches it\n * from source to boot earlier compatible releases' glue and files, then checks that the current build\n * can reopen their stores (tests/e2e/pgwasm-idb/continuity-builds.ts). PG19's format-2 list starts empty:\n * format-1 PG18 stores are explicitly refused, and future entries must preserve the PG19 host ABI too.\n */\nexport function createCBuildFrom(\n identity: BuildIdentity,\n artefacts: CBuildArtefactSet,\n options: CBuildOptions = {},\n): PostgresBuild {\n // Settled once, and handled here: a failed warm-up means the lazy load, never an unhandled rejection.\n const warmed: Promise<CBuildAssets | undefined> =\n options.assets === undefined\n ? Promise.resolve(undefined)\n : options.assets.then(\n (assets) => assets,\n () => undefined,\n );\n const resolved: Resolved = {\n artefacts,\n postgresWasm: async () => {\n const module = options.postgresWasmModule ?? (await warmed)?.postgresWasmModule;\n return module === undefined ? compileModule(artefacts.postgresWasm) : module;\n },\n initdbWasm: async () => {\n const module = options.initdbWasmModule ?? (await warmed)?.initdbWasmModule;\n return module === undefined ? compileModule(artefacts.initdbWasm) : module;\n },\n fsBundle: async () => {\n const bundle = options.fsBundle ?? (await warmed)?.fsBundle;\n return bundle === undefined ? loadBundle(artefacts.fsBundle) : bytesOf(bundle);\n },\n options,\n };\n\n // Everything a boot waits on before its own work: the warm-up, and the explicit Postgres module and\n // filesystem bundle when given as promises. Settled, never rejected: a rejected one fails (or falls back in)\n // the boot itself, which is where that belongs.\n const prepared: Promise<void> = Promise.allSettled([warmed, options.postgresWasmModule, options.fsBundle]).then(\n () => undefined,\n );\n\n return {\n identity,\n capabilities: C_BUILD_CAPABILITIES,\n prepare: () => prepared,\n async boot(request: BootRequest): Promise<MountedDataDirectory> {\n const extensionBundles = Promise.all(request.extensions.map((extension) => fetchExtensionBundle(extension)));\n // Awaited in start(); a failure before then must not surface as unhandled.\n extensionBundles.catch(() => undefined);\n // Start the downloads the warm-up did not cover now; the boot needs them in turn.\n const assets = await warmed;\n if (options.postgresWasmModule === undefined && assets?.postgresWasmModule === undefined) {\n prefetch(artefacts.postgresWasm);\n }\n if (options.initdbWasmModule === undefined && assets?.initdbWasmModule === undefined) {\n prefetch(artefacts.initdbWasm);\n }\n\n const mount = mountFor(request.storage);\n await mount.acquire();\n let instance: PostgresInstance | undefined;\n try {\n instance = await PostgresInstance.create({\n glue: artefacts,\n wasmModule: resolved.postgresWasm(),\n fsBundle: resolved.fsBundle(),\n user: request.user,\n database: request.database,\n debug: request.debug,\n ...(mount.preRun ? { mountPreRun: mount.preRun } : {}),\n ...(options.onPostgresModule ? { onModule: options.onPostgresModule } : {}),\n });\n await mount.initialSync(instance.module);\n } catch (error) {\n try {\n await mount.cleanupFailedInit(instance?.module);\n } catch {\n // The boot already failed; keep its cause.\n }\n instance?.dispose(1);\n throw error;\n }\n return new CMountedDataDirectory(instance, mount, request, resolved, extensionBundles);\n },\n };\n}\n\n/** The C build with its defaults: the artefacts load from next to this module when first booted. */\nexport const cBuild: PostgresBuild = createCBuild();\n"
22
23
  ],
23
- "mappings": ";;AAUA;AACA;;;ACCO,IAAM,mBAAmB;AAAA,EAC9B,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,UAAU,EAAE,KAAK,YAAY,QAAQ,2CAA2C;AAAA,EAChF,YAAY;AAAA,EACZ,cACE;AAAA,EACF,gBAAgB;AAClB;AAGO,IAAM,iBAAiB;AAAA,EAC5B,kBAAkB,EAAE,OAAO,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AA,QACvC,OAAO,OAAO;AAAA,QACd,IAAI;AAAA,UACF,MAAM,MAAM,kBAAkB,UAAU,MAAM;AAAA,UAC9C,MAAM;AAAA,QAGR,UAAU,QAAQ,CAAC;AAAA,QACnB,MAAM;AAAA;AAAA,MAER,OAAO,IAAI,sBAAsB,UAAU,OAAO,SAAS,UAAU,gBAAgB;AAAA;AAAA,EAEzF;AAAA;AAIK,IAAM,SAAwB,aAAa;",
25
+ "debugId": "1C7A0C07F8587C2D64756E2164756E21",
25
26
  "names": []
26
27
  }
@@ -0,0 +1,18 @@
1
+ import { PgwasmError } from "@pgxsinkit/pgwasm";
2
+ /** PostgreSQL's major data-directory version, independent of pgwasm's build-marker format. */
3
+ export declare const C_POSTGRES_MAJOR: string | undefined;
4
+ /** The C host cannot open this PostgreSQL major; retrying cannot make the directory compatible. */
5
+ export declare class PostgresVersionMismatchError extends PgwasmError {
6
+ name: string;
7
+ readonly expected: string;
8
+ readonly found: string | undefined;
9
+ /** Structured fields retained alongside the stable error name by the worker bridge. */
10
+ readonly detail: {
11
+ readonly expected: string;
12
+ readonly found: string | undefined;
13
+ };
14
+ constructor(expected: string, found: string | undefined);
15
+ }
16
+ /** Refuse another major before the C host writes a restored image or starts a mounted cluster. */
17
+ export declare function checkPostgresVersion(bytes: Uint8Array | undefined): void;
18
+ //# sourceMappingURL=postgres-version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-version.d.ts","sourceRoot":"","sources":["../src/postgres-version.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD,8FAA8F;AAC9F,eAAO,MAAM,gBAAgB,oBAAyD,CAAC;AAEvF,mGAAmG;AACnG,qBAAa,4BAA6B,SAAQ,WAAW;IAClD,IAAI,SAAkC;IAC/C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,uFAAuF;IACvF,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAC;IAEnF,YAAY,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAStD;CACF;AAED,kGAAkG;AAClG,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,CAKxE"}
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "/**\n * The C build's prepopulated data directory: a Store backup of a freshly initialised database, to start\n * from instead of running initdb.\n *\n * This entry point is emitted at its own depth (`dist/prepopulated.js`), so its relative reference to the\n * artefact stays valid once bundled; the `new URL` stays a literal so bundlers copy and fingerprint the\n * file.\n */\n\nconst prepopulatedUrl = new URL(\"../artefacts/prepopulated.tar.gz\", import.meta.url);\n\n/**\n * The prepopulated data directory, as a gzipped Store backup, for `createPgwasm({ build, loadDataDir })`:\n *\n * ```ts\n * import { createPgwasm } from \"@pgxsinkit/pgwasm\";\n * import { cBuild } from \"@pgxsinkit/pgwasm-c\";\n * import { prepopulatedDataDir } from \"@pgxsinkit/pgwasm-c/prepopulated\";\n *\n * const pg = await createPgwasm({ build: cBuild, loadDataDir: await prepopulatedDataDir() });\n * ```\n *\n * It is fetched by URL, like the build's other files, in Bun and in browsers. It is an asset of the pinned\n * pgwasm-postgres release, made deterministically by that release's own initdb; it is left unmarked, and\n * `createPgwasm` adds the marker whenever it restores an unmarked backup, so every data directory created\n * from it is marked as the C build's. Its directories are 0750 and its files 0640; a restore does not\n * carry a mode into the data directory. Like any backup of a running database it holds `/postmaster.pid`,\n * recording the engine's own process id: the C build treats it as stale and writes its own on start.\n */\nexport async function prepopulatedDataDir(): Promise<Blob> {\n const response = await fetch(prepopulatedUrl);\n if (!response.ok) {\n throw new Error(\n `Could not load the prepopulated data directory ${prepopulatedUrl.href}: HTTP ${response.status} ${response.statusText}`,\n );\n }\n return await response.blob();\n}\n"
6
6
  ],
7
- "mappings": ";;AASA,IAAM,kBAAkB,IAAI,IAAI,oCAAoC,YAAY,GAAG;AAoBnF,eAAsB,mBAAmB,GAAkB;AAAA,EACzD,MAAM,WAAW,MAAM,MAAM,eAAe;AAAA,EAC5C,IAAI,CAAC,SAAS,IAAI;AAAA,IAChB,MAAM,IAAI,MACR,kDAAkD,gBAAgB,cAAc,SAAS,UAAU,SAAS,YAC9G;AAAA,EACF;AAAA,EACA,OAAO,MAAM,SAAS,KAAK;AAAA;",
7
+ "mappings": ";;AASA,IAAM,kBAAkB,IAAI,IAAI,oCAAoC,YAAY,GAAG;AAoB5E,eAAe,mBAAmB,GAAkB;AAAA,EACzD,MAAM,WAAW,MAAM,MAAM,eAAe;AAAA,EAC5C,IAAI,CAAC,SAAS,IAAI;AAAA,IAChB,MAAM,IAAI,MACR,kDAAkD,gBAAgB,cAAc,SAAS,UAAU,SAAS,YAC9G;AAAA,EACF;AAAA,EACA,OAAO,MAAM,SAAS,KAAK;AAAA;",
8
8
  "debugId": "916605BE343ADB2864756E2164756E21",
9
9
  "names": []
10
10
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/pgwasm-c",
3
- "version": "0.5.2",
3
+ "version": "0.6.0-rc.1",
4
4
  "license": "PostgreSQL",
5
5
  "files": [
6
6
  "artefacts",
@@ -47,7 +47,7 @@
47
47
  "build": "bun --cwd ../.. run build:public-packages"
48
48
  },
49
49
  "peerDependencies": {
50
- "@pgxsinkit/pgwasm": "0.5.2"
50
+ "@pgxsinkit/pgwasm": "0.6.0-rc.1"
51
51
  },
52
52
  "repository": {
53
53
  "type": "git",