@antfly/embedded 0.0.0 → 0.3.0-rc.4

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