@aztec/sqlite3mc-wasm 5.2.0-nightly.20260723 → 5.2.0-nightly.20260724

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/dest/index.js CHANGED
@@ -1,28 +1,81 @@
1
+ import vendoredInit from '../vendor/jswasm/sqlite3.mjs';
1
2
  /**
2
- * Re-exports sqlite3mc's ES module default (sqlite3InitModule) and the TypeScript types expected by downstream
3
- * consumers. Mirrors the `@sqlite.org/sqlite-wasm` package default export sqlite3mc is a strict API-compatible
4
- * superset, so upstream types apply unchanged.
3
+ * Bundler-visible static reference to the wasm binary. Because the URL argument is a string literal, bundlers detect
4
+ * the expression, emit the wasm as an asset, and rewrite the URL, so the default `locateFile` below resolves to the
5
+ * emitted asset instead of guessing a path relative to the (relocated) output chunk at runtime.
6
+ */ export const SQLITE3_WASM_URL = new URL('../vendor/jswasm/sqlite3.wasm', import.meta.url);
7
+ /**
8
+ * Initializes the sqlite3mc wasm module.
9
+ *
10
+ * With no options, the wasm is fetched from {@link SQLITE3_WASM_URL}, which bundlers rewrite to their emitted asset,
11
+ * so bundled consumers work by default. Pass `locateFile`, `wasmBinary`, or `instantiateWasm` to override.
5
12
  *
6
- * BUNDLER COMPATIBILITY: SQLite3MultipleCiphers 2.3.5 stopped shipping the `-bundler-friendly` build variant, so
7
- * this entry re-exports the plain `sqlite3.mjs`. That loader always resolves `sqlite3.wasm` through its
8
- * `Module['locateFile']` hook, which computes `new URL(path, import.meta.url)` with a *dynamic* `path` invisible
9
- * to bundlers, so bundled consumers request an unhashed `sqlite3.wasm` relative to the emitted chunk and 404 at
10
- * runtime (pre-2.3.5, the bundler-friendly variant carried a statically-analyzable reference instead). To stay
11
- * bundler-friendly we wrap the init and inject `emscriptenLocateFile` the vendored loader's supported escape
12
- * hatch (`Module['locateFile']` defers to it when present on the init-module state) — resolving the wasm via a
13
- * static `new URL('…/sqlite3.wasm', import.meta.url)` that bundlers detect, emit, and rewrite. Unbundled usage is
14
- * unaffected: the static URL resolves to the real vendored path.
15
- */ import sqlite3InitModuleUnwrapped from '../vendor/jswasm/sqlite3.mjs';
16
- /** Statically analyzable wasm reference: bundlers emit the asset and rewrite this URL to its final location. */ const SQLITE3_WASM_URL = new URL('../vendor/jswasm/sqlite3.wasm', import.meta.url);
17
- const sqlite3InitModule = (...args)=>{
18
- // `sqlite3.mjs` creates `globalThis.sqlite3InitModuleState` at import time and the inner Emscripten factory
19
- // captures it (and deletes the global) on init, binding it as `this` of `Module['locateFile']`. Mutate the live
20
- // object; recreate it if a previous init already consumed it (`debugModule` must exist — the factory calls it).
21
- const g = globalThis;
22
- const state = g.sqlite3InitModuleState ??= Object.assign(Object.create(null), {
23
- debugModule: ()=>{}
13
+ * If loading the wasm fails (unreachable URL, HTTP error, corrupt bytes), the returned promise rejects with the cause.
14
+ * Exception: failures inside a caller-supplied `instantiateWasm` cannot be observed (Emscripten's hook contract has no
15
+ * error channel), so with a custom hook the promise never settles on failure.
16
+ */ export default function sqlite3InitModule(options = {}) {
17
+ return new Promise((resolve, reject)=>{
18
+ const instantiateWasm = options.instantiateWasm ?? (options.wasmBinary ? wasmBinaryInstantiator(options.wasmBinary, reject) : urlInstantiator(options.locateFile ?? defaultLocateFile, reject));
19
+ const callOptions = {
20
+ ...options,
21
+ instantiateWasm
22
+ };
23
+ installInitModuleState(callOptions);
24
+ // The vendored init consumes the installed state synchronously (its pre-js runs before the first await), so
25
+ // interleaved calls cannot observe each other's state. On instantiation failure the vendored promise never
26
+ // settles (the hook has no error channel), so the instantiators report failure through `reject` instead.
27
+ vendoredInit(callOptions).then(resolve, reject);
28
+ });
29
+ }
30
+ /** Builds an Emscripten `instantiateWasm` hook that instantiates the given bytes instead of fetching by URL. */ function wasmBinaryInstantiator(wasmBinary, onFailure) {
31
+ return (imports, onSuccess)=>{
32
+ void WebAssembly.instantiate(wasmBinary, imports).then(({ instance, module })=>onSuccess(instance, module), (error)=>onFailure(instantiationError('wasmBinary', error)));
33
+ return {};
34
+ };
35
+ }
36
+ /**
37
+ * Builds an Emscripten `instantiateWasm` hook that fetches and instantiates the wasm from the located URL, replacing
38
+ * the vendored fallback (which reports failures nowhere). Prefers streaming compilation, falling back to
39
+ * buffer-based instantiation when streaming is unavailable or fails (e.g. a server responding without the
40
+ * `application/wasm` MIME type, which `instantiateStreaming` rejects).
41
+ */ function urlInstantiator(locate, onFailure) {
42
+ return (imports, onSuccess)=>{
43
+ const url = locate('sqlite3.wasm', '');
44
+ const streaming = WebAssembly.instantiateStreaming ? WebAssembly.instantiateStreaming(fetch(url, {
45
+ credentials: 'same-origin'
46
+ }), imports).catch(()=>fetchAndInstantiate(url, imports)) : fetchAndInstantiate(url, imports);
47
+ void streaming.then(({ instance, module })=>onSuccess(instance, module), (error)=>onFailure(instantiationError(url, error)));
48
+ return {};
49
+ };
50
+ }
51
+ /** Fetches the wasm and instantiates it from a buffer, surfacing HTTP errors that streaming instantiation obscures. */ async function fetchAndInstantiate(url, imports) {
52
+ const response = await fetch(url, {
53
+ credentials: 'same-origin'
54
+ });
55
+ if (!response.ok) {
56
+ throw new Error(`HTTP ${response.status} ${response.statusText}`.trimEnd());
57
+ }
58
+ return WebAssembly.instantiate(await response.arrayBuffer(), imports);
59
+ }
60
+ function instantiationError(source, cause) {
61
+ const detail = cause instanceof Error ? cause.message : String(cause);
62
+ return new Error(`sqlite3 wasm instantiation failed (${source}): ${detail}`, {
63
+ cause
64
+ });
65
+ }
66
+ /**
67
+ * Installs the global state object the vendored module's pre-js binds its `Module.locateFile` and
68
+ * `Module.instantiateWasm` wrappers to.
69
+ */ function installInitModuleState(options) {
70
+ const urlParams = globalThis.location?.href ? new URL(globalThis.location.href).searchParams : new URLSearchParams();
71
+ const debugModule = urlParams.has('sqlite3.debugModule') ? (...args)=>console.warn('sqlite3.debugModule:', ...args) : ()=>{};
72
+ globalThis.sqlite3InitModuleState = Object.assign(Object.create(null), {
73
+ debugModule,
74
+ wasmFilename: 'sqlite3.wasm',
75
+ emscriptenLocateFile: options.locateFile ?? defaultLocateFile,
76
+ emscriptenInstantiateWasm: options.instantiateWasm
24
77
  });
25
- state.emscriptenLocateFile = (path, prefix)=>path === 'sqlite3.wasm' ? SQLITE3_WASM_URL.href : new URL(path, prefix || import.meta.url).href;
26
- return sqlite3InitModuleUnwrapped(...args);
27
- };
28
- export default sqlite3InitModule;
78
+ }
79
+ /** Resolves the wasm to {@link SQLITE3_WASM_URL} so bundled consumers load the bundler-emitted asset by default. */ function defaultLocateFile(path, prefix) {
80
+ return path === 'sqlite3.wasm' ? SQLITE3_WASM_URL.href : new URL(path, prefix || import.meta.url).href;
81
+ }
@@ -1,20 +1,33 @@
1
+ import type { Sqlite3Static } from '@sqlite.org/sqlite-wasm';
2
+ export type { Database, SAHPoolUtil, Sqlite3Static } from '@sqlite.org/sqlite-wasm';
3
+ /**
4
+ * Bundler-visible static reference to the wasm binary. Because the URL argument is a string literal, bundlers detect
5
+ * the expression, emit the wasm as an asset, and rewrite the URL, so the default `locateFile` below resolves to the
6
+ * emitted asset instead of guessing a path relative to the (relocated) output chunk at runtime.
7
+ */
8
+ export declare const SQLITE3_WASM_URL: URL;
1
9
  /**
2
- * Re-exports sqlite3mc's ES module default (sqlite3InitModule) and the TypeScript types expected by downstream
3
- * consumers. Mirrors the `@sqlite.org/sqlite-wasm` package default export — sqlite3mc is a strict API-compatible
4
- * superset, so upstream types apply unchanged.
10
+ * Emscripten module-loader options honored by {@link sqlite3InitModule}. Any further options are passed through to the
11
+ * vendored module unchanged.
12
+ */
13
+ export interface Sqlite3InitOptions {
14
+ /** Resolves the URL from which a runtime asset (in practice always `sqlite3.wasm`) is fetched. */
15
+ locateFile?: (path: string, prefix: string) => string;
16
+ /** Pre-fetched wasm bytes. When set, the wasm is instantiated directly and never fetched by URL. */
17
+ wasmBinary?: BufferSource;
18
+ /** Custom wasm instantiation hook (standard Emscripten contract). Takes precedence over `wasmBinary`. */
19
+ instantiateWasm?: (imports: WebAssembly.Imports, onSuccess: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) => object;
20
+ [key: string]: unknown;
21
+ }
22
+ /**
23
+ * Initializes the sqlite3mc wasm module.
24
+ *
25
+ * With no options, the wasm is fetched from {@link SQLITE3_WASM_URL}, which bundlers rewrite to their emitted asset,
26
+ * so bundled consumers work by default. Pass `locateFile`, `wasmBinary`, or `instantiateWasm` to override.
5
27
  *
6
- * BUNDLER COMPATIBILITY: SQLite3MultipleCiphers 2.3.5 stopped shipping the `-bundler-friendly` build variant, so
7
- * this entry re-exports the plain `sqlite3.mjs`. That loader always resolves `sqlite3.wasm` through its
8
- * `Module['locateFile']` hook, which computes `new URL(path, import.meta.url)` with a *dynamic* `path` invisible
9
- * to bundlers, so bundled consumers request an unhashed `sqlite3.wasm` relative to the emitted chunk and 404 at
10
- * runtime (pre-2.3.5, the bundler-friendly variant carried a statically-analyzable reference instead). To stay
11
- * bundler-friendly we wrap the init and inject `emscriptenLocateFile` — the vendored loader's supported escape
12
- * hatch (`Module['locateFile']` defers to it when present on the init-module state) — resolving the wasm via a
13
- * static `new URL('…/sqlite3.wasm', import.meta.url)` that bundlers detect, emit, and rewrite. Unbundled usage is
14
- * unaffected: the static URL resolves to the real vendored path.
28
+ * If loading the wasm fails (unreachable URL, HTTP error, corrupt bytes), the returned promise rejects with the cause.
29
+ * Exception: failures inside a caller-supplied `instantiateWasm` cannot be observed (Emscripten's hook contract has no
30
+ * error channel), so with a custom hook the promise never settles on failure.
15
31
  */
16
- import sqlite3InitModuleUnwrapped from '../vendor/jswasm/sqlite3.mjs';
17
- declare const sqlite3InitModule: typeof sqlite3InitModuleUnwrapped;
18
- export default sqlite3InitModule;
19
- export type { Database, SAHPoolUtil, Sqlite3Static } from '@sqlite.org/sqlite-wasm';
20
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7R0FjRztBQUNILE9BQU8sMEJBQTBCLE1BQU0sOEJBQThCLENBQUM7QUFVdEUsUUFBQSxNQUFNLGlCQUFpQixFQUFFLE9BQU8sMEJBVy9CLENBQUM7QUFFRixlQUFlLGlCQUFpQixDQUFDO0FBQ2pDLFlBQVksRUFBRSxRQUFRLEVBQUUsV0FBVyxFQUFFLGFBQWEsRUFBRSxNQUFNLHlCQUF5QixDQUFDIn0=
32
+ export default function sqlite3InitModule(options?: Sqlite3InitOptions): Promise<Sqlite3Static>;
33
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxhQUFhLEVBQUUsTUFBTSx5QkFBeUIsQ0FBQztBQUk3RCxZQUFZLEVBQUUsUUFBUSxFQUFFLFdBQVcsRUFBRSxhQUFhLEVBQUUsTUFBTSx5QkFBeUIsQ0FBQztBQUVwRjs7OztHQUlHO0FBQ0gsZUFBTyxNQUFNLGdCQUFnQixLQUE0RCxDQUFDO0FBRTFGOzs7R0FHRztBQUNILE1BQU0sV0FBVyxrQkFBa0I7SUFDakMsa0dBQWtHO0lBQ2xHLFVBQVUsQ0FBQyxFQUFFLENBQUMsSUFBSSxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxLQUFLLE1BQU0sQ0FBQztJQUN0RCxvR0FBb0c7SUFDcEcsVUFBVSxDQUFDLEVBQUUsWUFBWSxDQUFDO0lBQzFCLHlHQUF5RztJQUN6RyxlQUFlLENBQUMsRUFBRSxDQUNoQixPQUFPLEVBQUUsV0FBVyxDQUFDLE9BQU8sRUFDNUIsU0FBUyxFQUFFLENBQUMsUUFBUSxFQUFFLFdBQVcsQ0FBQyxRQUFRLEVBQUUsTUFBTSxFQUFFLFdBQVcsQ0FBQyxNQUFNLEtBQUssSUFBSSxLQUM1RSxNQUFNLENBQUM7SUFDWixDQUFDLEdBQUcsRUFBRSxNQUFNLEdBQUcsT0FBTyxDQUFDO0NBQ3hCO0FBRUQ7Ozs7Ozs7OztHQVNHO0FBQ0gsTUFBTSxDQUFDLE9BQU8sVUFBVSxpQkFBaUIsQ0FBQyxPQUFPLEdBQUUsa0JBQXVCLEdBQUcsT0FBTyxDQUFDLGFBQWEsQ0FBQyxDQWNsRyJ9
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,0BAA0B,MAAM,8BAA8B,CAAC;AAUtE,QAAA,MAAM,iBAAiB,EAAE,OAAO,0BAW/B,CAAC;AAEF,eAAe,iBAAiB,CAAC;AACjC,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAI7D,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,KAA4D,CAAC;AAE1F;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,kGAAkG;IAClG,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC;IACtD,oGAAoG;IACpG,UAAU,CAAC,EAAE,YAAY,CAAC;IAC1B,yGAAyG;IACzG,eAAe,CAAC,EAAE,CAChB,OAAO,EAAE,WAAW,CAAC,OAAO,EAC5B,SAAS,EAAE,CAAC,QAAQ,EAAE,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,MAAM,KAAK,IAAI,KAC5E,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,aAAa,CAAC,CAclG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/sqlite3mc-wasm",
3
- "version": "5.2.0-nightly.20260723",
3
+ "version": "5.2.0-nightly.20260724",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -59,6 +59,7 @@
59
59
  ]
60
60
  },
61
61
  "moduleNameMapper": {
62
+ "^\\.\\./vendor/jswasm/(.*)$": "<rootDir>/../vendor/jswasm/$1",
62
63
  "^(\\.{1,2}/.*)\\.[cm]?js$": "$1"
63
64
  },
64
65
  "reporters": [
package/src/index.ts CHANGED
@@ -1,40 +1,134 @@
1
+ import type { Sqlite3Static } from '@sqlite.org/sqlite-wasm';
2
+
3
+ import vendoredInit from '../vendor/jswasm/sqlite3.mjs';
4
+
5
+ export type { Database, SAHPoolUtil, Sqlite3Static } from '@sqlite.org/sqlite-wasm';
6
+
1
7
  /**
2
- * Re-exports sqlite3mc's ES module default (sqlite3InitModule) and the TypeScript types expected by downstream
3
- * consumers. Mirrors the `@sqlite.org/sqlite-wasm` package default export sqlite3mc is a strict API-compatible
4
- * superset, so upstream types apply unchanged.
8
+ * Bundler-visible static reference to the wasm binary. Because the URL argument is a string literal, bundlers detect
9
+ * the expression, emit the wasm as an asset, and rewrite the URL, so the default `locateFile` below resolves to the
10
+ * emitted asset instead of guessing a path relative to the (relocated) output chunk at runtime.
11
+ */
12
+ export const SQLITE3_WASM_URL = new URL('../vendor/jswasm/sqlite3.wasm', import.meta.url);
13
+
14
+ /**
15
+ * Emscripten module-loader options honored by {@link sqlite3InitModule}. Any further options are passed through to the
16
+ * vendored module unchanged.
17
+ */
18
+ export interface Sqlite3InitOptions {
19
+ /** Resolves the URL from which a runtime asset (in practice always `sqlite3.wasm`) is fetched. */
20
+ locateFile?: (path: string, prefix: string) => string;
21
+ /** Pre-fetched wasm bytes. When set, the wasm is instantiated directly and never fetched by URL. */
22
+ wasmBinary?: BufferSource;
23
+ /** Custom wasm instantiation hook (standard Emscripten contract). Takes precedence over `wasmBinary`. */
24
+ instantiateWasm?: (
25
+ imports: WebAssembly.Imports,
26
+ onSuccess: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,
27
+ ) => object;
28
+ [key: string]: unknown;
29
+ }
30
+
31
+ /**
32
+ * Initializes the sqlite3mc wasm module.
33
+ *
34
+ * With no options, the wasm is fetched from {@link SQLITE3_WASM_URL}, which bundlers rewrite to their emitted asset,
35
+ * so bundled consumers work by default. Pass `locateFile`, `wasmBinary`, or `instantiateWasm` to override.
5
36
  *
6
- * BUNDLER COMPATIBILITY: SQLite3MultipleCiphers 2.3.5 stopped shipping the `-bundler-friendly` build variant, so
7
- * this entry re-exports the plain `sqlite3.mjs`. That loader always resolves `sqlite3.wasm` through its
8
- * `Module['locateFile']` hook, which computes `new URL(path, import.meta.url)` with a *dynamic* `path` invisible
9
- * to bundlers, so bundled consumers request an unhashed `sqlite3.wasm` relative to the emitted chunk and 404 at
10
- * runtime (pre-2.3.5, the bundler-friendly variant carried a statically-analyzable reference instead). To stay
11
- * bundler-friendly we wrap the init and inject `emscriptenLocateFile` — the vendored loader's supported escape
12
- * hatch (`Module['locateFile']` defers to it when present on the init-module state) — resolving the wasm via a
13
- * static `new URL('…/sqlite3.wasm', import.meta.url)` that bundlers detect, emit, and rewrite. Unbundled usage is
14
- * unaffected: the static URL resolves to the real vendored path.
37
+ * If loading the wasm fails (unreachable URL, HTTP error, corrupt bytes), the returned promise rejects with the cause.
38
+ * Exception: failures inside a caller-supplied `instantiateWasm` cannot be observed (Emscripten's hook contract has no
39
+ * error channel), so with a custom hook the promise never settles on failure.
15
40
  */
16
- import sqlite3InitModuleUnwrapped from '../vendor/jswasm/sqlite3.mjs';
17
-
18
- /** Statically analyzable wasm reference: bundlers emit the asset and rewrite this URL to its final location. */
19
- const SQLITE3_WASM_URL = new URL('../vendor/jswasm/sqlite3.wasm', import.meta.url);
20
-
21
- type SqliteInitModuleState = {
22
- emscriptenLocateFile?: (path: string, prefix: string) => string;
23
- debugModule?: (...args: unknown[]) => void;
24
- };
25
-
26
- const sqlite3InitModule: typeof sqlite3InitModuleUnwrapped = (...args) => {
27
- // `sqlite3.mjs` creates `globalThis.sqlite3InitModuleState` at import time and the inner Emscripten factory
28
- // captures it (and deletes the global) on init, binding it as `this` of `Module['locateFile']`. Mutate the live
29
- // object; recreate it if a previous init already consumed it (`debugModule` must exist — the factory calls it).
30
- const g = globalThis as { sqlite3InitModuleState?: SqliteInitModuleState };
31
- const state = (g.sqlite3InitModuleState ??= Object.assign(Object.create(null), {
32
- debugModule: () => {},
33
- }));
34
- state.emscriptenLocateFile = (path: string, prefix: string) =>
35
- path === 'sqlite3.wasm' ? SQLITE3_WASM_URL.href : new URL(path, prefix || import.meta.url).href;
36
- return sqlite3InitModuleUnwrapped(...args);
37
- };
38
-
39
- export default sqlite3InitModule;
40
- export type { Database, SAHPoolUtil, Sqlite3Static } from '@sqlite.org/sqlite-wasm';
41
+ export default function sqlite3InitModule(options: Sqlite3InitOptions = {}): Promise<Sqlite3Static> {
42
+ return new Promise((resolve, reject) => {
43
+ const instantiateWasm =
44
+ options.instantiateWasm ??
45
+ (options.wasmBinary
46
+ ? wasmBinaryInstantiator(options.wasmBinary, reject)
47
+ : urlInstantiator(options.locateFile ?? defaultLocateFile, reject));
48
+ const callOptions = { ...options, instantiateWasm };
49
+ installInitModuleState(callOptions);
50
+ // The vendored init consumes the installed state synchronously (its pre-js runs before the first await), so
51
+ // interleaved calls cannot observe each other's state. On instantiation failure the vendored promise never
52
+ // settles (the hook has no error channel), so the instantiators report failure through `reject` instead.
53
+ vendoredInit(callOptions).then(resolve, reject);
54
+ });
55
+ }
56
+
57
+ /** Builds an Emscripten `instantiateWasm` hook that instantiates the given bytes instead of fetching by URL. */
58
+ function wasmBinaryInstantiator(
59
+ wasmBinary: BufferSource,
60
+ onFailure: (error: Error) => void,
61
+ ): Required<Sqlite3InitOptions>['instantiateWasm'] {
62
+ return (imports, onSuccess) => {
63
+ void WebAssembly.instantiate(wasmBinary, imports).then(
64
+ ({ instance, module }) => onSuccess(instance, module),
65
+ error => onFailure(instantiationError('wasmBinary', error)),
66
+ );
67
+ return {};
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Builds an Emscripten `instantiateWasm` hook that fetches and instantiates the wasm from the located URL, replacing
73
+ * the vendored fallback (which reports failures nowhere). Prefers streaming compilation, falling back to
74
+ * buffer-based instantiation when streaming is unavailable or fails (e.g. a server responding without the
75
+ * `application/wasm` MIME type, which `instantiateStreaming` rejects).
76
+ */
77
+ function urlInstantiator(
78
+ locate: (path: string, prefix: string) => string,
79
+ onFailure: (error: Error) => void,
80
+ ): Required<Sqlite3InitOptions>['instantiateWasm'] {
81
+ return (imports, onSuccess) => {
82
+ const url = locate('sqlite3.wasm', '');
83
+ const streaming = WebAssembly.instantiateStreaming
84
+ ? WebAssembly.instantiateStreaming(fetch(url, { credentials: 'same-origin' }), imports).catch(() =>
85
+ fetchAndInstantiate(url, imports),
86
+ )
87
+ : fetchAndInstantiate(url, imports);
88
+ void streaming.then(
89
+ ({ instance, module }) => onSuccess(instance, module),
90
+ error => onFailure(instantiationError(url, error)),
91
+ );
92
+ return {};
93
+ };
94
+ }
95
+
96
+ /** Fetches the wasm and instantiates it from a buffer, surfacing HTTP errors that streaming instantiation obscures. */
97
+ async function fetchAndInstantiate(
98
+ url: string,
99
+ imports: WebAssembly.Imports,
100
+ ): Promise<WebAssembly.WebAssemblyInstantiatedSource> {
101
+ const response = await fetch(url, { credentials: 'same-origin' });
102
+ if (!response.ok) {
103
+ throw new Error(`HTTP ${response.status} ${response.statusText}`.trimEnd());
104
+ }
105
+ return WebAssembly.instantiate(await response.arrayBuffer(), imports);
106
+ }
107
+
108
+ function instantiationError(source: string, cause: unknown): Error {
109
+ const detail = cause instanceof Error ? cause.message : String(cause);
110
+ return new Error(`sqlite3 wasm instantiation failed (${source}): ${detail}`, { cause });
111
+ }
112
+
113
+ /**
114
+ * Installs the global state object the vendored module's pre-js binds its `Module.locateFile` and
115
+ * `Module.instantiateWasm` wrappers to.
116
+ */
117
+ function installInitModuleState(options: Sqlite3InitOptions): void {
118
+ const urlParams = globalThis.location?.href ? new URL(globalThis.location.href).searchParams : new URLSearchParams();
119
+ const debugModule = urlParams.has('sqlite3.debugModule')
120
+ ? // eslint-disable-next-line no-console -- mirrors the vendored module's own console-based debug channel
121
+ (...args: unknown[]) => console.warn('sqlite3.debugModule:', ...args)
122
+ : () => {};
123
+ (globalThis as { sqlite3InitModuleState?: object }).sqlite3InitModuleState = Object.assign(Object.create(null), {
124
+ debugModule,
125
+ wasmFilename: 'sqlite3.wasm',
126
+ emscriptenLocateFile: options.locateFile ?? defaultLocateFile,
127
+ emscriptenInstantiateWasm: options.instantiateWasm,
128
+ });
129
+ }
130
+
131
+ /** Resolves the wasm to {@link SQLITE3_WASM_URL} so bundled consumers load the bundler-emitted asset by default. */
132
+ function defaultLocateFile(path: string, prefix: string): string {
133
+ return path === 'sqlite3.wasm' ? SQLITE3_WASM_URL.href : new URL(path, prefix || import.meta.url).href;
134
+ }