@nowledge/hawdb-bun 0.0.0-stage → 0.31.0

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/src/json.ts ADDED
@@ -0,0 +1,270 @@
1
+ /*
2
+ * Copyright 2026 Nowledge
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const MIN_I64 = -(1n << 63n);
18
+ const MAX_I64 = (1n << 63n) - 1n;
19
+ const MIN_SAFE_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
20
+ const MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
21
+
22
+ type ParsedJson =
23
+ | null
24
+ | boolean
25
+ | number
26
+ | bigint
27
+ | string
28
+ | ParsedJson[]
29
+ | { [key: string]: ParsedJson };
30
+
31
+ /** Parse valid JSON while preserving integers outside JavaScript's safe range. */
32
+ export function parseLosslessJson(text: string): ParsedJson {
33
+ let offset = 0;
34
+
35
+ function fail(message: string): never {
36
+ throw new SyntaxError(`${message} at JSON byte ${offset}`);
37
+ }
38
+
39
+ function skipWhitespace(): void {
40
+ while (
41
+ offset < text.length &&
42
+ (text[offset] === " " ||
43
+ text[offset] === "\n" ||
44
+ text[offset] === "\r" ||
45
+ text[offset] === "\t")
46
+ ) {
47
+ offset += 1;
48
+ }
49
+ }
50
+
51
+ function parseString(): string {
52
+ const start = offset;
53
+ offset += 1;
54
+ while (offset < text.length) {
55
+ const character = text[offset];
56
+ if (character === '"') {
57
+ offset += 1;
58
+ return JSON.parse(text.slice(start, offset)) as string;
59
+ }
60
+ if (character === "\\") {
61
+ offset += 2;
62
+ } else {
63
+ offset += 1;
64
+ }
65
+ }
66
+ return fail("unterminated JSON string");
67
+ }
68
+
69
+ function digits(): void {
70
+ const start = offset;
71
+ while (offset < text.length && text[offset] >= "0" && text[offset] <= "9") {
72
+ offset += 1;
73
+ }
74
+ if (offset === start) {
75
+ fail("expected a JSON digit");
76
+ }
77
+ }
78
+
79
+ function parseNumber(): number | bigint {
80
+ const start = offset;
81
+ if (text[offset] === "-") {
82
+ offset += 1;
83
+ }
84
+ if (text[offset] === "0") {
85
+ offset += 1;
86
+ if (text[offset] >= "0" && text[offset] <= "9") {
87
+ fail("leading zero in JSON number");
88
+ }
89
+ } else {
90
+ digits();
91
+ }
92
+ let integer = true;
93
+ if (text[offset] === ".") {
94
+ integer = false;
95
+ offset += 1;
96
+ digits();
97
+ }
98
+ if (text[offset] === "e" || text[offset] === "E") {
99
+ integer = false;
100
+ offset += 1;
101
+ if (text[offset] === "+" || text[offset] === "-") {
102
+ offset += 1;
103
+ }
104
+ digits();
105
+ }
106
+ const token = text.slice(start, offset);
107
+ if (!integer) {
108
+ return Number(token);
109
+ }
110
+ const value = BigInt(token);
111
+ return value >= MIN_SAFE_INTEGER && value <= MAX_SAFE_INTEGER ? Number(value) : value;
112
+ }
113
+
114
+ function parseArray(): ParsedJson[] {
115
+ offset += 1;
116
+ skipWhitespace();
117
+ const values: ParsedJson[] = [];
118
+ if (text[offset] === "]") {
119
+ offset += 1;
120
+ return values;
121
+ }
122
+ while (true) {
123
+ values.push(parseValue());
124
+ skipWhitespace();
125
+ if (text[offset] === "]") {
126
+ offset += 1;
127
+ return values;
128
+ }
129
+ if (text[offset] !== ",") {
130
+ fail("expected ',' or ']' in JSON array");
131
+ }
132
+ offset += 1;
133
+ skipWhitespace();
134
+ }
135
+ }
136
+
137
+ function parseObject(): { [key: string]: ParsedJson } {
138
+ offset += 1;
139
+ skipWhitespace();
140
+ const value: { [key: string]: ParsedJson } = Object.create(null) as {
141
+ [key: string]: ParsedJson;
142
+ };
143
+ if (text[offset] === "}") {
144
+ offset += 1;
145
+ return value;
146
+ }
147
+ while (true) {
148
+ if (text[offset] !== '"') {
149
+ fail("expected a JSON object key");
150
+ }
151
+ const key = parseString();
152
+ skipWhitespace();
153
+ if (text[offset] !== ":") {
154
+ fail("expected ':' after JSON object key");
155
+ }
156
+ offset += 1;
157
+ value[key] = parseValue();
158
+ skipWhitespace();
159
+ if (text[offset] === "}") {
160
+ offset += 1;
161
+ return value;
162
+ }
163
+ if (text[offset] !== ",") {
164
+ fail("expected ',' or '}' in JSON object");
165
+ }
166
+ offset += 1;
167
+ skipWhitespace();
168
+ }
169
+ }
170
+
171
+ function parseValue(): ParsedJson {
172
+ skipWhitespace();
173
+ const character = text[offset];
174
+ if (character === '"') return parseString();
175
+ if (character === "[") return parseArray();
176
+ if (character === "{") return parseObject();
177
+ if (text.startsWith("true", offset)) {
178
+ offset += 4;
179
+ return true;
180
+ }
181
+ if (text.startsWith("false", offset)) {
182
+ offset += 5;
183
+ return false;
184
+ }
185
+ if (text.startsWith("null", offset)) {
186
+ offset += 4;
187
+ return null;
188
+ }
189
+ if (character === "-" || (character >= "0" && character <= "9")) {
190
+ return parseNumber();
191
+ }
192
+ return fail("expected a JSON value");
193
+ }
194
+
195
+ const value = parseValue();
196
+ skipWhitespace();
197
+ if (offset !== text.length) {
198
+ fail("trailing JSON content");
199
+ }
200
+ return value;
201
+ }
202
+
203
+ function base64(bytes: Uint8Array): string {
204
+ let binary = "";
205
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
206
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
207
+ }
208
+ return btoa(binary);
209
+ }
210
+
211
+ /** Serialize HawDB parameter JSON without rounding bigint values. */
212
+ export function stringifyParameters(value: unknown): string {
213
+ const active = new WeakSet<object>();
214
+
215
+ function encode(item: unknown): string {
216
+ if (item === null) return "null";
217
+ if (typeof item === "boolean" || typeof item === "string") {
218
+ return JSON.stringify(item);
219
+ }
220
+ if (typeof item === "number") {
221
+ if (!Number.isFinite(item)) {
222
+ throw new TypeError("HawDB parameters require finite numbers");
223
+ }
224
+ if (Number.isInteger(item) && !Number.isSafeInteger(item)) {
225
+ throw new TypeError("unsafe integer HawDB parameters must use bigint");
226
+ }
227
+ return JSON.stringify(item);
228
+ }
229
+ if (typeof item === "bigint") {
230
+ if (item < MIN_I64 || item > MAX_I64) {
231
+ throw new RangeError("HawDB bigint parameter is outside the signed 64-bit range");
232
+ }
233
+ return item.toString();
234
+ }
235
+ if (item instanceof Uint8Array) {
236
+ return `{"$binary":${JSON.stringify(base64(item))}}`;
237
+ }
238
+ if (typeof item !== "object") {
239
+ throw new TypeError(`unsupported HawDB parameter type: ${typeof item}`);
240
+ }
241
+ if (active.has(item)) {
242
+ throw new TypeError("HawDB parameters must not contain cycles");
243
+ }
244
+ active.add(item);
245
+ try {
246
+ if (Array.isArray(item)) {
247
+ const length = item.length;
248
+ const values: string[] = [];
249
+ for (let index = 0; index < length; index += 1) {
250
+ if (!Object.hasOwn(item, index)) {
251
+ throw new TypeError("HawDB array parameters must not contain holes");
252
+ }
253
+ values.push(encode(item[index]));
254
+ }
255
+ return `[${values.join(",")}]`;
256
+ }
257
+ const prototype = Object.getPrototypeOf(item);
258
+ if (prototype !== Object.prototype && prototype !== null) {
259
+ throw new TypeError("HawDB map parameters must be plain objects");
260
+ }
261
+ return `{${Object.entries(item)
262
+ .map(([key, child]) => `${JSON.stringify(key)}:${encode(child)}`)
263
+ .join(",")}}`;
264
+ } finally {
265
+ active.delete(item);
266
+ }
267
+ }
268
+
269
+ return encode(value);
270
+ }
package/src/native.ts ADDED
@@ -0,0 +1,114 @@
1
+ /*
2
+ * Copyright 2026 Nowledge
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { CString, dlopen, type Pointer } from "bun:ffi";
18
+
19
+ export { CString };
20
+ export type NativePointer = bigint | Pointer;
21
+ export type NativeLibrary = ReturnType<typeof openNativeLibrary>;
22
+
23
+ const symbols = {
24
+ hawdb_open: {
25
+ args: ["buffer", "buffer_length", "buffer", "buffer_length", "buffer"],
26
+ returns: "ptr",
27
+ },
28
+ hawdb_open_in_memory: { args: ["buffer"], returns: "ptr" },
29
+ hawdb_close: { args: ["ptr"], returns: "void" },
30
+ hawdb_query: {
31
+ args: [
32
+ "ptr",
33
+ "buffer",
34
+ "buffer_length",
35
+ "buffer",
36
+ "buffer_length",
37
+ "buffer",
38
+ "buffer",
39
+ ],
40
+ returns: "bool",
41
+ },
42
+ hawdb_query_sql: {
43
+ args: [
44
+ "ptr",
45
+ "buffer",
46
+ "buffer_length",
47
+ "buffer",
48
+ "buffer_length",
49
+ "buffer",
50
+ "buffer",
51
+ ],
52
+ returns: "bool",
53
+ },
54
+ hawdb_export: {
55
+ args: ["ptr", "buffer", "buffer_length", "buffer", "buffer"],
56
+ returns: "bool",
57
+ },
58
+ hawdb_import: {
59
+ args: ["buffer", "buffer_length", "buffer", "buffer_length", "buffer", "buffer"],
60
+ returns: "bool",
61
+ },
62
+ hawdb_verify_dump: {
63
+ args: ["buffer", "buffer_length", "buffer", "buffer"],
64
+ returns: "bool",
65
+ },
66
+ hawdb_confirm_dump_publication: {
67
+ args: ["buffer", "buffer_length", "buffer"],
68
+ returns: "bool",
69
+ },
70
+ hawdb_format_version: { args: [], returns: "u32" },
71
+ hawdb_dump_format_version: { args: [], returns: "u32" },
72
+ hawdb_begin_transaction: { args: ["ptr", "buffer"], returns: "bool" },
73
+ hawdb_transaction_query: {
74
+ args: [
75
+ "ptr",
76
+ "buffer",
77
+ "buffer_length",
78
+ "buffer",
79
+ "buffer_length",
80
+ "buffer",
81
+ "buffer",
82
+ ],
83
+ returns: "bool",
84
+ },
85
+ hawdb_transaction_query_sql: {
86
+ args: [
87
+ "ptr",
88
+ "buffer",
89
+ "buffer_length",
90
+ "buffer",
91
+ "buffer_length",
92
+ "buffer",
93
+ "buffer",
94
+ ],
95
+ returns: "bool",
96
+ },
97
+ hawdb_commit_transaction: { args: ["ptr", "buffer", "buffer"], returns: "bool" },
98
+ hawdb_rollback_transaction: { args: ["ptr", "buffer"], returns: "bool" },
99
+ hawdb_backup: {
100
+ args: ["ptr", "buffer", "buffer_length", "buffer", "buffer"],
101
+ returns: "bool",
102
+ },
103
+ hawdb_restore: {
104
+ args: ["buffer", "buffer_length", "buffer", "buffer_length", "buffer", "buffer"],
105
+ returns: "bool",
106
+ },
107
+ hawdb_scrub: { args: ["ptr", "buffer", "buffer"], returns: "bool" },
108
+ hawdb_buffer_free: { args: ["buffer"], returns: "void" },
109
+ hawdb_version: { args: ["buffer"], returns: "void" },
110
+ } as const;
111
+
112
+ export function openNativeLibrary(path: string) {
113
+ return dlopen(path, symbols);
114
+ }
@@ -0,0 +1,295 @@
1
+ /*
2
+ * Copyright 2026 Nowledge
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
18
+ import { createRequire } from "node:module";
19
+ import { dirname, join, posix } from "node:path";
20
+
21
+ /** npm scope shared by the Bun package and its prebuilt C ABI packages. */
22
+ export const NPM_SCOPE = "@nowledge";
23
+
24
+ export type Libc = "glibc" | "musl";
25
+
26
+ /** One published prebuilt C ABI package and the hosts it serves. */
27
+ export interface PlatformPackage {
28
+ /** Suffix of `@nowledge/hawdb-ffi-<id>`. */
29
+ readonly id: string;
30
+ /** `process.platform` and the npm `os` field. */
31
+ readonly os: NodeJS.Platform;
32
+ /** `process.arch` and the npm `cpu` field. */
33
+ readonly cpu: NodeJS.Architecture;
34
+ /** npm `libc` field; Linux only. */
35
+ readonly libc?: Libc;
36
+ /** Release archive target name. */
37
+ readonly target: string;
38
+ /** Shared-library file name inside the package. */
39
+ readonly library: string;
40
+ }
41
+
42
+ // Keep this table, the release workflow matrix and docs/PREBUILT_LIBRARIES.md
43
+ // in the same order. Adding a row publishes a new npm package name, whose
44
+ // trusted publisher must be configured before its first CI publish.
45
+ export const PLATFORM_PACKAGES: readonly PlatformPackage[] = [
46
+ {
47
+ id: "darwin-arm64",
48
+ os: "darwin",
49
+ cpu: "arm64",
50
+ target: "aarch64-apple-darwin",
51
+ library: "libhawdb_ffi.dylib",
52
+ },
53
+ {
54
+ id: "darwin-x64",
55
+ os: "darwin",
56
+ cpu: "x64",
57
+ target: "x86_64-apple-darwin",
58
+ library: "libhawdb_ffi.dylib",
59
+ },
60
+ {
61
+ id: "linux-x64-gnu",
62
+ os: "linux",
63
+ cpu: "x64",
64
+ libc: "glibc",
65
+ target: "x86_64-unknown-linux-gnu",
66
+ library: "libhawdb_ffi.so",
67
+ },
68
+ {
69
+ id: "linux-arm64-gnu",
70
+ os: "linux",
71
+ cpu: "arm64",
72
+ libc: "glibc",
73
+ target: "aarch64-unknown-linux-gnu",
74
+ library: "libhawdb_ffi.so",
75
+ },
76
+ {
77
+ id: "win32-x64-msvc",
78
+ os: "win32",
79
+ cpu: "x64",
80
+ target: "x86_64-pc-windows-msvc",
81
+ library: "hawdb_ffi.dll",
82
+ },
83
+ ];
84
+
85
+ export interface Host {
86
+ readonly platform: string;
87
+ readonly arch: string;
88
+ /** Linux C library; ignored on other platforms. */
89
+ readonly libc?: Libc | null;
90
+ }
91
+
92
+ export function platformPackageName(platform: PlatformPackage): string {
93
+ return `${NPM_SCOPE}/hawdb-ffi-${platform.id}`;
94
+ }
95
+
96
+ export class UnsupportedPlatformError extends Error {
97
+ constructor(public readonly host: Host) {
98
+ const libc = host.platform === "linux" ? ` (${host.libc ?? "unknown libc"})` : "";
99
+ super(
100
+ `HawDB has no prebuilt library for ${host.platform}-${host.arch}${libc}. ` +
101
+ "Build //bindings/ffi:hawdb_ffi from source and pass its path to loadHawDB(path).",
102
+ );
103
+ this.name = "UnsupportedPlatformError";
104
+ }
105
+ }
106
+
107
+ /** Select the prebuilt package for a host, or throw UnsupportedPlatformError. */
108
+ export function selectPlatformPackage(host: Host): PlatformPackage {
109
+ const selected = PLATFORM_PACKAGES.find(
110
+ (candidate) =>
111
+ candidate.os === host.platform &&
112
+ candidate.cpu === host.arch &&
113
+ (candidate.libc === undefined || candidate.libc === host.libc),
114
+ );
115
+ if (selected === undefined) {
116
+ throw new UnsupportedPlatformError(host);
117
+ }
118
+ return selected;
119
+ }
120
+
121
+ /** Reads `length` bytes at `offset`; may return fewer at end of file. */
122
+ export type ReadAt = (offset: number, length: number) => Uint8Array;
123
+
124
+ const PT_INTERP = 3;
125
+ const MAX_PROGRAM_HEADERS = 4096;
126
+ const MAX_INTERPRETER_BYTES = 4096;
127
+
128
+ /**
129
+ * The `PT_INTERP` program interpreter of a little-endian 64-bit ELF image, or
130
+ * null when the image is not one or names no interpreter (a static binary).
131
+ */
132
+ export function elfInterpreter(read: ReadAt): string | null {
133
+ const header = read(0, 64);
134
+ if (
135
+ header.length < 64 ||
136
+ header[0] !== 0x7f ||
137
+ header[1] !== 0x45 ||
138
+ header[2] !== 0x4c ||
139
+ header[3] !== 0x46 ||
140
+ header[4] !== 2 || // ELFCLASS64
141
+ header[5] !== 1 // ELFDATA2LSB
142
+ ) {
143
+ return null;
144
+ }
145
+ const fields = new DataView(header.buffer, header.byteOffset, header.byteLength);
146
+ const tableOffset = Number(fields.getBigUint64(0x20, true));
147
+ const entrySize = fields.getUint16(0x36, true);
148
+ const entries = fields.getUint16(0x38, true);
149
+ if (entrySize < 56 || entries === 0 || entries > MAX_PROGRAM_HEADERS) {
150
+ return null;
151
+ }
152
+ const table = read(tableOffset, entrySize * entries);
153
+ if (table.length < entrySize * entries) {
154
+ return null;
155
+ }
156
+ const programs = new DataView(table.buffer, table.byteOffset, table.byteLength);
157
+ for (let entry = 0; entry < entries; entry += 1) {
158
+ const base = entry * entrySize;
159
+ if (programs.getUint32(base, true) !== PT_INTERP) {
160
+ continue;
161
+ }
162
+ const offset = Number(programs.getBigUint64(base + 8, true));
163
+ const size = Number(programs.getBigUint64(base + 32, true));
164
+ if (size === 0 || size > MAX_INTERPRETER_BYTES) {
165
+ return null;
166
+ }
167
+ const bytes = read(offset, size);
168
+ if (bytes.length < size) {
169
+ return null;
170
+ }
171
+ const end = bytes.indexOf(0);
172
+ return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));
173
+ }
174
+ return null;
175
+ }
176
+
177
+ /** Classify a program interpreter path: musl's `ld-musl-*` or glibc's `ld-linux*`. */
178
+ export function libcFromInterpreter(interpreter: string | null): Libc | null {
179
+ if (interpreter === null) {
180
+ return null;
181
+ }
182
+ const name = posix.basename(interpreter);
183
+ if (name.startsWith("ld-musl-")) {
184
+ return "musl";
185
+ }
186
+ if (name.startsWith("ld-linux")) {
187
+ return "glibc";
188
+ }
189
+ return null;
190
+ }
191
+
192
+ /**
193
+ * Detect the C library of the running process from the program interpreter
194
+ * of its own executable (`/proc/self/exe`). A musl loader installed beside
195
+ * glibc does not change which one this process uses, so loader files on disk
196
+ * are not consulted. Returns null off Linux, and on Linux when the process
197
+ * libc cannot be determined.
198
+ */
199
+ export function detectLibc(platform: string = process.platform, read?: ReadAt): Libc | null {
200
+ if (platform !== "linux") {
201
+ return null;
202
+ }
203
+ if (read !== undefined) {
204
+ return libcFromInterpreter(elfInterpreter(read));
205
+ }
206
+ let descriptor: number;
207
+ try {
208
+ descriptor = openSync("/proc/self/exe", "r");
209
+ } catch {
210
+ return null;
211
+ }
212
+ try {
213
+ return libcFromInterpreter(
214
+ elfInterpreter((offset, length) => {
215
+ const bytes = new Uint8Array(length);
216
+ return bytes.subarray(0, readSync(descriptor, bytes, 0, length, offset));
217
+ }),
218
+ );
219
+ } catch {
220
+ return null;
221
+ } finally {
222
+ closeSync(descriptor);
223
+ }
224
+ }
225
+
226
+ export function currentHost(): Host {
227
+ return { platform: process.platform, arch: process.arch, libc: detectLibc() };
228
+ }
229
+
230
+ export interface ResolveOptions {
231
+ readonly host?: Host;
232
+ /** Module resolution, defaulting to Node resolution from this package. */
233
+ readonly resolve?: (specifier: string) => string;
234
+ readonly exists?: (path: string) => boolean;
235
+ /** Reads a resolved package manifest as UTF-8. */
236
+ readonly readManifest?: (path: string) => string;
237
+ /** The release the platform package must match; defaults to this package's version. */
238
+ readonly expectedVersion?: string;
239
+ }
240
+
241
+ const requireFromHere = createRequire(import.meta.url);
242
+
243
+ function wrapperVersion(): string {
244
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
245
+ if (typeof manifest.version !== "string") {
246
+ throw new Error("@nowledge/hawdb-bun has no version in its package.json");
247
+ }
248
+ return manifest.version;
249
+ }
250
+
251
+ /**
252
+ * Locate the shared library shipped by the installed platform package that
253
+ * matches this host. Only package resolution decides the path; no environment
254
+ * variable or search path is consulted. The resolved package must be from the
255
+ * same release as this package: the exact pin in `optionalDependencies` does
256
+ * not constrain resolution, so an older copy left in the tree is refused.
257
+ */
258
+ export function resolvePrebuiltLibrary(options: ResolveOptions = {}): string {
259
+ const host = options.host ?? currentHost();
260
+ const resolve = options.resolve ?? ((specifier: string) => requireFromHere.resolve(specifier));
261
+ const exists = options.exists ?? existsSync;
262
+ const platform = selectPlatformPackage(host);
263
+ const name = platformPackageName(platform);
264
+ let manifest: string;
265
+ try {
266
+ manifest = resolve(`${name}/package.json`);
267
+ } catch {
268
+ throw new Error(
269
+ `HawDB's prebuilt library package ${name} is not installed. ` +
270
+ "Reinstall @nowledge/hawdb-bun without disabling optional dependencies, " +
271
+ "or pass an explicit library path to loadHawDB(path).",
272
+ );
273
+ }
274
+ const readManifest = options.readManifest ?? ((path: string) => readFileSync(path, "utf8"));
275
+ const expected = options.expectedVersion ?? wrapperVersion();
276
+ let installed: unknown;
277
+ try {
278
+ installed = JSON.parse(readManifest(manifest)).version;
279
+ } catch {
280
+ installed = undefined;
281
+ }
282
+ if (installed !== expected) {
283
+ const found = typeof installed === "string" ? `version ${installed}` : "an unreadable version";
284
+ throw new Error(
285
+ `HawDB's prebuilt library package ${name} is ${found}, but @nowledge/hawdb-bun is ${expected}. ` +
286
+ `Reinstall @nowledge/hawdb-bun with optional dependencies so ${name}@${expected} is installed, ` +
287
+ "or pass an explicit library path to loadHawDB(path).",
288
+ );
289
+ }
290
+ const library = join(dirname(manifest), platform.library);
291
+ if (!exists(library)) {
292
+ throw new Error(`HawDB's prebuilt library package ${name} has no ${platform.library}`);
293
+ }
294
+ return library;
295
+ }