@antfly/embedded 0.0.0 → 0.3.0-rc.1

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/dist/index.cjs ADDED
@@ -0,0 +1,2302 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AbiMismatchError: () => AbiMismatchError,
34
+ AntflyError: () => AntflyError,
35
+ BusyError: () => BusyError,
36
+ CancelledError: () => CancelledError,
37
+ Connection: () => Connection,
38
+ Database: () => Database,
39
+ ErrorCode: () => ErrorCode,
40
+ GraphDirection: () => GraphDirection,
41
+ Inference: () => Inference,
42
+ InferenceMode: () => InferenceMode,
43
+ IntentConflictError: () => IntentConflictError,
44
+ InternalError: () => InternalError,
45
+ InvalidArgumentError: () => InvalidArgumentError,
46
+ LibraryNotFoundError: () => LibraryNotFoundError,
47
+ MIN_THREAD_STACK_SIZE: () => NATIVE_STACK_SIZE,
48
+ NotFoundError: () => NotFoundError,
49
+ OpenMode: () => OpenMode,
50
+ OutcomeUnknownError: () => OutcomeUnknownError,
51
+ Profile: () => Profile,
52
+ SUPPORTED_ABI_VERSION: () => SUPPORTED_ABI_VERSION,
53
+ SqlError: () => SqlError,
54
+ StalledError: () => StalledError,
55
+ Storage: () => Storage,
56
+ THREADING_SERIALIZED: () => THREADING_SERIALIZED,
57
+ TxnNotFoundError: () => TxnNotFoundError,
58
+ TxnStatus: () => TxnStatus,
59
+ UnsupportedError: () => UnsupportedError,
60
+ UnsupportedPlatformError: () => UnsupportedPlatformError,
61
+ VersionConflictError: () => VersionConflictError,
62
+ abiVersion: () => abiVersion,
63
+ checkFile: () => checkFile,
64
+ checkFileRaw: () => checkFileRaw,
65
+ copyStableSnapshotFile: () => copyStableSnapshotFile,
66
+ copyStableSnapshotFileRaw: () => copyStableSnapshotFileRaw,
67
+ create: () => create,
68
+ createHosted: () => createHosted,
69
+ createWithOptions: () => createWithOptions,
70
+ decodeArtifactId: () => decodeArtifactId,
71
+ decodeArtifactIdRaw: () => decodeArtifactIdRaw,
72
+ embeddedPlatformPackageName: () => embeddedPlatformPackageName,
73
+ errorCodeDescription: () => errorCodeDescription,
74
+ errorCodeName: () => errorCodeName,
75
+ open: () => open2,
76
+ openHosted: () => openHosted,
77
+ openReadonly: () => openReadonly,
78
+ openStatusOnly: () => openStatusOnly,
79
+ openWithOptions: () => openWithOptions,
80
+ platformLibraryFileName: () => platformLibraryFileName,
81
+ resolveLibrary: () => resolveLibrary,
82
+ restore: () => restore,
83
+ restoreFile: () => restoreFile,
84
+ threadingMode: () => threadingMode,
85
+ validateAbi: () => validateAbi,
86
+ validateInferenceAbi: () => validateInferenceAbi
87
+ });
88
+ module.exports = __toCommonJS(index_exports);
89
+
90
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.7.0_postcss@8.5.15_supports-color@10.2.2_tsx@4.22.4_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
91
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
92
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
93
+
94
+ // src/abi.ts
95
+ var import_koffi2 = __toESM(require("koffi"), 1);
96
+
97
+ // src/native.ts
98
+ var import_koffi = __toESM(require("koffi"), 1);
99
+
100
+ // src/discovery.ts
101
+ var import_node_fs = require("fs");
102
+ var import_node_module = require("module");
103
+ var import_node_path = require("path");
104
+ var import_node_url = require("url");
105
+ var LibraryNotFoundError = class extends Error {
106
+ constructor(message) {
107
+ super(message);
108
+ this.name = "LibraryNotFoundError";
109
+ }
110
+ };
111
+ var UnsupportedPlatformError = class extends Error {
112
+ constructor(platform) {
113
+ super(`@antfly/embedded does not support platform ${platform}`);
114
+ this.name = "UnsupportedPlatformError";
115
+ }
116
+ };
117
+ function platformLibraryFileName(platform) {
118
+ switch (platform) {
119
+ case "darwin":
120
+ return "libantfly.dylib";
121
+ case "linux":
122
+ return "libantfly.so";
123
+ case "win32":
124
+ return "antfly.dll";
125
+ default:
126
+ return void 0;
127
+ }
128
+ }
129
+ function embeddedPlatformPackageName(platform, arch) {
130
+ if (platform === "darwin" && arch === "arm64") {
131
+ return "@antfly/embedded-darwin-arm64";
132
+ }
133
+ if (platform === "linux" && (arch === "arm64" || arch === "x64")) {
134
+ return `@antfly/embedded-linux-${arch}`;
135
+ }
136
+ return void 0;
137
+ }
138
+ function moduleFilename() {
139
+ return typeof __filename === "string" ? __filename : (0, import_node_url.fileURLToPath)(importMetaUrl);
140
+ }
141
+ function defaultStartDir() {
142
+ return (0, import_node_path.dirname)(moduleFilename());
143
+ }
144
+ function findUp(startDir, relative, existsSync) {
145
+ let dir = startDir;
146
+ for (let i = 0; i < 16; i++) {
147
+ const candidate = (0, import_node_path.join)(dir, relative);
148
+ if (existsSync(candidate)) {
149
+ return candidate;
150
+ }
151
+ if (existsSync((0, import_node_path.join)(dir, ".git"))) {
152
+ return void 0;
153
+ }
154
+ const parent = (0, import_node_path.dirname)(dir);
155
+ if (parent === dir) {
156
+ return void 0;
157
+ }
158
+ dir = parent;
159
+ }
160
+ return void 0;
161
+ }
162
+ function resolveLibrary(options = {}) {
163
+ const platform = options.platform ?? process.platform;
164
+ const arch = options.arch ?? process.arch;
165
+ const env = options.env ?? process.env;
166
+ const existsSync = options.existsSync ?? import_node_fs.existsSync;
167
+ const fileName = platformLibraryFileName(platform);
168
+ if (!fileName) {
169
+ throw new UnsupportedPlatformError(platform);
170
+ }
171
+ const explicitLibrary = env.ANTFLY_LIBRARY;
172
+ if (explicitLibrary) {
173
+ if (!existsSync(explicitLibrary)) {
174
+ throw new LibraryNotFoundError(`ANTFLY_LIBRARY=${explicitLibrary} does not exist`);
175
+ }
176
+ return { path: explicitLibrary, source: "ANTFLY_LIBRARY" };
177
+ }
178
+ const libDir = env.ANTFLY_LIB_DIR;
179
+ if (libDir) {
180
+ const candidate = (0, import_node_path.join)(libDir, fileName);
181
+ if (!existsSync(candidate)) {
182
+ throw new LibraryNotFoundError(`ANTFLY_LIB_DIR=${libDir} does not contain ${fileName}`);
183
+ }
184
+ return { path: candidate, source: "ANTFLY_LIB_DIR" };
185
+ }
186
+ const packageName = embeddedPlatformPackageName(platform, arch);
187
+ if (packageName) {
188
+ try {
189
+ const resolve = options.resolve ?? (0, import_node_module.createRequire)(moduleFilename()).resolve;
190
+ const packageJsonPath = resolve(`${packageName}/package.json`);
191
+ const candidate = (0, import_node_path.join)((0, import_node_path.dirname)(packageJsonPath), "lib", fileName);
192
+ if (existsSync(candidate)) {
193
+ return { path: candidate, source: "embedded-package" };
194
+ }
195
+ } catch {
196
+ }
197
+ }
198
+ const startDir = options.startDir ?? defaultStartDir();
199
+ const sourceTreeLibrary = findUp(startDir, (0, import_node_path.join)("zig", "zig-out", "lib", fileName), existsSync);
200
+ if (sourceTreeLibrary) {
201
+ return { path: sourceTreeLibrary, source: "source-tree" };
202
+ }
203
+ return { path: fileName, source: "system" };
204
+ }
205
+
206
+ // src/errors.ts
207
+ var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
208
+ ErrorCode2[ErrorCode2["OK"] = 0] = "OK";
209
+ ErrorCode2[ErrorCode2["InvalidArgument"] = 1] = "InvalidArgument";
210
+ ErrorCode2[ErrorCode2["NotFound"] = 2] = "NotFound";
211
+ ErrorCode2[ErrorCode2["VersionConflict"] = 3] = "VersionConflict";
212
+ ErrorCode2[ErrorCode2["IntentConflict"] = 4] = "IntentConflict";
213
+ ErrorCode2[ErrorCode2["TxnNotFound"] = 5] = "TxnNotFound";
214
+ ErrorCode2[ErrorCode2["Busy"] = 6] = "Busy";
215
+ ErrorCode2[ErrorCode2["OutcomeUnknown"] = 7] = "OutcomeUnknown";
216
+ ErrorCode2[ErrorCode2["Unsupported"] = 8] = "Unsupported";
217
+ ErrorCode2[ErrorCode2["Stalled"] = 9] = "Stalled";
218
+ ErrorCode2[ErrorCode2["Cancelled"] = 10] = "Cancelled";
219
+ ErrorCode2[ErrorCode2["Internal"] = 255] = "Internal";
220
+ return ErrorCode2;
221
+ })(ErrorCode || {});
222
+ var ERROR_CODE_NAMES = {
223
+ [0 /* OK */]: "ANTFLY_OK",
224
+ [1 /* InvalidArgument */]: "ANTFLY_INVALID_ARGUMENT",
225
+ [2 /* NotFound */]: "ANTFLY_NOT_FOUND",
226
+ [3 /* VersionConflict */]: "ANTFLY_VERSION_CONFLICT",
227
+ [4 /* IntentConflict */]: "ANTFLY_INTENT_CONFLICT",
228
+ [5 /* TxnNotFound */]: "ANTFLY_TXN_NOT_FOUND",
229
+ [6 /* Busy */]: "ANTFLY_BUSY",
230
+ [7 /* OutcomeUnknown */]: "ANTFLY_OUTCOME_UNKNOWN",
231
+ [8 /* Unsupported */]: "ANTFLY_UNSUPPORTED",
232
+ [9 /* Stalled */]: "ANTFLY_STALLED",
233
+ [10 /* Cancelled */]: "ANTFLY_CANCELLED",
234
+ [255 /* Internal */]: "ANTFLY_INTERNAL"
235
+ };
236
+ var ERROR_CODE_DESCRIPTIONS = {
237
+ [0 /* OK */]: "operation completed successfully",
238
+ [1 /* InvalidArgument */]: "an argument, request, path, or open mode is invalid",
239
+ [2 /* NotFound */]: "the requested database object was not found",
240
+ [3 /* VersionConflict */]: "a version predicate did not match the current document version",
241
+ [4 /* IntentConflict */]: "a transaction intent conflicts with the requested operation",
242
+ [5 /* TxnNotFound */]: "the requested transaction was not found",
243
+ [6 /* Busy */]: "the requested resource is temporarily busy or changed during streaming; stabilize it and retry",
244
+ [7 /* OutcomeUnknown */]: "the operation was published, but crash durability could not be confirmed; inspect the destination and do not retry automatically",
245
+ [8 /* Unsupported */]: "the operation requires a capability that is not supported by this platform or filesystem",
246
+ [9 /* Stalled */]: "derived work stalled or failed; inspect pending-work diagnostics and repair or reopen the database",
247
+ [10 /* Cancelled */]: "the caller cancelled the operation",
248
+ [255 /* Internal */]: "an internal error occurred"
249
+ };
250
+ function errorCodeName(code) {
251
+ return ERROR_CODE_NAMES[code] ?? "ANTFLY_UNKNOWN_ERROR";
252
+ }
253
+ function errorCodeDescription(code) {
254
+ return ERROR_CODE_DESCRIPTIONS[code] ?? "unknown Antfly error code";
255
+ }
256
+ var AntflyError = class extends Error {
257
+ code;
258
+ codeName;
259
+ /**
260
+ * Parsed JSON error body, when the failing call returned one. Currently
261
+ * only Inference calls populate this (embed/rerank/.../pull): libantfly
262
+ * always fills their antfly_buffer output with {"error": ..., "message":
263
+ * ...} on failure, even though the call also returns a non-OK error code.
264
+ */
265
+ body;
266
+ constructor(code, message) {
267
+ const codeName = errorCodeName(code);
268
+ super(message ?? `${codeName}: ${errorCodeDescription(code)}`);
269
+ this.name = "AntflyError";
270
+ this.code = code;
271
+ this.codeName = codeName;
272
+ Object.setPrototypeOf(this, new.target.prototype);
273
+ }
274
+ };
275
+ var InvalidArgumentError = class extends AntflyError {
276
+ constructor(message) {
277
+ super(1 /* InvalidArgument */, message);
278
+ this.name = "InvalidArgumentError";
279
+ Object.setPrototypeOf(this, new.target.prototype);
280
+ }
281
+ };
282
+ var NotFoundError = class extends AntflyError {
283
+ constructor(message) {
284
+ super(2 /* NotFound */, message);
285
+ this.name = "NotFoundError";
286
+ Object.setPrototypeOf(this, new.target.prototype);
287
+ }
288
+ };
289
+ var VersionConflictError = class extends AntflyError {
290
+ constructor(message) {
291
+ super(3 /* VersionConflict */, message);
292
+ this.name = "VersionConflictError";
293
+ Object.setPrototypeOf(this, new.target.prototype);
294
+ }
295
+ };
296
+ var IntentConflictError = class extends AntflyError {
297
+ constructor(message) {
298
+ super(4 /* IntentConflict */, message);
299
+ this.name = "IntentConflictError";
300
+ Object.setPrototypeOf(this, new.target.prototype);
301
+ }
302
+ };
303
+ var TxnNotFoundError = class extends AntflyError {
304
+ constructor(message) {
305
+ super(5 /* TxnNotFound */, message);
306
+ this.name = "TxnNotFoundError";
307
+ Object.setPrototypeOf(this, new.target.prototype);
308
+ }
309
+ };
310
+ var BusyError = class extends AntflyError {
311
+ constructor(message) {
312
+ super(6 /* Busy */, message);
313
+ this.name = "BusyError";
314
+ Object.setPrototypeOf(this, new.target.prototype);
315
+ }
316
+ };
317
+ var OutcomeUnknownError = class extends AntflyError {
318
+ constructor(message) {
319
+ super(7 /* OutcomeUnknown */, message);
320
+ this.name = "OutcomeUnknownError";
321
+ Object.setPrototypeOf(this, new.target.prototype);
322
+ }
323
+ };
324
+ var UnsupportedError = class extends AntflyError {
325
+ constructor(message) {
326
+ super(8 /* Unsupported */, message);
327
+ this.name = "UnsupportedError";
328
+ Object.setPrototypeOf(this, new.target.prototype);
329
+ }
330
+ };
331
+ var StalledError = class extends AntflyError {
332
+ constructor(message) {
333
+ super(9 /* Stalled */, message);
334
+ this.name = "StalledError";
335
+ Object.setPrototypeOf(this, new.target.prototype);
336
+ }
337
+ };
338
+ var CancelledError = class extends AntflyError {
339
+ constructor(message) {
340
+ super(10 /* Cancelled */, message);
341
+ this.name = "CancelledError";
342
+ Object.setPrototypeOf(this, new.target.prototype);
343
+ }
344
+ };
345
+ var InternalError = class extends AntflyError {
346
+ constructor(message) {
347
+ super(255 /* Internal */, message);
348
+ this.name = "InternalError";
349
+ Object.setPrototypeOf(this, new.target.prototype);
350
+ }
351
+ };
352
+ var ERROR_CLASSES = {
353
+ [1 /* InvalidArgument */]: InvalidArgumentError,
354
+ [2 /* NotFound */]: NotFoundError,
355
+ [3 /* VersionConflict */]: VersionConflictError,
356
+ [4 /* IntentConflict */]: IntentConflictError,
357
+ [5 /* TxnNotFound */]: TxnNotFoundError,
358
+ [6 /* Busy */]: BusyError,
359
+ [7 /* OutcomeUnknown */]: OutcomeUnknownError,
360
+ [8 /* Unsupported */]: UnsupportedError,
361
+ [9 /* Stalled */]: StalledError,
362
+ [10 /* Cancelled */]: CancelledError,
363
+ [255 /* Internal */]: InternalError
364
+ };
365
+ function errorFromCode(code, message) {
366
+ const Ctor = ERROR_CLASSES[code];
367
+ if (Ctor) {
368
+ return new Ctor(message);
369
+ }
370
+ return new AntflyError(code, message);
371
+ }
372
+ function checkCode(code) {
373
+ if (code !== 0 /* OK */) {
374
+ throw errorFromCode(code);
375
+ }
376
+ }
377
+
378
+ // src/types.ts
379
+ var OpenMode = /* @__PURE__ */ ((OpenMode2) => {
380
+ OpenMode2[OpenMode2["Writer"] = 0] = "Writer";
381
+ OpenMode2[OpenMode2["Readonly"] = 1] = "Readonly";
382
+ OpenMode2[OpenMode2["StatusOnly"] = 2] = "StatusOnly";
383
+ return OpenMode2;
384
+ })(OpenMode || {});
385
+ var Storage = /* @__PURE__ */ ((Storage2) => {
386
+ Storage2[Storage2["Lite"] = 0] = "Lite";
387
+ Storage2[Storage2["Directory"] = 1] = "Directory";
388
+ return Storage2;
389
+ })(Storage || {});
390
+ var Profile = /* @__PURE__ */ ((Profile2) => {
391
+ Profile2[Profile2["Native"] = 0] = "Native";
392
+ Profile2[Profile2["Hosted"] = 1] = "Hosted";
393
+ return Profile2;
394
+ })(Profile || {});
395
+ var GraphDirection = /* @__PURE__ */ ((GraphDirection2) => {
396
+ GraphDirection2[GraphDirection2["Out"] = 0] = "Out";
397
+ GraphDirection2[GraphDirection2["In"] = 1] = "In";
398
+ GraphDirection2[GraphDirection2["Both"] = 2] = "Both";
399
+ return GraphDirection2;
400
+ })(GraphDirection || {});
401
+ var TxnStatus = /* @__PURE__ */ ((TxnStatus2) => {
402
+ TxnStatus2[TxnStatus2["Pending"] = 0] = "Pending";
403
+ TxnStatus2[TxnStatus2["Committed"] = 1] = "Committed";
404
+ TxnStatus2[TxnStatus2["Aborted"] = 2] = "Aborted";
405
+ return TxnStatus2;
406
+ })(TxnStatus || {});
407
+ var InferenceMode = {
408
+ CallerSuppliedOrDisabled: "caller_supplied_or_disabled",
409
+ CallerSuppliedArtifacts: "caller_supplied_artifacts",
410
+ RemoteProvider: "remote_provider",
411
+ LocalEmbedded: "local_embedded",
412
+ ManualMaintenance: "manual_maintenance",
413
+ DisabledDeferred: "disabled_deferred"
414
+ };
415
+ var THREADING_SERIALIZED = 1;
416
+ var SUPPORTED_ABI_VERSION = 3;
417
+
418
+ // src/native.ts
419
+ var ANTFLY_STORAGE_KIND_DIRECTORY = 0;
420
+ var ANTFLY_STORAGE_KIND_LITE = 1;
421
+ function storageKind(storage) {
422
+ switch (storage ?? 0 /* Lite */) {
423
+ case 0 /* Lite */:
424
+ return ANTFLY_STORAGE_KIND_LITE;
425
+ case 1 /* Directory */:
426
+ return ANTFLY_STORAGE_KIND_DIRECTORY;
427
+ default:
428
+ throw new InvalidArgumentError(`invalid Storage value: ${storage}`);
429
+ }
430
+ }
431
+ var AntflySlice = import_koffi.default.struct("antfly_slice", {
432
+ ptr: "const uint8_t *",
433
+ len: "size_t"
434
+ });
435
+ var AntflyBuffer = import_koffi.default.struct("antfly_buffer", {
436
+ ptr: "uint8_t *",
437
+ len: "size_t"
438
+ });
439
+ var AntflyWriteIntent = import_koffi.default.struct("antfly_write_intent", {
440
+ key: AntflySlice,
441
+ value: AntflySlice,
442
+ is_delete: "bool"
443
+ });
444
+ var AntflyVersionPredicate = import_koffi.default.struct("antfly_version_predicate", {
445
+ key: AntflySlice,
446
+ expected_version: "uint64_t"
447
+ });
448
+ var AntflyDbOpaque = import_koffi.default.opaque("antfly_db");
449
+ var PAntflyDb = import_koffi.default.pointer(AntflyDbOpaque);
450
+ var PAntflyDbOut = import_koffi.default.out(import_koffi.default.pointer(AntflyDbOpaque, 2));
451
+ var AntflyOpenOptions = import_koffi.default.struct("antfly_open_options", {
452
+ abi_size: "uint32_t",
453
+ storage_kind: "uint32_t",
454
+ open_mode: "uint32_t",
455
+ profile: "uint32_t",
456
+ flags: "uint32_t",
457
+ reserved0: "uint32_t",
458
+ map_size: "uint64_t",
459
+ ttl_cleanup_enabled: "bool",
460
+ ttl_cleanup_lease_owned: "bool",
461
+ ttl_cleanup_batch_size: "uint32_t",
462
+ ttl_cleanup_owner_id: AntflySlice,
463
+ ttl_cleanup_lease_ttl_ms: "uint64_t",
464
+ ttl_cleanup_interval_ms: "uint64_t",
465
+ ttl_cleanup_grace_period_ns: "uint64_t",
466
+ inference_host_budget_mb: "uint32_t",
467
+ inference_backend_budget_mb: "uint32_t",
468
+ inference_process_memory_budget_mb: "uint32_t",
469
+ inference_combined_budget_mb: "uint32_t",
470
+ inference_kv_budget_mb: "uint32_t",
471
+ inference_scratch_budget_mb: "uint32_t",
472
+ busy_timeout_ms: "uint64_t",
473
+ reserved: import_koffi.default.array("uint64_t", 8)
474
+ });
475
+ var PAntflyOpenOptions = import_koffi.default.pointer(AntflyOpenOptions);
476
+ var PAntflyOpenOptionsOut = import_koffi.default.out(PAntflyOpenOptions);
477
+ var PAntflyBufferOut = import_koffi.default.out(import_koffi.default.pointer(AntflyBuffer));
478
+ var PAntflyWriteIntentArray = import_koffi.default.pointer(AntflyWriteIntent);
479
+ var PAntflyVersionPredicateArray = import_koffi.default.pointer(AntflyVersionPredicate);
480
+ var PAntflySliceArray = import_koffi.default.pointer(AntflySlice);
481
+ var PUint8Out = import_koffi.default.out(import_koffi.default.pointer("uint8_t"));
482
+ var PUint64Out = import_koffi.default.out(import_koffi.default.pointer("uint64_t"));
483
+ var PBoolOut = import_koffi.default.out(import_koffi.default.pointer("bool"));
484
+ var AntflyInferenceOpaque = import_koffi.default.opaque("antfly_inference");
485
+ var PAntflyInference = import_koffi.default.pointer(AntflyInferenceOpaque);
486
+ var PAntflyInferenceOut = import_koffi.default.out(import_koffi.default.pointer(AntflyInferenceOpaque, 2));
487
+ var AntflyInferenceOptions = import_koffi.default.struct("antfly_inference_options", {
488
+ abi_size: "uint32_t",
489
+ flags: "uint32_t",
490
+ models_dir: AntflySlice,
491
+ host_budget_mb: "uint32_t",
492
+ backend_budget_mb: "uint32_t",
493
+ process_memory_budget_mb: "uint32_t",
494
+ combined_budget_mb: "uint32_t",
495
+ kv_budget_mb: "uint32_t",
496
+ scratch_budget_mb: "uint32_t",
497
+ call_timeout_ms: "uint64_t",
498
+ reserved: import_koffi.default.array("uint64_t", 8)
499
+ });
500
+ var PAntflyInferenceOptions = import_koffi.default.pointer(AntflyInferenceOptions);
501
+ var PAntflyInferenceOptionsOut = import_koffi.default.out(PAntflyInferenceOptions);
502
+ var AntflyInferencePullProgress = import_koffi.default.struct("antfly_inference_pull_progress", {
503
+ abi_size: "uint32_t",
504
+ reserved0: "uint32_t",
505
+ model: AntflySlice,
506
+ file: AntflySlice,
507
+ bytes_downloaded: "uint64_t",
508
+ total_bytes: "uint64_t",
509
+ files_done: "uint64_t",
510
+ files_total: "uint64_t",
511
+ cached: "bool"
512
+ });
513
+ var AntflyInferencePullProgressFnProto = import_koffi.default.proto(
514
+ "antfly_inference_pull_progress_fn",
515
+ "bool",
516
+ ["void *", import_koffi.default.pointer(AntflyInferencePullProgress)]
517
+ );
518
+ var PAntflyInferencePullProgressFn = import_koffi.default.pointer(AntflyInferencePullProgressFnProto);
519
+ var AntflyInferenceStreamFnProto = import_koffi.default.proto("antfly_inference_stream_fn", "bool", [
520
+ "void *",
521
+ AntflySlice
522
+ ]);
523
+ var PAntflyInferenceStreamFn = import_koffi.default.pointer(AntflyInferenceStreamFnProto);
524
+ var cached;
525
+ var cachedError;
526
+ function loadNative() {
527
+ if (cached) {
528
+ return cached;
529
+ }
530
+ if (cachedError) {
531
+ throw cachedError;
532
+ }
533
+ try {
534
+ cached = buildNative();
535
+ return cached;
536
+ } catch (err) {
537
+ cachedError = err;
538
+ throw err;
539
+ }
540
+ }
541
+ var NATIVE_STACK_SIZE = 8 * 1024 * 1024;
542
+ function configureKoffiStacks() {
543
+ const current = import_koffi.default.config();
544
+ if ((current.sync_stack_size ?? 0) >= NATIVE_STACK_SIZE && (current.async_stack_size ?? 0) >= NATIVE_STACK_SIZE) {
545
+ return;
546
+ }
547
+ import_koffi.default.config({
548
+ ...current,
549
+ sync_stack_size: Math.max(current.sync_stack_size ?? 0, NATIVE_STACK_SIZE),
550
+ async_stack_size: Math.max(current.async_stack_size ?? 0, NATIVE_STACK_SIZE)
551
+ });
552
+ }
553
+ function buildNative() {
554
+ const resolved = resolveLibrary();
555
+ configureKoffiStacks();
556
+ const handle = import_koffi.default.load(resolved.path);
557
+ const f = handle.func.bind(handle);
558
+ return {
559
+ handle,
560
+ resolved,
561
+ abiVersion: f("antfly_abi_version", "uint32_t", []),
562
+ threadingMode: f("antfly_threading_mode", "uint32_t", []),
563
+ openOptionsSize: f("antfly_open_options_size", "uint32_t", []),
564
+ errorCodeName: f("antfly_error_code_name", "str", ["uint32_t"]),
565
+ errorCodeDescription: f("antfly_error_code_description", "str", ["uint32_t"]),
566
+ openOptionsInit: f("antfly_open_options_init", "uint32_t", [PAntflyOpenOptionsOut]),
567
+ dbOpenWithOptions: f("antfly_db_open_with_options", "uint32_t", [
568
+ "str",
569
+ PAntflyOpenOptions,
570
+ PAntflyDbOut
571
+ ]),
572
+ dbCreateWithOptions: f("antfly_db_create_with_options", "uint32_t", [
573
+ "str",
574
+ PAntflyOpenOptions,
575
+ PAntflyDbOut
576
+ ]),
577
+ liteOpenHosted: f("antfly_lite_open_hosted", "uint32_t", ["str", PAntflyDbOut]),
578
+ liteCreateHosted: f("antfly_lite_create_hosted", "uint32_t", ["str", PAntflyDbOut]),
579
+ dbClose: f("antfly_db_close", "void", [PAntflyDb]),
580
+ bufferFree: f("antfly_buffer_free", "void", [import_koffi.default.pointer(AntflyBuffer)]),
581
+ dbSqlJson: f("antfly_db_sql_json", "uint32_t", [PAntflyDb, AntflySlice, PAntflyBufferOut]),
582
+ dbOpenTable: f("antfly_db_open_table", "uint32_t", [PAntflyDb, AntflySlice, PAntflyDbOut]),
583
+ dbCreateTableJson: f("antfly_db_create_table_json", "uint32_t", [
584
+ PAntflyDb,
585
+ AntflySlice,
586
+ AntflySlice
587
+ ]),
588
+ dbDropTable: f("antfly_db_drop_table", "uint32_t", [PAntflyDb, AntflySlice]),
589
+ dbListTablesJson: f("antfly_db_list_tables_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
590
+ dbSqlSessionOpen: f("antfly_db_sql_session_open", "uint32_t", [
591
+ PAntflyDb,
592
+ import_koffi.default.out(import_koffi.default.pointer("uint64_t"))
593
+ ]),
594
+ dbSqlSessionClose: f("antfly_db_sql_session_close", "uint32_t", [PAntflyDb, "uint64_t"]),
595
+ dbSqlOpenCursorJson: f("antfly_db_sql_open_cursor_json", "uint32_t", [
596
+ PAntflyDb,
597
+ AntflySlice,
598
+ import_koffi.default.out(import_koffi.default.pointer("uint64_t")),
599
+ PAntflyBufferOut
600
+ ]),
601
+ dbSqlFetchCursorJson: f("antfly_db_sql_fetch_cursor_json", "uint32_t", [
602
+ PAntflyDb,
603
+ "uint64_t",
604
+ "uint32_t",
605
+ PAntflyBufferOut
606
+ ]),
607
+ dbSqlCloseCursor: f("antfly_db_sql_close_cursor", "uint32_t", [PAntflyDb, "uint64_t"]),
608
+ dbStatusJson: f("antfly_db_status_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
609
+ dbCapabilitiesJson: f("antfly_db_capabilities_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
610
+ dbBackup: f("antfly_db_backup", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
611
+ dbImportBackup: f("antfly_db_import_backup", "uint32_t", [PAntflyDb, AntflySlice]),
612
+ restoreBackupJson: f("antfly_restore_backup_json", "uint32_t", [
613
+ "str",
614
+ PAntflyOpenOptions,
615
+ AntflySlice,
616
+ "bool",
617
+ PAntflyBufferOut
618
+ ]),
619
+ restoreBackupFileJson: f("antfly_restore_backup_file_json", "uint32_t", [
620
+ "str",
621
+ PAntflyOpenOptions,
622
+ "str",
623
+ "bool",
624
+ PAntflyBufferOut
625
+ ]),
626
+ liteCheckJson: f("antfly_lite_check_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
627
+ liteCheckFileJson: f("antfly_lite_check_file_json", "uint32_t", ["str", PAntflyBufferOut]),
628
+ liteCopyStableSnapshotJson: f("antfly_lite_copy_stable_snapshot_json", "uint32_t", [
629
+ PAntflyDb,
630
+ "str",
631
+ "bool",
632
+ PAntflyBufferOut
633
+ ]),
634
+ liteCopyStableSnapshotFileJson: f("antfly_lite_copy_stable_snapshot_file_json", "uint32_t", [
635
+ "str",
636
+ "str",
637
+ "bool",
638
+ PAntflyBufferOut
639
+ ]),
640
+ liteCompactJson: f("antfly_lite_compact_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
641
+ liteVacuumJson: f("antfly_lite_vacuum_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
642
+ dbRunUntilIdle: f("antfly_db_run_until_idle", "uint32_t", [PAntflyDb]),
643
+ dbRunUntilIdleJson: f("antfly_db_run_until_idle_json", "uint32_t", [
644
+ PAntflyDb,
645
+ PAntflyBufferOut
646
+ ]),
647
+ dbReplayGeneratedEnrichmentsJson: f("antfly_db_replay_generated_enrichments_json", "uint32_t", [
648
+ PAntflyDb,
649
+ PAntflyBufferOut
650
+ ]),
651
+ dbPendingWorkStatsJson: f("antfly_db_pending_work_stats_json", "uint32_t", [
652
+ PAntflyDb,
653
+ PAntflyBufferOut
654
+ ]),
655
+ dbBatch: f("antfly_db_batch", "uint32_t", [
656
+ PAntflyDb,
657
+ PAntflyWriteIntentArray,
658
+ "size_t",
659
+ PAntflyVersionPredicateArray,
660
+ "size_t",
661
+ "uint64_t",
662
+ "uint8_t"
663
+ ]),
664
+ dbBatchJson: f("antfly_db_batch_json", "uint32_t", [PAntflyDb, AntflySlice, PAntflyBufferOut]),
665
+ dbBeginTransactionWithId: f("antfly_db_begin_transaction_with_id", "uint32_t", [
666
+ PAntflyDb,
667
+ "const uint8_t *",
668
+ "uint64_t",
669
+ PAntflySliceArray,
670
+ "size_t"
671
+ ]),
672
+ dbWriteTransaction: f("antfly_db_write_transaction", "uint32_t", [
673
+ PAntflyDb,
674
+ "const uint8_t *",
675
+ PAntflyWriteIntentArray,
676
+ "size_t",
677
+ PAntflyVersionPredicateArray,
678
+ "size_t"
679
+ ]),
680
+ dbResolveIntents: f("antfly_db_resolve_intents", "uint32_t", [
681
+ PAntflyDb,
682
+ "const uint8_t *",
683
+ "uint8_t",
684
+ "uint64_t"
685
+ ]),
686
+ dbGetTransactionStatus: f("antfly_db_get_transaction_status", "uint32_t", [
687
+ PAntflyDb,
688
+ "const uint8_t *",
689
+ PUint8Out
690
+ ]),
691
+ dbGetCommitVersion: f("antfly_db_get_commit_version", "uint32_t", [
692
+ PAntflyDb,
693
+ "const uint8_t *",
694
+ PUint64Out
695
+ ]),
696
+ dbLookupJson: f("antfly_db_lookup_json", "uint32_t", [
697
+ PAntflyDb,
698
+ AntflySlice,
699
+ PAntflyBufferOut
700
+ ]),
701
+ dbGetRaw: f("antfly_db_get_raw", "uint32_t", [PAntflyDb, AntflySlice, PAntflyBufferOut]),
702
+ dbGetSchemaJson: f("antfly_db_get_schema_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
703
+ dbSetSchemaJson: f("antfly_db_set_schema_json", "uint32_t", [PAntflyDb, AntflySlice]),
704
+ dbListIndexesJson: f("antfly_db_list_indexes_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
705
+ dbAddIndexJson: f("antfly_db_add_index_json", "uint32_t", [PAntflyDb, AntflySlice]),
706
+ dbDeleteIndex: f("antfly_db_delete_index", "uint32_t", [PAntflyDb, AntflySlice, PBoolOut]),
707
+ dbListEnrichmentsJson: f("antfly_db_list_enrichments_json", "uint32_t", [
708
+ PAntflyDb,
709
+ PAntflyBufferOut
710
+ ]),
711
+ dbAddEnrichmentJson: f("antfly_db_add_enrichment_json", "uint32_t", [PAntflyDb, AntflySlice]),
712
+ dbDeleteEnrichment: f("antfly_db_delete_enrichment", "uint32_t", [
713
+ PAntflyDb,
714
+ AntflySlice,
715
+ AntflySlice,
716
+ PBoolOut
717
+ ]),
718
+ dbScanJson: f("antfly_db_scan_json", "uint32_t", [PAntflyDb, AntflySlice, PAntflyBufferOut]),
719
+ dbStatsJson: f("antfly_db_stats_json", "uint32_t", [PAntflyDb, PAntflyBufferOut]),
720
+ dbSearchJson: f("antfly_db_search_json", "uint32_t", [
721
+ PAntflyDb,
722
+ AntflySlice,
723
+ PAntflyBufferOut
724
+ ]),
725
+ dbSearchDenseWire: f("antfly_db_search_dense_wire", "uint32_t", [
726
+ PAntflyDb,
727
+ AntflySlice,
728
+ PAntflyBufferOut
729
+ ]),
730
+ dbSearchTextMatchWire: f("antfly_db_search_text_match_wire", "uint32_t", [
731
+ PAntflyDb,
732
+ AntflySlice,
733
+ PAntflyBufferOut
734
+ ]),
735
+ dbSearchTextTermWire: f("antfly_db_search_text_term_wire", "uint32_t", [
736
+ PAntflyDb,
737
+ AntflySlice,
738
+ PAntflyBufferOut
739
+ ]),
740
+ dbSearchTextMatchPhraseWire: f("antfly_db_search_text_match_phrase_wire", "uint32_t", [
741
+ PAntflyDb,
742
+ AntflySlice,
743
+ PAntflyBufferOut
744
+ ]),
745
+ dbAggregateHitsJson: f("antfly_db_aggregate_hits_json", "uint32_t", [
746
+ PAntflyDb,
747
+ AntflySlice,
748
+ PAntflyBufferOut
749
+ ]),
750
+ dbLookupArtifactJson: f("antfly_db_lookup_artifact_json", "uint32_t", [
751
+ PAntflyDb,
752
+ AntflySlice,
753
+ PAntflyBufferOut
754
+ ]),
755
+ decodeArtifactIdJson: f("antfly_decode_artifact_id_json", "uint32_t", [
756
+ AntflySlice,
757
+ PAntflyBufferOut
758
+ ]),
759
+ dbExtractEnrichmentsJson: f("antfly_db_extract_enrichments_json", "uint32_t", [
760
+ PAntflyDb,
761
+ AntflySlice,
762
+ PAntflyBufferOut
763
+ ]),
764
+ dbComputeEnrichmentsJson: f("antfly_db_compute_enrichments_json", "uint32_t", [
765
+ PAntflyDb,
766
+ AntflySlice,
767
+ PAntflyBufferOut
768
+ ]),
769
+ dbGetEdgesJson: f("antfly_db_get_edges_json", "uint32_t", [
770
+ PAntflyDb,
771
+ AntflySlice,
772
+ AntflySlice,
773
+ AntflySlice,
774
+ "uint8_t",
775
+ PAntflyBufferOut
776
+ ]),
777
+ dbTraverseEdgesJson: f("antfly_db_traverse_edges_json", "uint32_t", [
778
+ PAntflyDb,
779
+ AntflySlice,
780
+ PAntflyBufferOut
781
+ ]),
782
+ dbExecuteGraphQueriesJson: f("antfly_db_execute_graph_queries_json", "uint32_t", [
783
+ PAntflyDb,
784
+ AntflySlice,
785
+ PAntflyBufferOut
786
+ ]),
787
+ dbGetNeighborsJson: f("antfly_db_get_neighbors_json", "uint32_t", [
788
+ PAntflyDb,
789
+ AntflySlice,
790
+ AntflySlice,
791
+ AntflySlice,
792
+ "uint8_t",
793
+ PAntflyBufferOut
794
+ ]),
795
+ dbFindShortestPathJson: f("antfly_db_find_shortest_path_json", "uint32_t", [
796
+ PAntflyDb,
797
+ AntflySlice,
798
+ PAntflyBufferOut
799
+ ]),
800
+ dbFindKShortestPathsJson: f("antfly_db_find_k_shortest_paths_json", "uint32_t", [
801
+ PAntflyDb,
802
+ AntflySlice,
803
+ PAntflyBufferOut
804
+ ]),
805
+ dbMatchPatternJson: f("antfly_db_match_pattern_json", "uint32_t", [
806
+ PAntflyDb,
807
+ AntflySlice,
808
+ PAntflyBufferOut
809
+ ]),
810
+ // --- Embedded inference (antfly_inference_*) ---
811
+ inferenceOptionsSize: f("antfly_inference_options_size", "uint32_t", []),
812
+ inferenceOptionsInit: f("antfly_inference_options_init", "uint32_t", [
813
+ PAntflyInferenceOptionsOut
814
+ ]),
815
+ inferenceOpen: f("antfly_inference_open", "uint32_t", [
816
+ PAntflyInferenceOptions,
817
+ PAntflyInferenceOut
818
+ ]),
819
+ inferenceClose: f("antfly_inference_close", "void", [PAntflyInference]),
820
+ inferenceEmbedJson: f("antfly_inference_embed_json", "uint32_t", [
821
+ PAntflyInference,
822
+ AntflySlice,
823
+ PAntflyBufferOut
824
+ ]),
825
+ inferenceRerankJson: f("antfly_inference_rerank_json", "uint32_t", [
826
+ PAntflyInference,
827
+ AntflySlice,
828
+ PAntflyBufferOut
829
+ ]),
830
+ inferenceChunkJson: f("antfly_inference_chunk_json", "uint32_t", [
831
+ PAntflyInference,
832
+ AntflySlice,
833
+ PAntflyBufferOut
834
+ ]),
835
+ inferenceGenerateJson: f("antfly_inference_generate_json", "uint32_t", [
836
+ PAntflyInference,
837
+ AntflySlice,
838
+ PAntflyBufferOut
839
+ ]),
840
+ inferenceGenerateStreamJson: f("antfly_inference_generate_stream_json", "uint32_t", [
841
+ PAntflyInference,
842
+ AntflySlice,
843
+ PAntflyInferenceStreamFn,
844
+ "void *",
845
+ PAntflyBufferOut
846
+ ]),
847
+ inferenceGenerateBatchJson: f("antfly_inference_generate_batch_json", "uint32_t", [
848
+ PAntflyInference,
849
+ AntflySlice,
850
+ PAntflyBufferOut
851
+ ]),
852
+ inferenceRewriteJson: f("antfly_inference_rewrite_json", "uint32_t", [
853
+ PAntflyInference,
854
+ AntflySlice,
855
+ PAntflyBufferOut
856
+ ]),
857
+ inferenceDecideJson: f("antfly_inference_decide_json", "uint32_t", [
858
+ PAntflyInference,
859
+ AntflySlice,
860
+ PAntflyBufferOut
861
+ ]),
862
+ inferenceExtractJson: f("antfly_inference_extract_json", "uint32_t", [
863
+ PAntflyInference,
864
+ AntflySlice,
865
+ PAntflyBufferOut
866
+ ]),
867
+ inferenceReadJson: f("antfly_inference_read_json", "uint32_t", [
868
+ PAntflyInference,
869
+ AntflySlice,
870
+ PAntflyBufferOut
871
+ ]),
872
+ inferenceTranscribeJson: f("antfly_inference_transcribe_json", "uint32_t", [
873
+ PAntflyInference,
874
+ AntflySlice,
875
+ PAntflyBufferOut
876
+ ]),
877
+ inferenceListModelsJson: f("antfly_inference_list_models_json", "uint32_t", [
878
+ PAntflyInference,
879
+ PAntflyBufferOut
880
+ ]),
881
+ inferencePullJson: f("antfly_inference_pull_json", "uint32_t", [
882
+ PAntflyInference,
883
+ AntflySlice,
884
+ PAntflyInferencePullProgressFn,
885
+ "void *",
886
+ PAntflyBufferOut
887
+ ])
888
+ };
889
+ }
890
+
891
+ // src/abi.ts
892
+ var AbiMismatchError = class extends Error {
893
+ constructor(message) {
894
+ super(message);
895
+ this.name = "AbiMismatchError";
896
+ }
897
+ };
898
+ function abiVersion() {
899
+ return loadNative().abiVersion();
900
+ }
901
+ function threadingMode() {
902
+ return loadNative().threadingMode();
903
+ }
904
+ function validateAbi() {
905
+ const native = loadNative();
906
+ const gotVersion = native.abiVersion();
907
+ if (gotVersion !== SUPPORTED_ABI_VERSION) {
908
+ throw new AbiMismatchError(
909
+ `lite: unsupported C ABI version ${gotVersion}, want ${SUPPORTED_ABI_VERSION}`
910
+ );
911
+ }
912
+ const gotSize = native.openOptionsSize();
913
+ const wantSize = import_koffi2.default.sizeof(AntflyOpenOptions);
914
+ if (gotSize !== wantSize) {
915
+ throw new AbiMismatchError(
916
+ `lite: C ABI open options size ${gotSize}, compiled header size ${wantSize}`
917
+ );
918
+ }
919
+ }
920
+ function validateInferenceAbi() {
921
+ const native = loadNative();
922
+ const gotSize = native.inferenceOptionsSize();
923
+ const wantSize = import_koffi2.default.sizeof(AntflyInferenceOptions);
924
+ if (gotSize !== wantSize) {
925
+ throw new AbiMismatchError(
926
+ `lite: C ABI inference options size ${gotSize}, compiled header size ${wantSize}`
927
+ );
928
+ }
929
+ }
930
+
931
+ // src/database.ts
932
+ var fsp = __toESM(require("fs/promises"), 1);
933
+ var import_node_path2 = require("path");
934
+
935
+ // src/marshal.ts
936
+ var import_node_util = require("util");
937
+ var import_koffi3 = __toESM(require("koffi"), 1);
938
+ function toRawBytes(input) {
939
+ if (Buffer.isBuffer(input)) {
940
+ return input;
941
+ }
942
+ if (input instanceof Uint8Array) {
943
+ return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
944
+ }
945
+ throw new InvalidArgumentError(`expected Buffer or Uint8Array, got ${typeof input}`);
946
+ }
947
+ function toJsonBytes(input) {
948
+ if (typeof input === "string") {
949
+ return Buffer.from(input, "utf8");
950
+ }
951
+ if (Buffer.isBuffer(input) || input instanceof Uint8Array) {
952
+ return toRawBytes(input);
953
+ }
954
+ return Buffer.from(JSON.stringify(input), "utf8");
955
+ }
956
+ function sliceOf(bytes) {
957
+ return bytes.length === 0 ? { ptr: null, len: 0 } : { ptr: bytes, len: bytes.length };
958
+ }
959
+ function jsonSlice(input) {
960
+ return sliceOf(toJsonBytes(input));
961
+ }
962
+ function stringSlice(input) {
963
+ return sliceOf(Buffer.from(input, "utf8"));
964
+ }
965
+ function parseJson(buf) {
966
+ if (buf.length === 0) {
967
+ return null;
968
+ }
969
+ return JSON.parse(buf.toString("utf8"));
970
+ }
971
+ function newBufferOut() {
972
+ return { ptr: null, len: 0 };
973
+ }
974
+ function takeBuffer(native, out) {
975
+ try {
976
+ const len = Number(out.len ?? 0);
977
+ if (!out.ptr || len === 0) {
978
+ return Buffer.alloc(0);
979
+ }
980
+ const view = import_koffi3.default.decode(out.ptr, "uint8_t", len);
981
+ return Buffer.from(view);
982
+ } finally {
983
+ native.bufferFree(out);
984
+ }
985
+ }
986
+ function callAsync(fn, ...args) {
987
+ const bound = (0, import_node_util.promisify)(fn.async.bind(fn));
988
+ return withNativeSlot(() => bound(...args));
989
+ }
990
+ var nativeSlots = Math.max(1, Number.parseInt(process.env.UV_THREADPOOL_SIZE ?? "", 10) || 4);
991
+ var nativeActive = 0;
992
+ var nativeWaiters = [];
993
+ async function withNativeSlot(run) {
994
+ if (nativeActive >= nativeSlots) {
995
+ await new Promise((resolve) => nativeWaiters.push(resolve));
996
+ } else {
997
+ nativeActive++;
998
+ }
999
+ try {
1000
+ return await run();
1001
+ } finally {
1002
+ const next = nativeWaiters.shift();
1003
+ if (next) {
1004
+ next();
1005
+ } else {
1006
+ nativeActive--;
1007
+ }
1008
+ }
1009
+ }
1010
+ function txnIdBytes(id) {
1011
+ if (typeof id === "string") {
1012
+ if (!/^[0-9a-fA-F]{32}$/.test(id)) {
1013
+ throw new InvalidArgumentError(`txnId must be 32 hex characters, got ${JSON.stringify(id)}`);
1014
+ }
1015
+ return Buffer.from(id, "hex");
1016
+ }
1017
+ const buf = toRawBytes(id);
1018
+ if (buf.length !== 16) {
1019
+ throw new InvalidArgumentError(`txnId must be 16 bytes, got ${buf.length}`);
1020
+ }
1021
+ return buf;
1022
+ }
1023
+
1024
+ // src/sql-types.ts
1025
+ var SqlError = class extends Error {
1026
+ constructor(diagnostic, transactionId) {
1027
+ super(`${diagnostic.code}: ${diagnostic.message}`);
1028
+ this.diagnostic = diagnostic;
1029
+ this.transactionId = transactionId;
1030
+ this.name = "SqlError";
1031
+ this.sqlstate = diagnostic.code;
1032
+ }
1033
+ diagnostic;
1034
+ transactionId;
1035
+ sqlstate;
1036
+ };
1037
+
1038
+ // src/database.ts
1039
+ var OPEN_FLAG_NO_SYNC = 1 << 0;
1040
+ var OPEN_FLAG_TTL_CLEANUP = 1 << 1;
1041
+ var OPEN_FLAG_REMOTE_PROVIDER_CONFIGURED = 1 << 2;
1042
+ var OPEN_FLAG_LOCAL_RUNTIME_CONFIGURED = 1 << 3;
1043
+ var OPEN_FLAG_GENERATED_ENRICHMENT_REPLAY = 1 << 4;
1044
+ function buildOpenOptionsStruct(native, opts) {
1045
+ const options = {};
1046
+ checkCode(native.openOptionsInit(options));
1047
+ options.storage_kind = storageKind(opts.storage);
1048
+ options.open_mode = opts.mode ?? 0 /* Writer */;
1049
+ options.profile = opts.profile ?? 0 /* Native */;
1050
+ let flags = 0;
1051
+ if (opts.noSync) flags |= OPEN_FLAG_NO_SYNC;
1052
+ if (opts.remoteProviderConfigured) flags |= OPEN_FLAG_REMOTE_PROVIDER_CONFIGURED;
1053
+ if (opts.localRuntimeConfigured) flags |= OPEN_FLAG_LOCAL_RUNTIME_CONFIGURED;
1054
+ if (opts.generatedEnrichmentReplay) flags |= OPEN_FLAG_GENERATED_ENRICHMENT_REPLAY;
1055
+ if (opts.ttlCleanup) flags |= OPEN_FLAG_TTL_CLEANUP;
1056
+ options.flags = flags;
1057
+ options.map_size = opts.mapSize ?? 0;
1058
+ options.inference_host_budget_mb = opts.inferenceHostBudgetMb ?? 0;
1059
+ options.inference_backend_budget_mb = opts.inferenceBackendBudgetMb ?? 0;
1060
+ options.inference_combined_budget_mb = opts.inferenceCombinedBudgetMb ?? 0;
1061
+ options.inference_kv_budget_mb = opts.inferenceKvBudgetMb ?? 0;
1062
+ options.inference_scratch_budget_mb = opts.inferenceScratchBudgetMb ?? 0;
1063
+ options.inference_process_memory_budget_mb = opts.inferenceProcessMemoryBudgetMb ?? 0;
1064
+ options.busy_timeout_ms = opts.busyTimeoutMs ?? 0;
1065
+ if (opts.ttlCleanup) {
1066
+ const ttl = opts.ttlCleanup;
1067
+ options.ttl_cleanup_enabled = ttl.enabled;
1068
+ options.ttl_cleanup_lease_owned = ttl.leaseOwned;
1069
+ options.ttl_cleanup_batch_size = ttl.batchSize ?? 0;
1070
+ options.ttl_cleanup_owner_id = stringSlice(ttl.ownerId ?? "");
1071
+ options.ttl_cleanup_lease_ttl_ms = ttl.leaseTtlMs ?? 0;
1072
+ options.ttl_cleanup_interval_ms = ttl.intervalMs ?? 0;
1073
+ options.ttl_cleanup_grace_period_ns = ttl.gracePeriodNs ?? 0;
1074
+ }
1075
+ return options;
1076
+ }
1077
+ function keySlice(key) {
1078
+ return typeof key === "string" ? stringSlice(key) : sliceOf(toRawBytes(key));
1079
+ }
1080
+ function writeIntentValueBytes(w) {
1081
+ if (w.delete || w.value == null) {
1082
+ return Buffer.alloc(0);
1083
+ }
1084
+ if (w.value instanceof Uint8Array) {
1085
+ return toRawBytes(w.value);
1086
+ }
1087
+ return Buffer.from(JSON.stringify(w.value), "utf8");
1088
+ }
1089
+ function toNativeWriteIntent(w) {
1090
+ return {
1091
+ key: stringSlice(w.key),
1092
+ value: sliceOf(writeIntentValueBytes(w)),
1093
+ is_delete: Boolean(w.delete)
1094
+ };
1095
+ }
1096
+ var Database = class _Database {
1097
+ /** @internal use open()/create()/openHosted()/etc. instead of the constructor. */
1098
+ constructor(native, handle, owner) {
1099
+ this.owner = owner;
1100
+ this.#native = native;
1101
+ this.#handle = handle;
1102
+ finalizationRegistry.register(this, { native, handle }, this.#finalizerToken);
1103
+ }
1104
+ owner;
1105
+ #native;
1106
+ #handle;
1107
+ #state = "open";
1108
+ #pending = /* @__PURE__ */ new Set();
1109
+ #closeTask;
1110
+ #finalizerToken = {};
1111
+ #run(op) {
1112
+ if (this.#state !== "open") {
1113
+ return Promise.reject(new InvalidArgumentError("database handle is closed"));
1114
+ }
1115
+ const handle = this.#handle;
1116
+ const promise = op(handle);
1117
+ this.#pending.add(promise);
1118
+ const cleanup = () => this.#pending.delete(promise);
1119
+ promise.then(cleanup, cleanup);
1120
+ return promise;
1121
+ }
1122
+ // biome-ignore lint/suspicious/noExplicitAny: koffi function signatures vary per call site
1123
+ #invokeCode(fn, ...args) {
1124
+ return this.#run(async (handle) => {
1125
+ const code = await callAsync(fn, handle, ...args);
1126
+ checkCode(code);
1127
+ });
1128
+ }
1129
+ // biome-ignore lint/suspicious/noExplicitAny: koffi function signatures vary per call site
1130
+ #invokeBuffer(fn, ...args) {
1131
+ return this.#run(async (handle) => {
1132
+ const out = newBufferOut();
1133
+ const code = await callAsync(fn, handle, ...args, out);
1134
+ checkCode(code);
1135
+ return takeBuffer(this.#native, out);
1136
+ });
1137
+ }
1138
+ // SQL buffers must be released on failures as well as successful calls.
1139
+ // biome-ignore lint/suspicious/noExplicitAny: native signatures vary
1140
+ #invokeSql(fn, ...args) {
1141
+ return this.#run(async (handle) => {
1142
+ const out = newBufferOut();
1143
+ const code = await callAsync(fn, handle, ...args, out);
1144
+ const body = takeBuffer(this.#native, out);
1145
+ const value = body.length ? JSON.parse(body.toString("utf8")) : void 0;
1146
+ if (code && value?.error) throw new SqlError(value.error, value.transaction_id);
1147
+ checkCode(code);
1148
+ return value;
1149
+ });
1150
+ }
1151
+ sqlJson(request2) {
1152
+ return this.#invokeSql(this.#native.dbSqlJson, jsonSlice(request2));
1153
+ }
1154
+ createTable(name, schema) {
1155
+ return this.#invokeCode(this.#native.dbCreateTableJson, stringSlice(name), jsonSlice(schema));
1156
+ }
1157
+ dropTable(name) {
1158
+ return this.#invokeCode(this.#native.dbDropTable, stringSlice(name));
1159
+ }
1160
+ async listTables() {
1161
+ return parseJson(await this.#invokeBuffer(this.#native.dbListTablesJson));
1162
+ }
1163
+ async openSqlSession() {
1164
+ return this.#run(async (handle) => {
1165
+ const out = [0];
1166
+ checkCode(await callAsync(this.#native.dbSqlSessionOpen, handle, out));
1167
+ return out[0];
1168
+ });
1169
+ }
1170
+ closeSqlSession(id) {
1171
+ return this.#invokeCode(this.#native.dbSqlSessionClose, id);
1172
+ }
1173
+ async openSqlCursor(request2) {
1174
+ const out = [0];
1175
+ await this.#invokeSql(this.#native.dbSqlOpenCursorJson, jsonSlice(request2), out);
1176
+ return out[0];
1177
+ }
1178
+ fetchSqlCursor(id, rows = 128) {
1179
+ return this.#invokeSql(this.#native.dbSqlFetchCursorJson, id, rows);
1180
+ }
1181
+ closeSqlCursor(id) {
1182
+ return this.#invokeCode(this.#native.dbSqlCloseCursor, id);
1183
+ }
1184
+ // --- Lifecycle ---
1185
+ /** Idempotent; waits for in-flight calls before freeing the native handle. Calls made after close() rejects with InvalidArgumentError. */
1186
+ async close() {
1187
+ if (this.#state === "closed") return;
1188
+ if (this.#state === "closing") {
1189
+ await this.#closeTask;
1190
+ return;
1191
+ }
1192
+ this.#state = "closing";
1193
+ finalizationRegistry.unregister(this.#finalizerToken);
1194
+ const handle = this.#handle;
1195
+ this.#closeTask = (async () => {
1196
+ while (this.#pending.size > 0) {
1197
+ await Promise.allSettled([...this.#pending]);
1198
+ }
1199
+ if (handle != null) {
1200
+ await callAsync(this.#native.dbClose, handle);
1201
+ }
1202
+ this.#handle = null;
1203
+ this.#state = "closed";
1204
+ })();
1205
+ await this.#closeTask;
1206
+ }
1207
+ async [Symbol.asyncDispose]() {
1208
+ await this.close();
1209
+ }
1210
+ /** Open a table-scoped document/schema/index/enrichment handle. */
1211
+ async openTable(name) {
1212
+ const out = [null];
1213
+ await this.#invokeCode(this.#native.dbOpenTable, stringSlice(name), out);
1214
+ return new _Database(this.#native, out[0], this);
1215
+ }
1216
+ // --- Status / capabilities / maintenance ---
1217
+ statusRaw() {
1218
+ return this.#invokeBuffer(this.#native.dbStatusJson);
1219
+ }
1220
+ async status() {
1221
+ return parseJson(await this.statusRaw());
1222
+ }
1223
+ capabilitiesRaw() {
1224
+ return this.#invokeBuffer(this.#native.dbCapabilitiesJson);
1225
+ }
1226
+ async capabilities() {
1227
+ return parseJson(await this.capabilitiesRaw());
1228
+ }
1229
+ checkRaw() {
1230
+ return this.#invokeBuffer(this.#native.liteCheckJson);
1231
+ }
1232
+ async check() {
1233
+ return parseJson(await this.checkRaw());
1234
+ }
1235
+ vacuumRaw() {
1236
+ return this.#invokeBuffer(this.#native.liteVacuumJson);
1237
+ }
1238
+ async vacuum() {
1239
+ return parseJson(await this.vacuumRaw());
1240
+ }
1241
+ compactRaw() {
1242
+ return this.#invokeBuffer(this.#native.liteCompactJson);
1243
+ }
1244
+ async compact() {
1245
+ return parseJson(await this.compactRaw());
1246
+ }
1247
+ copyStableSnapshotRaw(destPath, replace) {
1248
+ if (!destPath.endsWith(".aflite")) {
1249
+ return Promise.reject(new InvalidArgumentError("destPath must end with .aflite"));
1250
+ }
1251
+ return this.#invokeBuffer(this.#native.liteCopyStableSnapshotJson, destPath, replace);
1252
+ }
1253
+ async copyStableSnapshot(destPath, replace) {
1254
+ return parseJson(await this.copyStableSnapshotRaw(destPath, replace));
1255
+ }
1256
+ pendingWorkStatsRaw() {
1257
+ return this.#invokeBuffer(this.#native.dbPendingWorkStatsJson);
1258
+ }
1259
+ async pendingWorkStats() {
1260
+ return parseJson(await this.pendingWorkStatsRaw());
1261
+ }
1262
+ /** Drains pending enrichment and index work; returns no result (see runUntilIdleStatus for the post-drain report). */
1263
+ runUntilIdle() {
1264
+ return this.#invokeCode(this.#native.dbRunUntilIdle);
1265
+ }
1266
+ runUntilIdleStatusRaw() {
1267
+ return this.#invokeBuffer(this.#native.dbRunUntilIdleJson);
1268
+ }
1269
+ async runUntilIdleStatus() {
1270
+ return parseJson(await this.runUntilIdleStatusRaw());
1271
+ }
1272
+ replayGeneratedEnrichmentsRaw() {
1273
+ return this.#invokeBuffer(this.#native.dbReplayGeneratedEnrichmentsJson);
1274
+ }
1275
+ async replayGeneratedEnrichments() {
1276
+ return parseJson(
1277
+ await this.replayGeneratedEnrichmentsRaw()
1278
+ );
1279
+ }
1280
+ // --- Backup / import ---
1281
+ /** Returns a portable Antfly backup archive (.afb) of this database, which restores or imports into either storage kind. */
1282
+ backup() {
1283
+ return this.#invokeBuffer(this.#native.dbBackup);
1284
+ }
1285
+ /** Imports a portable Antfly backup archive into this empty database. OutcomeUnknown means the live handle adopted the imported generation, but crash durability could not be confirmed; inspect the handle and do not retry automatically. */
1286
+ importBackup(backup) {
1287
+ return this.#invokeCode(this.#native.dbImportBackup, sliceOf(toRawBytes(backup)));
1288
+ }
1289
+ async backupToFile(path) {
1290
+ if (!path.endsWith(".afb")) throw new InvalidArgumentError("path must end with .afb");
1291
+ await writeFileAtomically(path, await this.backup());
1292
+ }
1293
+ // --- Documents ---
1294
+ batch(writes, timestampNs) {
1295
+ return this.#run(async (handle) => {
1296
+ const cWrites = writes.length ? writes.map(toNativeWriteIntent) : null;
1297
+ const code = await callAsync(
1298
+ this.#native.dbBatch,
1299
+ handle,
1300
+ cWrites,
1301
+ writes.length,
1302
+ null,
1303
+ 0,
1304
+ timestampNs,
1305
+ 0
1306
+ );
1307
+ checkCode(code);
1308
+ });
1309
+ }
1310
+ batchJsonRaw(request2) {
1311
+ return this.#invokeBuffer(this.#native.dbBatchJson, jsonSlice(request2));
1312
+ }
1313
+ async batchJson(request2) {
1314
+ return parseJson(await this.batchJsonRaw(request2));
1315
+ }
1316
+ lookupRaw(key) {
1317
+ return this.#invokeBuffer(this.#native.dbLookupJson, keySlice(key));
1318
+ }
1319
+ async lookup(key) {
1320
+ return parseJson(await this.lookupRaw(key));
1321
+ }
1322
+ /** Raw stored bytes for key (antfly_db_get_raw), not JSON. */
1323
+ getRaw(key) {
1324
+ return this.#invokeBuffer(this.#native.dbGetRaw, keySlice(key));
1325
+ }
1326
+ getSchemaRaw() {
1327
+ return this.#invokeBuffer(this.#native.dbGetSchemaJson);
1328
+ }
1329
+ async getSchema() {
1330
+ return parseJson(await this.getSchemaRaw());
1331
+ }
1332
+ setSchema(schema) {
1333
+ return this.#invokeCode(this.#native.dbSetSchemaJson, jsonSlice(schema));
1334
+ }
1335
+ listIndexesRaw() {
1336
+ return this.#invokeBuffer(this.#native.dbListIndexesJson);
1337
+ }
1338
+ async listIndexes() {
1339
+ return parseJson(await this.listIndexesRaw());
1340
+ }
1341
+ addIndex(config) {
1342
+ return this.#invokeCode(this.#native.dbAddIndexJson, jsonSlice(config));
1343
+ }
1344
+ deleteIndex(name) {
1345
+ return this.#run(async (handle) => {
1346
+ const out = [false];
1347
+ const code = await callAsync(this.#native.dbDeleteIndex, handle, stringSlice(name), out);
1348
+ checkCode(code);
1349
+ return Boolean(out[0]);
1350
+ });
1351
+ }
1352
+ listEnrichmentsRaw() {
1353
+ return this.#invokeBuffer(this.#native.dbListEnrichmentsJson);
1354
+ }
1355
+ async listEnrichments() {
1356
+ return parseJson(await this.listEnrichmentsRaw());
1357
+ }
1358
+ addEnrichment(config) {
1359
+ return this.#invokeCode(this.#native.dbAddEnrichmentJson, jsonSlice(config));
1360
+ }
1361
+ deleteEnrichment(kind, name) {
1362
+ return this.#run(async (handle) => {
1363
+ const out = [false];
1364
+ const code = await callAsync(
1365
+ this.#native.dbDeleteEnrichment,
1366
+ handle,
1367
+ stringSlice(kind),
1368
+ stringSlice(name),
1369
+ out
1370
+ );
1371
+ checkCode(code);
1372
+ return Boolean(out[0]);
1373
+ });
1374
+ }
1375
+ scanRaw(request2) {
1376
+ return this.#invokeBuffer(this.#native.dbScanJson, jsonSlice(request2));
1377
+ }
1378
+ async scan(request2) {
1379
+ return parseJson(await this.scanRaw(request2));
1380
+ }
1381
+ statsRaw() {
1382
+ return this.#invokeBuffer(this.#native.dbStatsJson);
1383
+ }
1384
+ async stats() {
1385
+ return parseJson(await this.statsRaw());
1386
+ }
1387
+ searchRaw(request2) {
1388
+ return this.#invokeBuffer(this.#native.dbSearchJson, jsonSlice(request2));
1389
+ }
1390
+ async search(request2) {
1391
+ return parseJson(await this.searchRaw(request2));
1392
+ }
1393
+ // --- Packed wire searches (binary wire format, never JSON: request/response are raw bytes) ---
1394
+ denseSearchWire(request2) {
1395
+ return this.#invokeBuffer(this.#native.dbSearchDenseWire, sliceOf(toRawBytes(request2)));
1396
+ }
1397
+ textMatchWire(request2) {
1398
+ return this.#invokeBuffer(this.#native.dbSearchTextMatchWire, sliceOf(toRawBytes(request2)));
1399
+ }
1400
+ textTermWire(request2) {
1401
+ return this.#invokeBuffer(this.#native.dbSearchTextTermWire, sliceOf(toRawBytes(request2)));
1402
+ }
1403
+ textMatchPhraseWire(request2) {
1404
+ return this.#invokeBuffer(
1405
+ this.#native.dbSearchTextMatchPhraseWire,
1406
+ sliceOf(toRawBytes(request2))
1407
+ );
1408
+ }
1409
+ aggregateHitsRaw(request2) {
1410
+ return this.#invokeBuffer(this.#native.dbAggregateHitsJson, jsonSlice(request2));
1411
+ }
1412
+ async aggregateHits(request2) {
1413
+ return parseJson(await this.aggregateHitsRaw(request2));
1414
+ }
1415
+ lookupArtifactRaw(artifactIdBase64) {
1416
+ return this.#invokeBuffer(this.#native.dbLookupArtifactJson, stringSlice(artifactIdBase64));
1417
+ }
1418
+ async lookupArtifact(artifactIdBase64) {
1419
+ return parseJson(await this.lookupArtifactRaw(artifactIdBase64));
1420
+ }
1421
+ extractEnrichmentsRaw(request2) {
1422
+ return this.#invokeBuffer(this.#native.dbExtractEnrichmentsJson, jsonSlice(request2));
1423
+ }
1424
+ async extractEnrichments(request2) {
1425
+ return parseJson(await this.extractEnrichmentsRaw(request2));
1426
+ }
1427
+ computeEnrichmentsRaw(request2) {
1428
+ return this.#invokeBuffer(this.#native.dbComputeEnrichmentsJson, jsonSlice(request2));
1429
+ }
1430
+ async computeEnrichments(request2) {
1431
+ return parseJson(await this.computeEnrichmentsRaw(request2));
1432
+ }
1433
+ // --- Graph ---
1434
+ edgesRaw(indexName, key, edgeType, direction) {
1435
+ return this.#invokeBuffer(
1436
+ this.#native.dbGetEdgesJson,
1437
+ stringSlice(indexName),
1438
+ stringSlice(key),
1439
+ stringSlice(edgeType),
1440
+ direction
1441
+ );
1442
+ }
1443
+ async edges(indexName, key, edgeType, direction) {
1444
+ return parseJson(await this.edgesRaw(indexName, key, edgeType, direction));
1445
+ }
1446
+ neighborsRaw(indexName, key, edgeType, direction) {
1447
+ return this.#invokeBuffer(
1448
+ this.#native.dbGetNeighborsJson,
1449
+ stringSlice(indexName),
1450
+ stringSlice(key),
1451
+ stringSlice(edgeType),
1452
+ direction
1453
+ );
1454
+ }
1455
+ async neighbors(indexName, key, edgeType, direction) {
1456
+ return parseJson(await this.neighborsRaw(indexName, key, edgeType, direction));
1457
+ }
1458
+ traverseEdgesRaw(request2) {
1459
+ return this.#invokeBuffer(this.#native.dbTraverseEdgesJson, jsonSlice(request2));
1460
+ }
1461
+ async traverseEdges(request2) {
1462
+ return parseJson(await this.traverseEdgesRaw(request2));
1463
+ }
1464
+ executeGraphQueriesRaw(request2) {
1465
+ return this.#invokeBuffer(this.#native.dbExecuteGraphQueriesJson, jsonSlice(request2));
1466
+ }
1467
+ async executeGraphQueries(request2) {
1468
+ return parseJson(await this.executeGraphQueriesRaw(request2));
1469
+ }
1470
+ findShortestPathRaw(request2) {
1471
+ return this.#invokeBuffer(this.#native.dbFindShortestPathJson, jsonSlice(request2));
1472
+ }
1473
+ async findShortestPath(request2) {
1474
+ return parseJson(await this.findShortestPathRaw(request2));
1475
+ }
1476
+ findKShortestPathsRaw(request2) {
1477
+ return this.#invokeBuffer(this.#native.dbFindKShortestPathsJson, jsonSlice(request2));
1478
+ }
1479
+ async findKShortestPaths(request2) {
1480
+ return parseJson(await this.findKShortestPathsRaw(request2));
1481
+ }
1482
+ matchPatternRaw(request2) {
1483
+ return this.#invokeBuffer(this.#native.dbMatchPatternJson, jsonSlice(request2));
1484
+ }
1485
+ async matchPattern(request2) {
1486
+ return parseJson(await this.matchPatternRaw(request2));
1487
+ }
1488
+ // --- Transactions ---
1489
+ beginTransaction(txnId, timestampNs, participants = []) {
1490
+ return this.#run(async (handle) => {
1491
+ const id = txnIdBytes(txnId);
1492
+ const cParticipants = participants.length ? participants.map(stringSlice) : null;
1493
+ const code = await callAsync(
1494
+ this.#native.dbBeginTransactionWithId,
1495
+ handle,
1496
+ id,
1497
+ timestampNs,
1498
+ cParticipants,
1499
+ participants.length
1500
+ );
1501
+ checkCode(code);
1502
+ });
1503
+ }
1504
+ writeTransaction(txnId, writes) {
1505
+ return this.#run(async (handle) => {
1506
+ const id = txnIdBytes(txnId);
1507
+ const cWrites = writes.length ? writes.map(toNativeWriteIntent) : null;
1508
+ const code = await callAsync(
1509
+ this.#native.dbWriteTransaction,
1510
+ handle,
1511
+ id,
1512
+ cWrites,
1513
+ writes.length,
1514
+ null,
1515
+ 0
1516
+ );
1517
+ checkCode(code);
1518
+ });
1519
+ }
1520
+ resolveTransaction(txnId, status, commitVersion = 0) {
1521
+ return this.#invokeCode(
1522
+ this.#native.dbResolveIntents,
1523
+ txnIdBytes(txnId),
1524
+ status,
1525
+ commitVersion
1526
+ );
1527
+ }
1528
+ transactionStatus(txnId) {
1529
+ return this.#run(async (handle) => {
1530
+ const id = txnIdBytes(txnId);
1531
+ const out = [0];
1532
+ const code = await callAsync(this.#native.dbGetTransactionStatus, handle, id, out);
1533
+ checkCode(code);
1534
+ return out[0];
1535
+ });
1536
+ }
1537
+ commitVersion(txnId) {
1538
+ return this.#run(async (handle) => {
1539
+ const id = txnIdBytes(txnId);
1540
+ const out = [0];
1541
+ const code = await callAsync(this.#native.dbGetCommitVersion, handle, id, out);
1542
+ checkCode(code);
1543
+ return BigInt(out[0] ?? 0);
1544
+ });
1545
+ }
1546
+ };
1547
+ var finalizationRegistry = new FinalizationRegistry(
1548
+ ({ native, handle }) => {
1549
+ if (handle != null) {
1550
+ try {
1551
+ native.dbClose(handle);
1552
+ } catch {
1553
+ }
1554
+ }
1555
+ }
1556
+ );
1557
+ async function writeFileAtomically(path, data, mode = 384) {
1558
+ const dir = (0, import_node_path2.dirname)(path);
1559
+ const tmpPath = (0, import_node_path2.join)(
1560
+ dir,
1561
+ `.${(0, import_node_path2.basename)(path)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
1562
+ );
1563
+ const handle = await fsp.open(tmpPath, "w", mode);
1564
+ try {
1565
+ await handle.writeFile(data);
1566
+ await handle.sync();
1567
+ } finally {
1568
+ await handle.close();
1569
+ }
1570
+ await fsp.rename(tmpPath, path);
1571
+ }
1572
+ async function openOrCreate(path, opts, create2) {
1573
+ validateAbi();
1574
+ const native = loadNative();
1575
+ const options = buildOpenOptionsStruct(native, opts);
1576
+ const outHandle = [null];
1577
+ const fn = create2 ? native.dbCreateWithOptions : native.dbOpenWithOptions;
1578
+ const code = await callAsync(fn, path, options, outHandle);
1579
+ checkCode(code);
1580
+ return new Database(native, outHandle[0]);
1581
+ }
1582
+ function open2(path) {
1583
+ return openWithOptions(path, { mode: 0 /* Writer */, profile: 0 /* Native */ });
1584
+ }
1585
+ function create(path) {
1586
+ return createWithOptions(path, { mode: 0 /* Writer */, profile: 0 /* Native */ });
1587
+ }
1588
+ function openReadonly(path) {
1589
+ return openWithOptions(path, { mode: 1 /* Readonly */, profile: 0 /* Native */ });
1590
+ }
1591
+ function openStatusOnly(path) {
1592
+ return openWithOptions(path, { mode: 2 /* StatusOnly */, profile: 0 /* Native */ });
1593
+ }
1594
+ function openWithOptions(path, options = {}) {
1595
+ return openOrCreate(path, options, false);
1596
+ }
1597
+ function createWithOptions(path, options = {}) {
1598
+ return openOrCreate(path, options, true);
1599
+ }
1600
+ async function openHosted(path) {
1601
+ validateAbi();
1602
+ const native = loadNative();
1603
+ const outHandle = [null];
1604
+ const code = await callAsync(native.liteOpenHosted, path, outHandle);
1605
+ checkCode(code);
1606
+ return new Database(native, outHandle[0]);
1607
+ }
1608
+ async function createHosted(path) {
1609
+ validateAbi();
1610
+ const native = loadNative();
1611
+ const outHandle = [null];
1612
+ const code = await callAsync(native.liteCreateHosted, path, outHandle);
1613
+ checkCode(code);
1614
+ return new Database(native, outHandle[0]);
1615
+ }
1616
+
1617
+ // src/files.ts
1618
+ function restoreOpenOptions(native, storage) {
1619
+ const options = {};
1620
+ checkCode(native.openOptionsInit(options));
1621
+ options.storage_kind = storageKind(storage);
1622
+ return options;
1623
+ }
1624
+ async function checkFileRaw(path) {
1625
+ validateAbi();
1626
+ const native = loadNative();
1627
+ const out = newBufferOut();
1628
+ const code = await callAsync(native.liteCheckFileJson, path, out);
1629
+ checkCode(code);
1630
+ return takeBuffer(native, out);
1631
+ }
1632
+ async function checkFile(path) {
1633
+ return parseJson(await checkFileRaw(path));
1634
+ }
1635
+ async function copyStableSnapshotFileRaw(srcPath, destPath, replace) {
1636
+ if (!srcPath.endsWith(".aflite") || !destPath.endsWith(".aflite")) {
1637
+ throw new InvalidArgumentError("srcPath and destPath must end with .aflite");
1638
+ }
1639
+ const native = loadNative();
1640
+ const out = newBufferOut();
1641
+ const code = await callAsync(
1642
+ native.liteCopyStableSnapshotFileJson,
1643
+ srcPath,
1644
+ destPath,
1645
+ replace,
1646
+ out
1647
+ );
1648
+ checkCode(code);
1649
+ return takeBuffer(native, out);
1650
+ }
1651
+ async function copyStableSnapshotFile(srcPath, destPath, replace) {
1652
+ return parseJson(
1653
+ await copyStableSnapshotFileRaw(srcPath, destPath, replace)
1654
+ );
1655
+ }
1656
+ async function restore(path, backup, opts = {}) {
1657
+ if ((opts.storage ?? 0 /* Lite */) === 0 /* Lite */ && !path.endsWith(".aflite")) {
1658
+ throw new InvalidArgumentError("path must end with .aflite for Storage.Lite");
1659
+ }
1660
+ if (backup.length === 0) {
1661
+ throw new InvalidArgumentError("backup must be non-empty");
1662
+ }
1663
+ const native = loadNative();
1664
+ const options = restoreOpenOptions(native, opts.storage);
1665
+ const out = newBufferOut();
1666
+ const code = await callAsync(
1667
+ native.restoreBackupJson,
1668
+ path,
1669
+ options,
1670
+ sliceOf(toRawBytes(backup)),
1671
+ Boolean(opts.replace),
1672
+ out
1673
+ );
1674
+ checkCode(code);
1675
+ takeBuffer(native, out);
1676
+ }
1677
+ async function restoreFile(path, backupPath, opts = {}) {
1678
+ if (!backupPath.endsWith(".afb")) {
1679
+ throw new InvalidArgumentError("backupPath must end with .afb");
1680
+ }
1681
+ if ((opts.storage ?? 0 /* Lite */) === 0 /* Lite */ && !path.endsWith(".aflite")) {
1682
+ throw new InvalidArgumentError("path must end with .aflite for Storage.Lite");
1683
+ }
1684
+ const native = loadNative();
1685
+ const options = restoreOpenOptions(native, opts.storage);
1686
+ const out = newBufferOut();
1687
+ const code = await callAsync(
1688
+ native.restoreBackupFileJson,
1689
+ path,
1690
+ options,
1691
+ backupPath,
1692
+ Boolean(opts.replace),
1693
+ out
1694
+ );
1695
+ checkCode(code);
1696
+ takeBuffer(native, out);
1697
+ }
1698
+ async function decodeArtifactIdRaw(artifactIdBase64) {
1699
+ const native = loadNative();
1700
+ const out = newBufferOut();
1701
+ const code = await callAsync(native.decodeArtifactIdJson, stringSlice(artifactIdBase64), out);
1702
+ checkCode(code);
1703
+ return takeBuffer(native, out);
1704
+ }
1705
+ async function decodeArtifactId(artifactIdBase64) {
1706
+ return parseJson(await decodeArtifactIdRaw(artifactIdBase64));
1707
+ }
1708
+
1709
+ // src/inference.ts
1710
+ var import_koffi4 = __toESM(require("koffi"), 1);
1711
+ function buildInferenceOptionsStruct(native, opts) {
1712
+ const options = {};
1713
+ checkCode(native.inferenceOptionsInit(options));
1714
+ options.models_dir = stringSlice(opts.modelsDir ?? "");
1715
+ options.host_budget_mb = opts.hostBudgetMb ?? 0;
1716
+ options.backend_budget_mb = opts.backendBudgetMb ?? 0;
1717
+ options.process_memory_budget_mb = opts.processMemoryBudgetMb ?? 0;
1718
+ options.combined_budget_mb = opts.combinedBudgetMb ?? 0;
1719
+ options.kv_budget_mb = opts.kvBudgetMb ?? 0;
1720
+ options.scratch_budget_mb = opts.scratchBudgetMb ?? 0;
1721
+ options.call_timeout_ms = opts.callTimeoutMs ?? 0;
1722
+ return options;
1723
+ }
1724
+ function errorFromResponseBody(code, body) {
1725
+ let parsed;
1726
+ if (body.length > 0) {
1727
+ try {
1728
+ parsed = JSON.parse(body.toString("utf8"));
1729
+ } catch {
1730
+ parsed = void 0;
1731
+ }
1732
+ }
1733
+ let message;
1734
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1735
+ const b = parsed;
1736
+ const errPart = typeof b.error === "string" ? b.error : void 0;
1737
+ const msgPart = typeof b.message === "string" ? b.message : void 0;
1738
+ message = [errPart, msgPart].filter((s) => Boolean(s)).join(": ") || void 0;
1739
+ }
1740
+ const err = errorFromCode(code, message);
1741
+ err.body = parsed;
1742
+ return err;
1743
+ }
1744
+ function decodeSliceBytes(slice) {
1745
+ if (!slice || slice.ptr == null) {
1746
+ return Buffer.alloc(0);
1747
+ }
1748
+ const len = Number(slice.len ?? 0);
1749
+ if (len === 0) {
1750
+ return Buffer.alloc(0);
1751
+ }
1752
+ const view = import_koffi4.default.decode(slice.ptr, "uint8_t", len);
1753
+ return Buffer.from(view);
1754
+ }
1755
+ function decodeSliceUtf8(slice) {
1756
+ return decodeSliceBytes(slice).toString("utf8");
1757
+ }
1758
+ function toPullProgress(decoded) {
1759
+ return {
1760
+ model: decodeSliceUtf8(decoded.model),
1761
+ file: decodeSliceUtf8(decoded.file),
1762
+ bytesDownloaded: BigInt(decoded.bytes_downloaded ?? 0),
1763
+ totalBytes: BigInt(decoded.total_bytes ?? 0),
1764
+ filesDone: BigInt(decoded.files_done ?? 0),
1765
+ filesTotal: BigInt(decoded.files_total ?? 0),
1766
+ cached: Boolean(decoded.cached)
1767
+ };
1768
+ }
1769
+ var Inference = class _Inference {
1770
+ #native;
1771
+ #handle;
1772
+ #state = "open";
1773
+ #pending = /* @__PURE__ */ new Set();
1774
+ #closeTask;
1775
+ #finalizerToken = {};
1776
+ /** @internal use Inference.open() instead of the constructor. */
1777
+ constructor(native, handle) {
1778
+ this.#native = native;
1779
+ this.#handle = handle;
1780
+ inferenceFinalizationRegistry.register(this, { native, handle }, this.#finalizerToken);
1781
+ }
1782
+ /** Starts the embedded inference runtime with no database. Returns UnsupportedError if this build does not link the inference runtime or it cannot start. */
1783
+ static async open(options = {}) {
1784
+ validateAbi();
1785
+ validateInferenceAbi();
1786
+ const native = loadNative();
1787
+ const optsStruct = buildInferenceOptionsStruct(native, options);
1788
+ const outHandle = [null];
1789
+ const code = await callAsync(native.inferenceOpen, optsStruct, outHandle);
1790
+ checkCode(code);
1791
+ return new _Inference(native, outHandle[0]);
1792
+ }
1793
+ #run(op) {
1794
+ if (this.#state !== "open") {
1795
+ return Promise.reject(new InvalidArgumentError("inference handle is closed"));
1796
+ }
1797
+ const handle = this.#handle;
1798
+ const promise = op(handle);
1799
+ this.#pending.add(promise);
1800
+ const cleanup = () => this.#pending.delete(promise);
1801
+ promise.then(cleanup, cleanup);
1802
+ return promise;
1803
+ }
1804
+ #track(promise) {
1805
+ this.#pending.add(promise);
1806
+ const cleanup = () => this.#pending.delete(promise);
1807
+ promise.then(cleanup, cleanup);
1808
+ return promise;
1809
+ }
1810
+ // biome-ignore lint/suspicious/noExplicitAny: koffi function signatures vary per call site
1811
+ #invokeJson(fn, request2) {
1812
+ return this.#run(async (handle) => {
1813
+ const out = newBufferOut();
1814
+ const code = await callAsync(fn, handle, jsonSlice(request2), out);
1815
+ const body = takeBuffer(this.#native, out);
1816
+ if (code !== 0 /* OK */) {
1817
+ throw errorFromResponseBody(code, body);
1818
+ }
1819
+ return body;
1820
+ });
1821
+ }
1822
+ /** Idempotent; waits for in-flight calls before freeing the native handle. Calls made after close() rejects with InvalidArgumentError. */
1823
+ async close() {
1824
+ if (this.#state === "closed") return;
1825
+ if (this.#state === "closing") {
1826
+ await this.#closeTask;
1827
+ return;
1828
+ }
1829
+ this.#state = "closing";
1830
+ inferenceFinalizationRegistry.unregister(this.#finalizerToken);
1831
+ const handle = this.#handle;
1832
+ this.#closeTask = (async () => {
1833
+ while (this.#pending.size > 0) {
1834
+ await Promise.allSettled([...this.#pending]);
1835
+ }
1836
+ if (handle != null) {
1837
+ await callAsync(this.#native.inferenceClose, handle);
1838
+ }
1839
+ this.#handle = null;
1840
+ this.#state = "closed";
1841
+ })();
1842
+ await this.#closeTask;
1843
+ }
1844
+ async [Symbol.asyncDispose]() {
1845
+ await this.close();
1846
+ }
1847
+ // --- JSON calls (POST /ai/v1/<route>) ---
1848
+ embedRaw(request2) {
1849
+ return this.#invokeJson(this.#native.inferenceEmbedJson, request2);
1850
+ }
1851
+ async embed(request2) {
1852
+ return parseJson(await this.embedRaw(request2));
1853
+ }
1854
+ rerankRaw(request2) {
1855
+ return this.#invokeJson(this.#native.inferenceRerankJson, request2);
1856
+ }
1857
+ async rerank(request2) {
1858
+ return parseJson(await this.rerankRaw(request2));
1859
+ }
1860
+ chunkRaw(request2) {
1861
+ return this.#invokeJson(this.#native.inferenceChunkJson, request2);
1862
+ }
1863
+ async chunk(request2) {
1864
+ return parseJson(await this.chunkRaw(request2));
1865
+ }
1866
+ /** A generate request with "stream": true fails with InvalidArgumentError; responses are always complete. Use generateStream() to stream. */
1867
+ generateRaw(request2) {
1868
+ return this.#invokeJson(this.#native.inferenceGenerateJson, request2);
1869
+ }
1870
+ async generate(request2) {
1871
+ return parseJson(await this.generateRaw(request2));
1872
+ }
1873
+ /**
1874
+ * Streams a generate request (antfly_inference_generate_stream_json): the
1875
+ * same request body as generate(), with "stream" set for you. onChunk is
1876
+ * called synchronously, on the calling thread, once per streamed chunk
1877
+ * (a parsed "chat.completion.chunk" JSON object), as the model produces
1878
+ * tokens.
1879
+ *
1880
+ * Returning `false` from onChunk stops generation early; the call then
1881
+ * rejects with CancelledError. A thrown error also stops generation and
1882
+ * is rethrown from this call (generation does not continue in the
1883
+ * background). generateStream() runs synchronously on the JS thread and
1884
+ * blocks the event loop for its duration -- see the class docstring for
1885
+ * why (the same koffi callback-threading constraint as pull()); this is
1886
+ * the reason this binding offers a callback, not an async iterator.
1887
+ *
1888
+ * A request rejected before generation starts (e.g. a missing model)
1889
+ * rejects the same way generate() does, with the JSON error body on
1890
+ * `.body`. A failure mid-stream rejects InternalError with
1891
+ * `.body.error === "STREAM_FAILED"`.
1892
+ */
1893
+ generateStreamRaw(request2, onChunk) {
1894
+ if (this.#state !== "open") {
1895
+ return Promise.reject(new InvalidArgumentError("inference handle is closed"));
1896
+ }
1897
+ const handle = this.#handle;
1898
+ const native = this.#native;
1899
+ const run = () => {
1900
+ let callbackError;
1901
+ let callbackThrew = false;
1902
+ const callbackPtr = import_koffi4.default.register(
1903
+ (_context, chunk) => {
1904
+ try {
1905
+ return onChunk(decodeSliceBytes(chunk)) !== false;
1906
+ } catch (err) {
1907
+ callbackThrew = true;
1908
+ callbackError = err;
1909
+ return false;
1910
+ }
1911
+ },
1912
+ PAntflyInferenceStreamFn
1913
+ );
1914
+ try {
1915
+ const out = newBufferOut();
1916
+ const code = native.inferenceGenerateStreamJson(
1917
+ handle,
1918
+ jsonSlice(request2),
1919
+ callbackPtr,
1920
+ null,
1921
+ out
1922
+ );
1923
+ const body = takeBuffer(native, out);
1924
+ if (callbackThrew) {
1925
+ throw callbackError;
1926
+ }
1927
+ if (code !== 0 /* OK */) {
1928
+ throw errorFromResponseBody(code, body);
1929
+ }
1930
+ return body;
1931
+ } finally {
1932
+ import_koffi4.default.unregister(callbackPtr);
1933
+ }
1934
+ };
1935
+ return this.#track(Promise.resolve().then(run));
1936
+ }
1937
+ async generateStream(request2, onChunk) {
1938
+ return parseJson(
1939
+ await this.generateStreamRaw(request2, (chunkJson) => onChunk(parseJson(chunkJson)))
1940
+ );
1941
+ }
1942
+ /** Up to 128 non-streaming generate requests in one call; per-item failures are reported in the response. */
1943
+ generateBatchRaw(request2) {
1944
+ return this.#invokeJson(this.#native.inferenceGenerateBatchJson, request2);
1945
+ }
1946
+ async generateBatch(request2) {
1947
+ return parseJson(await this.generateBatchRaw(request2));
1948
+ }
1949
+ rewriteRaw(request2) {
1950
+ return this.#invokeJson(this.#native.inferenceRewriteJson, request2);
1951
+ }
1952
+ async rewrite(request2) {
1953
+ return parseJson(await this.rewriteRaw(request2));
1954
+ }
1955
+ /** Named choice, ordinal score, and Boolean questions using DecideRequest JSON. */
1956
+ decideRaw(request2) {
1957
+ return this.#invokeJson(this.#native.inferenceDecideJson, request2);
1958
+ }
1959
+ /** Parsed DecideResponse from the same contract as POST /ai/v1/decisions. */
1960
+ async decide(request2) {
1961
+ return parseJson(await this.decideRaw(request2));
1962
+ }
1963
+ extractRaw(request2) {
1964
+ return this.#invokeJson(this.#native.inferenceExtractJson, request2);
1965
+ }
1966
+ async extract(request2) {
1967
+ return parseJson(await this.extractRaw(request2));
1968
+ }
1969
+ /** OCR. */
1970
+ readRaw(request2) {
1971
+ return this.#invokeJson(this.#native.inferenceReadJson, request2);
1972
+ }
1973
+ async read(request2) {
1974
+ return parseJson(await this.readRaw(request2));
1975
+ }
1976
+ transcribeRaw(request2) {
1977
+ return this.#invokeJson(this.#native.inferenceTranscribeJson, request2);
1978
+ }
1979
+ async transcribe(request2) {
1980
+ return parseJson(await this.transcribeRaw(request2));
1981
+ }
1982
+ /** The installed models, as returned by GET /ai/v1/models. */
1983
+ listModelsRaw() {
1984
+ return this.#run(async (handle) => {
1985
+ const out = newBufferOut();
1986
+ const code = await callAsync(this.#native.inferenceListModelsJson, handle, out);
1987
+ const body = takeBuffer(this.#native, out);
1988
+ if (code !== 0 /* OK */) {
1989
+ throw errorFromResponseBody(code, body);
1990
+ }
1991
+ return body;
1992
+ });
1993
+ }
1994
+ async listModels() {
1995
+ return parseJson(await this.listModelsRaw());
1996
+ }
1997
+ /**
1998
+ * Downloads a model from the Hugging Face Hub into the handle's models
1999
+ * directory, like `antfly inference pull`. request: {"model": "owner/name[:variant]",
2000
+ * required; "variants": [...]; "token": "..." (default $HF_TOKEN);
2001
+ * "tasks"/"capabilities" to override the model manifest; "projector":
2002
+ * "auto" | "none" | "match"; "max_artifact_bytes"/"max_model_bytes"}.
2003
+ *
2004
+ * onProgress (optional) is called synchronously, on the calling thread,
2005
+ * as each file starts, every 16 MiB, and as it completes; see the class
2006
+ * docstring for why pull() itself runs synchronously (blocking the event
2007
+ * loop) rather than on koffi's async worker pool. Returning `false` from
2008
+ * onProgress cancels the pull -- the call then rejects with
2009
+ * CancelledError, and completed files stay staged, so a later pull()
2010
+ * for the same model resumes rather than restarts. A thrown error also
2011
+ * cancels the pull and is rethrown from this call.
2012
+ *
2013
+ * `signal` (optional) is a best-effort, honestly-limited cancellation
2014
+ * knob: because pull() blocks the JS thread for its whole duration,
2015
+ * there is no way to interrupt it asynchronously from the outside the
2016
+ * way `fetch(url, { signal })` can. An already-aborted signal rejects
2017
+ * immediately without starting the pull; otherwise the signal is polled
2018
+ * only at the same report points as onProgress (each file start, every
2019
+ * 16 MiB, file end) -- an abort in between those points is not observed
2020
+ * until the next one. Prefer returning `false` from onProgress when you
2021
+ * need precise control.
2022
+ *
2023
+ * A model missing from the hub rejects with NotFoundError, a bad request
2024
+ * or a model over the size limits with InvalidArgumentError, and a
2025
+ * network or hub failure with BusyError. close() waits for a pull in
2026
+ * progress.
2027
+ */
2028
+ pullRaw(request2, onProgress, signal) {
2029
+ if (this.#state !== "open") {
2030
+ return Promise.reject(new InvalidArgumentError("inference handle is closed"));
2031
+ }
2032
+ if (signal?.aborted) {
2033
+ return Promise.reject(cancelledBySignal(signal));
2034
+ }
2035
+ const handle = this.#handle;
2036
+ const native = this.#native;
2037
+ const run = () => {
2038
+ let callbackPtr;
2039
+ let callbackError;
2040
+ let callbackThrew = false;
2041
+ if (onProgress || signal) {
2042
+ callbackPtr = import_koffi4.default.register((_context, progressPtr) => {
2043
+ try {
2044
+ if (signal?.aborted) {
2045
+ return false;
2046
+ }
2047
+ const decoded = import_koffi4.default.decode(
2048
+ progressPtr,
2049
+ AntflyInferencePullProgress
2050
+ );
2051
+ return onProgress?.(toPullProgress(decoded)) !== false;
2052
+ } catch (err) {
2053
+ callbackThrew = true;
2054
+ callbackError = err;
2055
+ return false;
2056
+ }
2057
+ }, PAntflyInferencePullProgressFn);
2058
+ }
2059
+ try {
2060
+ const out = newBufferOut();
2061
+ const code = native.inferencePullJson(
2062
+ handle,
2063
+ jsonSlice(request2),
2064
+ callbackPtr ?? null,
2065
+ null,
2066
+ out
2067
+ );
2068
+ const body = takeBuffer(native, out);
2069
+ if (callbackThrew) {
2070
+ throw callbackError;
2071
+ }
2072
+ if (code !== 0 /* OK */) {
2073
+ throw errorFromResponseBody(code, body);
2074
+ }
2075
+ return body;
2076
+ } finally {
2077
+ if (callbackPtr !== void 0) {
2078
+ import_koffi4.default.unregister(callbackPtr);
2079
+ }
2080
+ }
2081
+ };
2082
+ return this.#track(Promise.resolve().then(run));
2083
+ }
2084
+ async pull(request2, onProgress, signal) {
2085
+ return parseJson(await this.pullRaw(request2, onProgress, signal));
2086
+ }
2087
+ };
2088
+ function cancelledBySignal(signal) {
2089
+ const reason = signal.reason;
2090
+ const detail = reason instanceof Error ? reason.message : reason !== void 0 ? String(reason) : void 0;
2091
+ return new CancelledError(
2092
+ detail ? `pull cancelled before it started: ${detail}` : "pull cancelled before it started"
2093
+ );
2094
+ }
2095
+ var inferenceFinalizationRegistry = new FinalizationRegistry(({ native, handle }) => {
2096
+ if (handle != null) {
2097
+ try {
2098
+ native.inferenceClose(handle);
2099
+ } catch {
2100
+ }
2101
+ }
2102
+ });
2103
+
2104
+ // src/sql.ts
2105
+ function request(statement, parameters, session, streaming = false) {
2106
+ return JSON.stringify(
2107
+ { statement, parameters, session_id: session, limit: streaming ? void 0 : 4096 },
2108
+ (_key, value) => {
2109
+ if (typeof value === "bigint") {
2110
+ if (value < -(1n << 63n) || value >= 1n << 63n)
2111
+ throw new RangeError("integer parameter is outside the signed 64-bit range");
2112
+ return value.toString();
2113
+ }
2114
+ if (typeof value === "number" && (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)))
2115
+ throw new RangeError("use bigint for integer parameters outside JavaScript's safe range");
2116
+ return value;
2117
+ }
2118
+ );
2119
+ }
2120
+ function result(wire) {
2121
+ return {
2122
+ columns: wire.columns,
2123
+ commandTag: wire.command_tag,
2124
+ rowsAffected: BigInt(wire.rows_affected),
2125
+ rows: wire.rows.map(
2126
+ (row, rowIndex) => Object.fromEntries(
2127
+ wire.columns.map((column, index) => [
2128
+ column.name,
2129
+ wire.sql_nulls?.[rowIndex]?.[index] ? null : column.type === "integer" && row[index] !== null ? BigInt(row[index]) : row[index]
2130
+ ])
2131
+ )
2132
+ )
2133
+ };
2134
+ }
2135
+ var Connection = class _Connection {
2136
+ constructor(database, session, direct = false) {
2137
+ this.database = database;
2138
+ this.session = session;
2139
+ this.direct = direct;
2140
+ }
2141
+ database;
2142
+ session;
2143
+ direct;
2144
+ #pending = Promise.resolve();
2145
+ #closed = false;
2146
+ static async open(database) {
2147
+ return new _Connection(database, await database.openSqlSession());
2148
+ }
2149
+ #run(operation) {
2150
+ if (this.#closed) return Promise.reject(new Error("SQL connection is closed"));
2151
+ if (this.direct) return operation();
2152
+ const work = this.#pending.then(operation);
2153
+ this.#pending = work.catch(() => void 0);
2154
+ return work;
2155
+ }
2156
+ execute(statement, parameters = []) {
2157
+ return this.#run(
2158
+ async () => result(
2159
+ await this.database.sqlJson(request(statement, parameters, this.session))
2160
+ )
2161
+ );
2162
+ }
2163
+ query(statement, parameters = []) {
2164
+ return this.#run(async () => {
2165
+ let cursor;
2166
+ try {
2167
+ cursor = await this.database.openSqlCursor(
2168
+ request(statement, parameters, this.session, true)
2169
+ );
2170
+ } catch (error) {
2171
+ if (!(error instanceof SqlError) || error.sqlstate !== "0A000") throw error;
2172
+ return result(
2173
+ await this.database.sqlJson(request(statement, parameters, this.session))
2174
+ );
2175
+ }
2176
+ let output;
2177
+ try {
2178
+ while (true) {
2179
+ const page = await this.database.fetchSqlCursor(cursor);
2180
+ const decoded = result(page.result);
2181
+ if (output) output.rows.push(...decoded.rows);
2182
+ else output = decoded;
2183
+ if (page.exhausted) return output;
2184
+ }
2185
+ } finally {
2186
+ await this.database.closeSqlCursor(cursor);
2187
+ }
2188
+ });
2189
+ }
2190
+ async *stream(statement, parameters = [], chunkSize = 128) {
2191
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > 4096)
2192
+ throw new RangeError("chunkSize must be 1..4096");
2193
+ if (this.#closed) throw new Error("SQL connection is closed");
2194
+ const previous = this.#pending;
2195
+ let release = () => {
2196
+ };
2197
+ if (!this.direct)
2198
+ this.#pending = new Promise((resolve) => {
2199
+ release = resolve;
2200
+ });
2201
+ await previous;
2202
+ let cursor;
2203
+ try {
2204
+ cursor = await this.database.openSqlCursor(
2205
+ request(statement, parameters, this.session, true)
2206
+ );
2207
+ while (true) {
2208
+ const page = await this.database.fetchSqlCursor(cursor, chunkSize);
2209
+ yield result(page.result);
2210
+ if (page.exhausted) break;
2211
+ }
2212
+ } finally {
2213
+ try {
2214
+ if (cursor !== void 0) await this.database.closeSqlCursor(cursor);
2215
+ } finally {
2216
+ release();
2217
+ }
2218
+ }
2219
+ }
2220
+ transaction(operation) {
2221
+ return this.#run(async () => {
2222
+ const transaction = new _Connection(this.database, this.session, true);
2223
+ await transaction.execute("BEGIN ISOLATION LEVEL READ COMMITTED");
2224
+ try {
2225
+ const value = await operation(transaction);
2226
+ await transaction.execute("COMMIT");
2227
+ return value;
2228
+ } catch (error) {
2229
+ try {
2230
+ await transaction.execute("ROLLBACK");
2231
+ } catch {
2232
+ }
2233
+ throw error;
2234
+ } finally {
2235
+ transaction.#closed = true;
2236
+ }
2237
+ });
2238
+ }
2239
+ async close() {
2240
+ if (this.#closed) return;
2241
+ this.#closed = true;
2242
+ await this.#pending;
2243
+ await this.database.closeSqlSession(this.session);
2244
+ }
2245
+ };
2246
+ // Annotate the CommonJS export names for ESM import in node:
2247
+ 0 && (module.exports = {
2248
+ AbiMismatchError,
2249
+ AntflyError,
2250
+ BusyError,
2251
+ CancelledError,
2252
+ Connection,
2253
+ Database,
2254
+ ErrorCode,
2255
+ GraphDirection,
2256
+ Inference,
2257
+ InferenceMode,
2258
+ IntentConflictError,
2259
+ InternalError,
2260
+ InvalidArgumentError,
2261
+ LibraryNotFoundError,
2262
+ MIN_THREAD_STACK_SIZE,
2263
+ NotFoundError,
2264
+ OpenMode,
2265
+ OutcomeUnknownError,
2266
+ Profile,
2267
+ SUPPORTED_ABI_VERSION,
2268
+ SqlError,
2269
+ StalledError,
2270
+ Storage,
2271
+ THREADING_SERIALIZED,
2272
+ TxnNotFoundError,
2273
+ TxnStatus,
2274
+ UnsupportedError,
2275
+ UnsupportedPlatformError,
2276
+ VersionConflictError,
2277
+ abiVersion,
2278
+ checkFile,
2279
+ checkFileRaw,
2280
+ copyStableSnapshotFile,
2281
+ copyStableSnapshotFileRaw,
2282
+ create,
2283
+ createHosted,
2284
+ createWithOptions,
2285
+ decodeArtifactId,
2286
+ decodeArtifactIdRaw,
2287
+ embeddedPlatformPackageName,
2288
+ errorCodeDescription,
2289
+ errorCodeName,
2290
+ open,
2291
+ openHosted,
2292
+ openReadonly,
2293
+ openStatusOnly,
2294
+ openWithOptions,
2295
+ platformLibraryFileName,
2296
+ resolveLibrary,
2297
+ restore,
2298
+ restoreFile,
2299
+ threadingMode,
2300
+ validateAbi,
2301
+ validateInferenceAbi
2302
+ });