Skip to content

Commit 149b859

Browse files
committed
fix: lazy-load node:sqlite polyfill to avoid crash on library import
The node:sqlite import in node-polyfills.ts was eagerly evaluated at bundle load time, causing ERR_UNKNOWN_BUILTIN_MODULE on Node.js versions without node:sqlite support. Now the import is deferred to the NodeDatabasePolyfill constructor — only loaded when a database is actually opened, not when the library is require()d.
1 parent 0d6e642 commit 149b859

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

script/node-polyfills.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
*/
44
import { execSync, spawn as nodeSpawn } from "node:child_process";
55
import { access, readFile, writeFile } from "node:fs/promises";
6-
import { DatabaseSync } from "node:sqlite";
6+
// node:sqlite is imported lazily inside NodeDatabasePolyfill to avoid
7+
// crashing on Node.js versions without node:sqlite support when the
8+
// bundle is loaded as a library (the consumer may never use SQLite).
79

810
import picomatch from "picomatch";
911
import { compare as semverCompare } from "semver";
@@ -16,11 +18,19 @@ declare global {
1618

1719
type SqliteValue = string | number | bigint | null | Uint8Array;
1820

21+
/** Lazy-loaded node:sqlite DatabaseSync constructor. */
22+
function getNodeSqlite(): typeof import("node:sqlite").DatabaseSync {
23+
// eslint-disable-next-line @typescript-eslint/no-require-imports
24+
return require("node:sqlite").DatabaseSync;
25+
}
26+
1927
/** Wraps node:sqlite StatementSync to match bun:sqlite query() API. */
2028
class NodeStatementPolyfill {
21-
private readonly stmt: ReturnType<DatabaseSync["prepare"]>;
29+
// biome-ignore lint/suspicious/noExplicitAny: node:sqlite types loaded lazily
30+
private readonly stmt: any;
2231

23-
constructor(stmt: ReturnType<DatabaseSync["prepare"]>) {
32+
// biome-ignore lint/suspicious/noExplicitAny: node:sqlite types loaded lazily
33+
constructor(stmt: any) {
2434
this.stmt = stmt;
2535
}
2636

@@ -39,11 +49,13 @@ class NodeStatementPolyfill {
3949

4050
/** Wraps node:sqlite DatabaseSync to match bun:sqlite Database API. */
4151
class NodeDatabasePolyfill {
42-
private readonly db: DatabaseSync;
52+
// biome-ignore lint/suspicious/noExplicitAny: node:sqlite types loaded lazily
53+
private readonly db: any;
4354

4455
constructor(path: string) {
4556
// SQLite configuration (busy_timeout, foreign_keys, WAL mode) is applied
4657
// via PRAGMA statements in src/lib/db/index.ts after construction
58+
const DatabaseSync = getNodeSqlite();
4759
this.db = new DatabaseSync(path);
4860
}
4961

0 commit comments

Comments
 (0)