Replaces "runtime npm dependency that gets `npm install`-ed into
dist/" with "TS wrapper that loads the native `.node` from
`dist/native/` like every other native binding in the project".
Why the change
--------------
The previous approach (better-sqlite3 declared in
packages/runtime/package.json, materialized by `npm install
--omit=dev` in dist/) worked but produced an artifact that needed
runtime npm install — a step the rest of SnowLuma's native bindings
don't need (websocket / snowluma-hook / ffmpeg are all standalone
`.node` files copied into `dist/native/` by vite-plugin-cp). The
asymmetry was friction: dev mode required `pnpm dist:install`,
build artifacts carried a `dist/node_modules/` tree the other
modules didn't need, and Docker images had to special-case the
glibc-vs-musl ABI lookup that prebuild-install runs.
The new shape:
- `@snowluma/sqlite` (packages/sqlite/) — TS wrapper. Has
`better-sqlite3` as a devDep (for the JS-layer types + the
actual JS wrapper code that vite inlines). At runtime, calls
`createRequire().require()` against
`<dist|repo>/native/better-sqlite3-v<abi>-<platform>-<arch>.node`
and passes the resolved addon to `new Database(path, {
nativeBinding })`.
- `packages/runtime/native/better-sqlite3-v<abi>-<triplet>.node`
— prebuilt binaries vendored into the repo. Two ABIs ship side-
by-side (v127 = Node 22 LTS used by CI, v137 = Node 24 used by
dev boxes) so `process.versions.modules` picks the matching one
at load time.
- `tools/fetch-sqlite-prebuilts.mjs` — fetches all 5 platforms ×
N ABIs from WiseLibs's GitHub releases. Idempotent: existing
`.node` files skip. Accepts extra ABI args:
`node tools/fetch-sqlite-prebuilts.mjs 12.10.0 v127 v137 v115`.
What was unwound
----------------
- packages/runtime/package.json — dependencies removed (runtime
artifact is now self-contained, no `npm install` step needed).
- root package.json — `dist:install` script removed (no node_modules
to install).
- .github/workflows/dev-build.yml — `Bundle runtime dependencies`
step removed.
- .github/workflows/release.yml — kept the `Bundle runtime
dependencies` step (was a no-op already, but harmless safety net
in case a future runtime dep shows up).
- packages/core/vite.config.ts — `better-sqlite3` no longer
external; vite inlines the JS wrapper (+~33 KB to bundle, ~2.84
MB → 2.87 MB total).
Naming
------
Mirrors the existing `websocket-${triplet}.node` convention (flat
dir under `runtime/native/`, dash-separated `<platform>-<arch>`).
Adds a `v<abi>` segment because better-sqlite3 is NOT N-API — one
binary per Node ABI. Naming:
better-sqlite3-v127-darwin-arm64.node Node 22 / macOS arm
better-sqlite3-v127-darwin-x64.node Node 22 / macOS intel
better-sqlite3-v127-linux-arm64.node Node 22 / Linux arm
better-sqlite3-v127-linux-x64.node Node 22 / Linux x64
better-sqlite3-v127-win32-x64.node Node 22 / Windows x64
better-sqlite3-v137-... (5) Node 24 / same 5 hosts
Total: 10 binaries × ~1.9 MB = ~19 MB committed. Aligned with the
existing native-vendoring footprint (websocket ~2 MB × 5, snowluma-
hook ~10 MB × Windows + Linux, ffmpeg ~10-30 MB × 4).
What changes for consumers
--------------------------
Source-side: nothing. `import Database, { type Database, type
Statement } from '@snowluma/sqlite'` is a drop-in for the previous
`import Database from 'better-sqlite3'`. The wrapper re-exports the
same types and the `Database` callable factory has the same
overload set.
Runtime: `node` finds the binding at
`<dist|repo>/native/better-sqlite3-v${process.versions.modules}-
${process.platform}-${process.arch}.node`. If the ABI doesn't
match a vendored binary, the wrapper throws a clear error pointing
at `tools/fetch-sqlite-prebuilts.mjs` with the missing ABI/triplet.
Bumped better-sqlite3 from 11.10.0 → 12.10.0 because v11 only had
prebuilt up to Node ABI v127 (no v137 = no Node 24). v12.10.0
ships both. Both versions are API-compat (the breaking changes
between v11 and v12 were either internal or in error-handling
paths SnowLuma doesn't exercise).
Verification
------------
- pnpm -r typecheck (12 projects): clean
- @snowluma/core test: 302/302
- @snowluma/onebot test: 250/250 (552/552 combined, unchanged from
the perf-series baseline)
- Bench numbers preserved — wrapper indirection is sub-μs:
storeMeta ~11 μs, storeEvent ~17 μs, findMeta hit ~1.1 μs (all
within noise of the post-RoadMap-#5 measurements).
- Vite build clean, bundle = 2.87 MB / 230 KB gzip
- `dist/index.mjs` no longer contains a `node:sqlite` import (it
did before — media-store hadn't migrated; now neither it nor
message-store reach into the Node builtin).
Bonus side-fix: `packages/onebot/src/media-store.ts` also moved
off `node:sqlite` (caught by the post-build bundle grep — the
file was using `DatabaseSync` + `StatementSync` from the builtin
even though it had already been written to cache its prepared
statements). Its hot paths now go through the same wrapper.
119 lines
5.6 KiB
TypeScript
119 lines
5.6 KiB
TypeScript
// @snowluma/sqlite — wraps better-sqlite3 so the native `.node` binding
|
|
// is loaded from
|
|
// `dist/native/better-sqlite3-v<abi>-<platform>-<arch>.node` instead
|
|
// of `node_modules/better-sqlite3/build/Release/`. This lets the
|
|
// production artifact ship as a single self-contained `dist/`
|
|
// directory (no `dist/node_modules/`, no `npm install --omit=dev`
|
|
// step) — the same pattern SnowLuma already uses for its
|
|
// `websocket-<platform>-<arch>.node` and `snowluma-*.{dll,node,so}`
|
|
// addons (flat dir, dash-separated triplet).
|
|
//
|
|
// How it works:
|
|
// 1. better-sqlite3's `Database` constructor accepts a `nativeBinding`
|
|
// option (string path or already-`require()`-ed object) that
|
|
// overrides the default `require('bindings')('better_sqlite3.node')`
|
|
// lookup. We forward through every other option/argument
|
|
// verbatim and inject this one.
|
|
// 2. The vendored `.node` lives at one of two locations depending
|
|
// on whether we're in dev (workspace TS source) or production
|
|
// (bundled into dist/native/):
|
|
// - Prod: `<dist>/native/better-sqlite3-v<abi>-<triplet>.node`
|
|
// - Dev: `<repo>/packages/runtime/native/better-sqlite3-v<abi>-<triplet>.node`
|
|
// We probe both paths and take whichever exists.
|
|
// 3. `<triplet>` is `<process.platform>-<process.arch>` (e.g.
|
|
// `darwin-arm64`, `linux-x64`, `linux-arm64`, `win32-x64`).
|
|
// 4. `<abi>` is `process.versions.modules` (NODE_MODULE_VERSION).
|
|
// better-sqlite3 is NOT N-API — its binding is locked to one
|
|
// Node ABI per build. Vendoring `vNNN` in the filename lets us
|
|
// ship multiple ABIs side-by-side (e.g. v127 for Node 22 LTS
|
|
// shipped to CI, v137 for Node 24 used by some dev boxes).
|
|
|
|
import { createRequire } from 'node:module';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { dirname, join, resolve } from 'node:path';
|
|
import { existsSync } from 'node:fs';
|
|
import BetterSqlite3 from 'better-sqlite3';
|
|
|
|
// Re-export the public types/classes consumers need. `Database` and
|
|
// `Statement` come straight from better-sqlite3 — we only intercept
|
|
// the constructor at call time, not the class shape.
|
|
export type { Database, Statement, RunResult, Options } from 'better-sqlite3';
|
|
|
|
function triplet(): string {
|
|
return `${process.platform}-${process.arch}`;
|
|
}
|
|
|
|
function abi(): string {
|
|
// `process.versions.modules` is the NODE_MODULE_VERSION the running
|
|
// Node binary expects — e.g. "127" for Node 22, "137" for Node 24.
|
|
// Stays in sync with whatever the host actually does at load time.
|
|
return `v${process.versions.modules}`;
|
|
}
|
|
|
|
function locateBinding(): string {
|
|
const tri = triplet();
|
|
const fileName = `better-sqlite3-${abi()}-${tri}.node`;
|
|
// Two candidate locations, tried in order:
|
|
// 1. Production: dist/native/better-sqlite3-<triplet>.node
|
|
// — `import.meta.url` resolves to dist/ at runtime (the wrapper
|
|
// is bundled into index.mjs alongside it).
|
|
// 2. Dev: <repo>/packages/runtime/native/better-sqlite3-<triplet>.node
|
|
// — `import.meta.url` resolves to packages/sqlite/src/index.ts;
|
|
// walk up to repo root + into runtime/native.
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const distCandidate = join(here, 'native', fileName);
|
|
if (existsSync(distCandidate)) return distCandidate;
|
|
|
|
// From packages/sqlite/src ⇢ go up to packages/, then into
|
|
// runtime/native. (Two `..` segments, not three — `src` → `sqlite/`
|
|
// → `packages/`, then descend into `runtime/native`.)
|
|
const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName);
|
|
if (existsSync(devCandidate)) return devCandidate;
|
|
|
|
throw new Error(
|
|
`@snowluma/sqlite: could not locate ${fileName}. ` +
|
|
`Tried:\n ${distCandidate}\n ${devCandidate}\n` +
|
|
`Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`,
|
|
);
|
|
}
|
|
|
|
// Load the native addon once at module import — keeping it module-
|
|
// scoped so the require() cost is paid exactly once per process.
|
|
let addon: unknown | null = null;
|
|
function loadAddon(): unknown {
|
|
if (addon) return addon;
|
|
const bindingPath = locateBinding();
|
|
// better-sqlite3 expects the addon to be loaded via the CJS
|
|
// require() mechanism (N-API init runs through it). createRequire
|
|
// is the ESM-safe way to do that with an absolute path.
|
|
const req = createRequire(import.meta.url);
|
|
addon = req(bindingPath);
|
|
return addon;
|
|
}
|
|
|
|
// Drop-in `Database` factory. Matches the better-sqlite3 default-
|
|
// export signature exactly: `new Database(filename[, options])` →
|
|
// `Database` instance.
|
|
//
|
|
// We can't just `class extends BetterSqlite3` because better-sqlite3's
|
|
// default export is a function that returns the instance (the `new
|
|
// Database(...)` shape works through that function's `new.target`
|
|
// check). Wrapping at the function-call boundary keeps that contract
|
|
// intact.
|
|
type BetterSqlite3Type = typeof BetterSqlite3;
|
|
type DatabaseInstance = InstanceType<BetterSqlite3Type>;
|
|
type DatabaseOptions = ConstructorParameters<BetterSqlite3Type>[1];
|
|
|
|
const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance {
|
|
const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions;
|
|
// The `as any` shrug here is unavoidable — better-sqlite3's
|
|
// overload set declares `new Database(...)` returns the class type
|
|
// but its default export is a callable that *also* returns it via
|
|
// an internal `new.target == null` branch. TS can't reconcile the
|
|
// two without `as any`.
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
return new (BetterSqlite3 as any)(filename, opts);
|
|
} as unknown as BetterSqlite3Type;
|
|
|
|
export default Database;
|