|
| 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 | +} |
0 commit comments