@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/LICENSE +1 -1
- package/README.md +452 -4
- package/dist/chunk-ELM44XQ4.js +168 -0
- package/dist/database-D9gL3wnT.d.cts +585 -0
- package/dist/database-D9gL3wnT.d.ts +585 -0
- package/dist/index.cjs +2498 -0
- package/dist/index.d.cts +322 -0
- package/dist/index.d.ts +322 -0
- package/dist/index.js +2253 -0
- package/dist/kysely.cjs +346 -0
- package/dist/kysely.d.cts +28 -0
- package/dist/kysely.d.ts +28 -0
- package/dist/kysely.js +169 -0
- package/package.json +82 -10
package/LICENSE
CHANGED
|
@@ -187,7 +187,7 @@
|
|
|
187
187
|
same "printed page" as the copyright notice for easier
|
|
188
188
|
identification within third-party archives.
|
|
189
189
|
|
|
190
|
-
Copyright 2026 Antfly
|
|
190
|
+
Copyright 2026 Antfly, Inc.
|
|
191
191
|
|
|
192
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
193
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -1,7 +1,455 @@
|
|
|
1
1
|
# @antfly/embedded
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Node.js binding for embedded Antfly databases and inference -- the stable `libantfly` C ABI --
|
|
4
|
+
using [koffi](https://koffi.dev) for FFI (prebuilt binaries, no node-gyp).
|
|
5
|
+
Applications embed a live `.aflite` database directly in the Node process
|
|
6
|
+
instead of talking to the network SDK.
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
**Node-only.** This package uses koffi to load a native shared library and
|
|
9
|
+
does not work in browsers. Antfly Lite also ships a separate WebAssembly
|
|
10
|
+
build for browser use; this package is unrelated to that build.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @antfly/embedded
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Published platform packages include the Apache-2.0 `libantfly` library,
|
|
19
|
+
without installing CLI commands or an unused worker executable.
|
|
20
|
+
Prebuilt embedded packages support Linux x86-64 and ARM64 with glibc 2.28
|
|
21
|
+
or newer, and macOS ARM64. Windows, Intel macOS, and Alpine/musl do not
|
|
22
|
+
have prebuilt language packages. The native release archive matrix is
|
|
23
|
+
separate; a source build or native archive does not imply wheel/npm support.
|
|
24
|
+
Source checkouts
|
|
25
|
+
can build the shared library with "Library discovery" below. From the
|
|
26
|
+
`antfly` monorepo source tree, build it
|
|
27
|
+
with `cd zig && zig build libantfly` (produces `zig/zig-out/lib/libantfly.*`);
|
|
28
|
+
this package does not build it for you.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { create, THREADING_SERIALIZED, threadingMode } from "@antfly/embedded";
|
|
34
|
+
|
|
35
|
+
// `await using` calls Symbol.asyncDispose, which closes the handle.
|
|
36
|
+
await using db = await create("my.aflite");
|
|
37
|
+
|
|
38
|
+
await db.batch(
|
|
39
|
+
[{ key: "doc:1", value: { title: "hello", body: "world" } }],
|
|
40
|
+
BigInt(Date.now()) * 1_000_000n // nanoseconds
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
const doc = await db.lookup("doc:1"); // parsed JSON
|
|
44
|
+
const raw = await db.lookupRaw("doc:1"); // raw JSON bytes (Buffer)
|
|
45
|
+
|
|
46
|
+
const hits = await db.search({
|
|
47
|
+
full_text_search: { match: { field: "body", text: "world" } },
|
|
48
|
+
limit: 5,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
console.log(threadingMode() === THREADING_SERIALIZED); // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Without top-level `await using` support, call `close()` explicitly (ideally
|
|
55
|
+
in a `finally` block), or rely on the best-effort `FinalizationRegistry`
|
|
56
|
+
cleanup as a last resort.
|
|
57
|
+
|
|
58
|
+
## Async-first, thread-safe by design
|
|
59
|
+
|
|
60
|
+
Every operation that touches an open handle is **async** and runs on koffi's
|
|
61
|
+
native worker thread pool via `fn.async(...)`, so database work never blocks
|
|
62
|
+
the Node event loop and concurrent calls actually run in parallel. Only cheap
|
|
63
|
+
metadata calls that never touch a handle -- `abiVersion()`, `threadingMode()`,
|
|
64
|
+
`validateAbi()`, `errorCodeName()` / `errorCodeDescription()` -- are
|
|
65
|
+
synchronous.
|
|
66
|
+
|
|
67
|
+
`libantfly` runs in **serialized threading mode** (`antfly_threading_mode()`
|
|
68
|
+
== `THREADING_SERIALIZED`, like `sqlite3_threadsafe()`): any thread may call
|
|
69
|
+
any function on any handle concurrently. Reads (`lookup`, `search`, `scan`,
|
|
70
|
+
`stats`, ...) run in parallel with each other and with writes; writes on one
|
|
71
|
+
handle queue behind each other instead of failing with `BusyError`; and
|
|
72
|
+
schema/index/enrichment changes wait for in-flight calls. See
|
|
73
|
+
`zig/CAPI.md`'s "Thread Safety" section for the full contract. A `Database`
|
|
74
|
+
is safe to share across any number of concurrent async operations -- open one
|
|
75
|
+
handle per file, not one per call.
|
|
76
|
+
|
|
77
|
+
### koffi's worker thread pool size
|
|
78
|
+
|
|
79
|
+
koffi dispatches async calls through Node's native async-work queue, which
|
|
80
|
+
runs on **libuv's shared threadpool** (the same pool used by `fs`, `dns`,
|
|
81
|
+
`zlib`, and `crypto.pbkdf2`). Its default size is 4 threads
|
|
82
|
+
(`UV_THREADPOOL_SIZE`, max 1024). If your application needs more than 4
|
|
83
|
+
truly concurrent native calls in flight (across `@antfly/embedded` and any other
|
|
84
|
+
libuv-threadpool consumer), set `UV_THREADPOOL_SIZE` **before the Node
|
|
85
|
+
process starts** (it cannot be changed at runtime):
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
UV_THREADPOOL_SIZE=16 node app.js
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`koffi.config()` additionally controls per-call memory pool sizing
|
|
92
|
+
(`async_stack_size`, `async_heap_size`, `resident_async_pools`,
|
|
93
|
+
`max_async_calls`) but does not change the number of worker threads; the
|
|
94
|
+
defaults are sufficient for this binding since `antfly_buffer` outputs are a
|
|
95
|
+
small fixed-size struct (the pointed-to bytes are heap-allocated by
|
|
96
|
+
`libantfly`, not stack/heap-marshaled by koffi).
|
|
97
|
+
|
|
98
|
+
### Close semantics
|
|
99
|
+
|
|
100
|
+
`db.close()` is idempotent and safe to call concurrently. It:
|
|
101
|
+
|
|
102
|
+
1. Immediately rejects (with `InvalidArgumentError`) any new call made after
|
|
103
|
+
`close()` has started.
|
|
104
|
+
2. Waits for every call this binding has already dispatched (queued on
|
|
105
|
+
koffi's worker pool, or actively executing) to settle.
|
|
106
|
+
3. Only then calls the native `antfly_db_close`, and marks the handle closed.
|
|
107
|
+
|
|
108
|
+
This extra bookkeeping exists because `antfly_db_close` only drains C calls
|
|
109
|
+
that have already **entered** the library; a koffi async call can be queued
|
|
110
|
+
on the libuv threadpool but not yet dequeued ("entered") when `close()`
|
|
111
|
+
starts. Freeing the handle while such a call is still queued would be a
|
|
112
|
+
use-after-free once that call finally runs. `@antfly/embedded` tracks its own
|
|
113
|
+
in-flight promises (comparable to the Go binding's `sync.RWMutex` held around
|
|
114
|
+
every call, exclusively in `Close`) so this can never happen.
|
|
115
|
+
|
|
116
|
+
`await using` (`Symbol.asyncDispose`) calls `close()` for you. A
|
|
117
|
+
`FinalizationRegistry` also closes the handle as a best-effort fallback if a
|
|
118
|
+
`Database` is garbage-collected without an explicit `close()` -- do not rely
|
|
119
|
+
on this for anything but leak mitigation; it is not deterministic.
|
|
120
|
+
|
|
121
|
+
## Library discovery
|
|
122
|
+
|
|
123
|
+
`@antfly/embedded` resolves the `libantfly` shared library in this order:
|
|
124
|
+
|
|
125
|
+
1. **`ANTFLY_LIBRARY`** environment variable -- an exact file path. Throws if
|
|
126
|
+
the file does not exist (fails loudly rather than silently falling
|
|
127
|
+
through).
|
|
128
|
+
2. **`ANTFLY_LIB_DIR`** environment variable -- a directory expected to
|
|
129
|
+
contain the platform library file (see below). Throws if the file is
|
|
130
|
+
missing from that directory.
|
|
131
|
+
3. The installed Apache **`@antfly/embedded-<platform>`** package's `lib/` directory,
|
|
132
|
+
resolved via `require.resolve`.
|
|
133
|
+
4. **`zig/zig-out/lib/`** found by walking up from this package's own
|
|
134
|
+
directory -- for running against a local `antfly` monorepo source
|
|
135
|
+
checkout.
|
|
136
|
+
5. The bare **system loader name**, resolved by the OS's normal shared
|
|
137
|
+
library search path (`LD_LIBRARY_PATH` / `DYLD_LIBRARY_PATH` / `PATH` /
|
|
138
|
+
rpath), matching the Go binding's fallback.
|
|
139
|
+
|
|
140
|
+
Platform file names: `libantfly.dylib` (macOS), `libantfly.so` (Linux),
|
|
141
|
+
`antfly.dll` (Windows).
|
|
142
|
+
|
|
143
|
+
Call `resolveLibrary()` yourself to see which tier resolved and why, without
|
|
144
|
+
loading the library.
|
|
145
|
+
|
|
146
|
+
### Embedded inference
|
|
147
|
+
|
|
148
|
+
`libantfly` runs inference **in-process**, in the calling process, on every
|
|
149
|
+
backend -- Metal, CUDA, ONNX, and CPU alike -- for both `Database` (with
|
|
150
|
+
`localRuntimeConfigured: true`) and the standalone `Inference` handle below.
|
|
151
|
+
There is no separate worker process and no `ANTFLY_INFERENCE_WORKER`
|
|
152
|
+
variable to configure. This is the trade SQLite makes for extensions that
|
|
153
|
+
touch a GPU driver: a call that reaches the device or driver has no per-call
|
|
154
|
+
abort, so `callTimeoutMs` and `close()` only take effect once the call
|
|
155
|
+
returns, and a driver fault terminates the process. Calls on CPU backends
|
|
156
|
+
still stop cooperatively. (The `antfly` server instead runs these backends
|
|
157
|
+
in a worker process it can kill and restart; a library cannot do that to its
|
|
158
|
+
host program.) See `zig/CAPI.md`'s "Inference In Process" section for the
|
|
159
|
+
full rationale.
|
|
160
|
+
|
|
161
|
+
### `Inference`: embedded inference without a database
|
|
162
|
+
|
|
163
|
+
`Inference.open(options?)` starts the embedded inference runtime with no
|
|
164
|
+
database attached -- models load on first use and stay cached until
|
|
165
|
+
`close()`. Each call sends the request JSON and returns the response JSON of
|
|
166
|
+
the matching `/ai/v1` route of the Antfly inference HTTP API
|
|
167
|
+
(`specs/openapi/inference/api.yaml`):
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
import { Inference } from "@antfly/embedded";
|
|
171
|
+
|
|
172
|
+
const inf = await Inference.open({ modelsDir: "/path/to/models" });
|
|
173
|
+
try {
|
|
174
|
+
const { data } = (await inf.chunk({
|
|
175
|
+
input: "Ants live in colonies. Workers gather food.",
|
|
176
|
+
})) as { data: unknown[] };
|
|
177
|
+
|
|
178
|
+
const embeddings = await inf.embed({ model: "owner/name", input: ["hello"] });
|
|
179
|
+
} finally {
|
|
180
|
+
await inf.close();
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
For decision question types and examples, see the
|
|
185
|
+
[typed decision guide](../../../docs/guides/decisions.md).
|
|
186
|
+
|
|
187
|
+
- **Calls**: `embed`, `rerank`, `chunk`, `generate`, `generateBatch`,
|
|
188
|
+
`rewrite`, `decide`, `extract`, `read` (OCR), `transcribe`, `listModels` -- each with
|
|
189
|
+
a bare form (parsed JSON) and a `...Raw` form (raw `Buffer`), following the
|
|
190
|
+
same convention as `Database`. Binary inputs (images, audio) go inline in
|
|
191
|
+
the request JSON, as base64 or `data:` URIs. Responses are always
|
|
192
|
+
complete: a `generate` request with `"stream": true` rejects with
|
|
193
|
+
`InvalidArgumentError` -- use `generateStream()` to stream.
|
|
194
|
+
- **Errors**: every failed inference call still gets a JSON error body from
|
|
195
|
+
`libantfly` (`{"error": ..., "message": ...}`); this binding folds it into
|
|
196
|
+
the thrown `AntflyError`'s message and exposes the parsed body as
|
|
197
|
+
`.body`, in addition to the usual `.code`/`.codeName`. A model that is not
|
|
198
|
+
installed rejects with `NotFoundError` (`.body.error === "MODEL_NOT_FOUND"`).
|
|
199
|
+
- **`generateStream(request, onChunk)`** streams a generate request (the
|
|
200
|
+
same body as `generate()`, with `"stream"` set for you). `onChunk` is
|
|
201
|
+
called **synchronously, on the calling thread**, once per streamed chunk
|
|
202
|
+
(a parsed `chat.completion.chunk` JSON object). Returning `false` from
|
|
203
|
+
`onChunk` stops generation early and the call rejects with
|
|
204
|
+
`CancelledError`; a thrown error also stops generation and is rethrown.
|
|
205
|
+
Like `pull()` below, `generateStream()` runs synchronously and blocks the
|
|
206
|
+
Node event loop for its duration -- the same koffi callback-threading
|
|
207
|
+
constraint applies, which is why this binding exposes a callback rather
|
|
208
|
+
than an async iterator (an async iterator would need the call running off
|
|
209
|
+
the JS thread, which a koffi callback cannot do safely). `generateStreamRaw`
|
|
210
|
+
gives `onChunk` the raw per-chunk `Buffer` instead of parsed JSON.
|
|
211
|
+
- **`pull(request, onProgress?, signal?)`** downloads a model from the
|
|
212
|
+
Hugging Face Hub into the handle's models directory, like
|
|
213
|
+
`antfly inference pull`: `{ model: "owner/name[:variant]", variants?,
|
|
214
|
+
token?, tasks?, capabilities?, projector?, maxArtifactBytes?,
|
|
215
|
+
maxModelBytes? }` (as request JSON; field names follow the HTTP API, e.g.
|
|
216
|
+
`"model"`). The optional `onProgress` callback is called synchronously, on
|
|
217
|
+
the calling thread, as each file starts, every 16 MiB, and as it
|
|
218
|
+
completes. Returning `false` from `onProgress` cancels the pull -- the
|
|
219
|
+
call then rejects with `CancelledError`, and completed files stay staged,
|
|
220
|
+
so a later `pull()` for the same model resumes rather than restarts; a
|
|
221
|
+
thrown error also cancels the pull and is rethrown. The optional `signal`
|
|
222
|
+
(`AbortSignal`) is a best-effort, honestly-limited convenience on top of
|
|
223
|
+
that: because `pull()` blocks the JS thread for its whole duration, there
|
|
224
|
+
is no way to interrupt it asynchronously the way `fetch(url, { signal })`
|
|
225
|
+
can. An already-aborted signal rejects before the pull starts; otherwise
|
|
226
|
+
it is only checked at the same report points as `onProgress` -- prefer
|
|
227
|
+
returning `false` from `onProgress` when you need precise control.
|
|
228
|
+
Unlike every other `Inference`/`Database` call, **`pull()` runs
|
|
229
|
+
synchronously and blocks the Node event loop** for its duration -- this is
|
|
230
|
+
intentional: JS execution is single-threaded, and a callback koffi
|
|
231
|
+
delivers from a background thread (as happens for a call dispatched via
|
|
232
|
+
`fn.async(...)`, which runs on koffi's worker thread pool) has to be
|
|
233
|
+
queued back onto the JS main thread rather than invoked as a true
|
|
234
|
+
blocking round-trip; per koffi's docs that queuing only runs "as soon as
|
|
235
|
+
the event loop has a chance to run", which could reorder or delay a
|
|
236
|
+
report arbitrarily relative to the (already-freed) native data it points
|
|
237
|
+
to, or even deadlock. Calling synchronously keeps the whole call,
|
|
238
|
+
including every callback invocation, on one OS thread throughout,
|
|
239
|
+
matching the C API's "called on the calling thread" guarantee exactly.
|
|
240
|
+
`close()` waits for a pull in progress.
|
|
241
|
+
- **Options**: `InferenceOptions` -- `modelsDir` (defaults to
|
|
242
|
+
`$ANTFLY_INFERENCE_MODELS_DIR`, else `~/.antfly/inference/models`),
|
|
243
|
+
the same `*BudgetMb` resource knobs as `Database`'s `OpenOptions`, and
|
|
244
|
+
`callTimeoutMs` (a deadline per call; 0 means none).
|
|
245
|
+
- **Lifecycle**: `close()` is idempotent, safe to call concurrently, and
|
|
246
|
+
waits for in-flight calls; `Inference` implements `AsyncDisposable`
|
|
247
|
+
(`await using`), same as `Database`.
|
|
248
|
+
|
|
249
|
+
## ABI validation
|
|
250
|
+
|
|
251
|
+
`validateAbi()` checks that the loaded library's `antfly_abi_version()`
|
|
252
|
+
(expected: 2) and `antfly_open_options` struct size match what this binding
|
|
253
|
+
was compiled against, throwing `AbiMismatchError` otherwise. It runs
|
|
254
|
+
automatically before every open/create call and before `checkFile()`; call
|
|
255
|
+
it yourself at startup to fail fast.
|
|
256
|
+
|
|
257
|
+
## Storage kinds
|
|
258
|
+
|
|
259
|
+
Every open/create call accepts `storage` (`Storage.Lite`, the default, or
|
|
260
|
+
`Storage.Directory`) via `OpenOptions.storage`:
|
|
261
|
+
|
|
262
|
+
- `Storage.Lite` -- a single-file `.aflite` database (this package's usual
|
|
263
|
+
use case).
|
|
264
|
+
- `Storage.Directory` -- a normal single-node Antfly directory. Directory
|
|
265
|
+
storage is created by opening a missing path with `open`/`openWithOptions`;
|
|
266
|
+
`create`/`createWithOptions` only create `.aflite` files.
|
|
267
|
+
|
|
268
|
+
A portable `.afb` backup (`backup()`) round-trips across storage kinds: it
|
|
269
|
+
restores into either kind with the module-level `restore`/`restoreFile`, and
|
|
270
|
+
imports into an *empty* database of either kind with `importBackup()`.
|
|
271
|
+
`restore(path, backup, { storage, replace })` and
|
|
272
|
+
`restoreFile(path, backupPath, { storage, replace })` select the destination
|
|
273
|
+
kind with `storage` (default `Storage.Lite`); the `.aflite` suffix is only
|
|
274
|
+
required client-side when the destination is `Storage.Lite`.
|
|
275
|
+
|
|
276
|
+
## JSON conventions
|
|
277
|
+
|
|
278
|
+
Every request parameter that accepts a JSON body (`request`, `config`,
|
|
279
|
+
`schema`, ...) accepts a plain object (JSON.stringify'd), a JSON string, or
|
|
280
|
+
raw UTF-8 bytes (`Buffer` / `Uint8Array`).
|
|
281
|
+
|
|
282
|
+
Every JSON-returning operation has two forms:
|
|
283
|
+
|
|
284
|
+
- The bare name (e.g. `lookup`, `search`, `status`) returns **parsed JSON**
|
|
285
|
+
(typed as `unknown`, or a specific interface for `Status` /
|
|
286
|
+
`Capabilities` / the maintenance reports).
|
|
287
|
+
- The `...Raw` suffix (e.g. `lookupRaw`, `searchRaw`, `statusRaw`) returns
|
|
288
|
+
the **raw JSON bytes** as a `Buffer`, skipping the parse.
|
|
289
|
+
|
|
290
|
+
The packed **wire** searches (`denseSearchWire`, `textMatchWire`,
|
|
291
|
+
`textTermWire`, `textMatchPhraseWire`) are a different, non-JSON binary
|
|
292
|
+
format matching the server's wire protocol; they always take and return raw
|
|
293
|
+
bytes (`Buffer` / `Uint8Array`), never JSON.
|
|
294
|
+
|
|
295
|
+
`getRaw(key)` is the one exception to the naming scheme above: it mirrors
|
|
296
|
+
`antfly_db_get_raw` / the Go binding's `Raw(key)`, returning the document's
|
|
297
|
+
raw stored bytes (not JSON at all, since a document need not be JSON at the
|
|
298
|
+
storage layer).
|
|
299
|
+
|
|
300
|
+
Timestamps and versions that are `uint64_t` in the C ABI (`timestampNs`,
|
|
301
|
+
`expectedVersion`, `commitVersion`, `busyTimeoutMs`, ...) accept both
|
|
302
|
+
`number` and `bigint`; use `bigint` where precision matters; a nanosecond
|
|
303
|
+
Unix timestamp exceeds `Number.MAX_SAFE_INTEGER`, so `commitVersion()`
|
|
304
|
+
always returns `bigint`.
|
|
305
|
+
|
|
306
|
+
## Errors
|
|
307
|
+
|
|
308
|
+
Every failed call rejects with an `AntflyError` subclass carrying:
|
|
309
|
+
|
|
310
|
+
- `.code` -- the numeric `antfly_error_code`.
|
|
311
|
+
- `.codeName` -- the stable symbolic name, e.g. `"ANTFLY_BUSY"`, matching
|
|
312
|
+
`antfly_error_code_name()`.
|
|
313
|
+
- `.message` -- built from `antfly_error_code_description()`.
|
|
314
|
+
|
|
315
|
+
Subclasses: `InvalidArgumentError` (1), `NotFoundError` (2),
|
|
316
|
+
`VersionConflictError` (3), `IntentConflictError` (4), `TxnNotFoundError` (5),
|
|
317
|
+
`BusyError` (6), `OutcomeUnknownError` (7, not safe to retry automatically --
|
|
318
|
+
publication may have succeeded but crash durability could not be confirmed),
|
|
319
|
+
`UnsupportedError` (8, not transient), `StalledError` (9, a bounded drain
|
|
320
|
+
like `runUntilIdle` made no progress and gave up), `CancelledError` (10, the
|
|
321
|
+
caller returned `false` from an `Inference.pull()` `onProgress` or
|
|
322
|
+
`Inference.generateStream()` `onChunk` callback -- a callback that throws
|
|
323
|
+
instead stops the operation the same way, but rejects with the thrown error
|
|
324
|
+
itself, not `CancelledError`), `InternalError` (255).
|
|
325
|
+
|
|
326
|
+
## API surface
|
|
327
|
+
|
|
328
|
+
Mirrors `go/pkg/embedded`'s surface idiomatically:
|
|
329
|
+
|
|
330
|
+
- **Open/create**: `create`, `open`, `openReadonly`, `openStatusOnly`,
|
|
331
|
+
`openHosted`, `createHosted`, `openWithOptions`, `createWithOptions`, plus
|
|
332
|
+
`OpenOptions` (including `storage`), `Storage`, `OpenMode`, `Profile`,
|
|
333
|
+
`TxnStatus`, `GraphDirection`, `InferenceMode`, `THREADING_SERIALIZED`.
|
|
334
|
+
- **`Database`**: `close()`, `[Symbol.asyncDispose]`; `batch`/`batchJson`;
|
|
335
|
+
`lookup`/`lookupRaw`/`getRaw`; `scan`/`search`/`stats`; `status`,
|
|
336
|
+
`capabilities`, `check`, `pendingWorkStats`, `runUntilIdle` /
|
|
337
|
+
`runUntilIdleStatus`, `replayGeneratedEnrichments`; `getSchema`/
|
|
338
|
+
`setSchema`; `listIndexes`/`addIndex`/`deleteIndex` (returns `boolean`);
|
|
339
|
+
`listEnrichments`/`addEnrichment`/`deleteEnrichment`; graph
|
|
340
|
+
(`edges`/`neighbors`/`traverseEdges`/`executeGraphQueries`/
|
|
341
|
+
`findShortestPath`/`findKShortestPaths`/`matchPattern`); wire searches
|
|
342
|
+
(`denseSearchWire`/`textMatchWire`/`textTermWire`/`textMatchPhraseWire`);
|
|
343
|
+
`aggregateHits`, `lookupArtifact`; `extractEnrichments`/
|
|
344
|
+
`computeEnrichments`; transactions (`beginTransaction`/`writeTransaction`/
|
|
345
|
+
`resolveTransaction`/`transactionStatus`/`commitVersion` -- 16-byte
|
|
346
|
+
transaction ids accepted as a `Uint8Array(16)` or a 32-char hex string);
|
|
347
|
+
`backup`/`importBackup`, `backupToFile`; `compact`/`vacuum`/
|
|
348
|
+
`copyStableSnapshot`.
|
|
349
|
+
- **Module-level**: `checkFile`, `restore`/`restoreFile` (both take
|
|
350
|
+
`RestoreOptions` -- `{ storage, replace }`), `copyStableSnapshotFile`,
|
|
351
|
+
`decodeArtifactId`, `abiVersion`, `threadingMode`, `validateAbi`.
|
|
352
|
+
- **`Inference`**: `Inference.open(options?)`, `close()`,
|
|
353
|
+
`[Symbol.asyncDispose]`; `embed`/`rerank`/`chunk`/`generate`/
|
|
354
|
+
`generateBatch`/`rewrite`/`extract`/`read`/`transcribe`/`listModels`
|
|
355
|
+
(each with a `...Raw` form); `generateStream(request, onChunk)` /
|
|
356
|
+
`generateStreamRaw`; `pull(request, onProgress?, signal?)`; plus
|
|
357
|
+
`InferenceOptions`, `PullProgress`, `CancelledError`,
|
|
358
|
+
`validateInferenceAbi`. See "Embedded inference" above.
|
|
359
|
+
|
|
360
|
+
See `src/index.ts` for the full export list and `src/types.ts` for typed
|
|
361
|
+
`Status` / `Capabilities` / report interfaces.
|
|
362
|
+
|
|
363
|
+
## Testing
|
|
364
|
+
|
|
365
|
+
```bash
|
|
366
|
+
pnpm run typecheck
|
|
367
|
+
pnpm run lint
|
|
368
|
+
pnpm run build
|
|
369
|
+
pnpm run test # skips native-library tests cleanly if libantfly isn't found
|
|
370
|
+
ANTFLY_LITE_REQUIRE_LIBRARY=1 pnpm run test # fails instead of skipping if libantfly isn't found
|
|
371
|
+
ANTFLY_LIBRARY=/nonexistent pnpm run test # exercises the clean-skip path directly
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
`test/conformance.test.ts` runs every case under
|
|
375
|
+
`zig/pkg/antfly-embedded/capi-conformance/cases/*.json` through this public API,
|
|
376
|
+
mirroring `go/pkg/embedded/conformance_cgo_test.go`'s semantics, including the
|
|
377
|
+
`storage`-typed opens and the `import_backup`/`restore_open` cross-storage
|
|
378
|
+
cases. `test/storage.test.ts` adds coverage beyond conformance: restoring a
|
|
379
|
+
`.aflite` backup into directory storage and reopening it. `test/
|
|
380
|
+
concurrency.test.ts` covers mixed concurrent operations, `close()` racing
|
|
381
|
+
in-flight calls, `busyTimeoutMs` behavior, and that concurrent searches
|
|
382
|
+
overlap instead of serializing on the event loop. `test/errors.test.ts` and
|
|
383
|
+
`test/discovery.test.ts` include pure tests that need no native library at
|
|
384
|
+
all. `test/package.test.ts` builds and packs the package, then verifies CommonJS
|
|
385
|
+
and ESM discovery in isolated Node processes outside a checkout. It checks all
|
|
386
|
+
three platform packages and package-relative source discovery in installation
|
|
387
|
+
paths containing spaces, `#`, and `?`, without loading the fixture libraries. `test/inference.test.ts` covers the `Inference` handle: open/close,
|
|
388
|
+
calls that need no model (`chunk`, `listModels`), missing-model
|
|
389
|
+
`NotFoundError` for both `embed` and `generateStream`, `pull({})`/
|
|
390
|
+
streaming-`generate`/malformed-JSON-`generateStream` `InvalidArgumentError`
|
|
391
|
+
cases, an optional real-embedding test gated on a locally installed Qwen
|
|
392
|
+
model, an optional `generateStream` test gated on a locally installed Gemma
|
|
393
|
+
generate model (`~/.antfly/inference/models/ggml-org/gemma-4-e2b-it-gguf*`)
|
|
394
|
+
covering both a normal multi-chunk stream and cancelling after two chunks
|
|
395
|
+
(`CancelledError`, exactly two `onChunk` calls), and a network-gated
|
|
396
|
+
`pull()` test (`ANTFLY_INFERENCE_PULL_TEST_MODEL`, e.g.
|
|
397
|
+
`sparse-encoder-testing/splade-bert-tiny-nq-onnx`) that cancels on the first
|
|
398
|
+
progress report (`CancelledError`, model still absent from `listModels()`),
|
|
399
|
+
then pulls the same model to completion with progress callbacks.
|
|
400
|
+
|
|
401
|
+
## License
|
|
402
|
+
|
|
403
|
+
Apache-2.0
|
|
404
|
+
|
|
405
|
+
## SQL, Kysely, and multiple tables
|
|
406
|
+
|
|
407
|
+
`Connection` provides a promise-based SQL session over a `Database`:
|
|
408
|
+
|
|
409
|
+
```ts
|
|
410
|
+
import { create, Connection } from "@antfly/embedded";
|
|
411
|
+
const database = await create("app.aflite");
|
|
412
|
+
const connection = await Connection.open(database);
|
|
413
|
+
await connection.execute("CREATE TABLE people (id BIGINT PRIMARY KEY, name TEXT)");
|
|
414
|
+
await connection.transaction(async tx => {
|
|
415
|
+
await tx.execute("INSERT INTO people (id,name) VALUES ($1,$2)", [1n, "Ada"]);
|
|
416
|
+
});
|
|
417
|
+
const result = await connection.query("SELECT id,name FROM people");
|
|
418
|
+
for await (const page of connection.stream("SELECT id,name FROM people", [], 128)) {
|
|
419
|
+
console.log(page.rows);
|
|
420
|
+
}
|
|
421
|
+
await connection.close();
|
|
422
|
+
await database.close();
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
`query` reads all native cursor pages; `stream` yields bounded pages. Integer
|
|
426
|
+
columns use `bigint`, SQL NULL uses `null`, and JSON uses JavaScript values.
|
|
427
|
+
Use bigint parameters when values exceed JavaScript's safe integer range.
|
|
428
|
+
Errors carry `sqlstate` and an optional `transactionId`.
|
|
429
|
+
|
|
430
|
+
Install Kysely 0.29 and import the optional dialect subpath:
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
import { Kysely } from "kysely";
|
|
434
|
+
import { AntflyDialect } from "@antfly/embedded/kysely";
|
|
435
|
+
const sql = new Kysely<{ people: { id: bigint; name: string } }>({
|
|
436
|
+
dialect: new AntflyDialect({ database }),
|
|
437
|
+
});
|
|
438
|
+
const people = await sql.selectFrom("people").selectAll().execute();
|
|
439
|
+
await sql.destroy(); // The caller still owns database.
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
`createTable`, `listTables`, `openTable`, and `dropTable` expose the shared
|
|
443
|
+
document catalog. Table handles reuse existing schema, index, enrichment,
|
|
444
|
+
search, and document methods. Close them before dropping their tables;
|
|
445
|
+
database close invalidates them.
|
|
446
|
+
|
|
447
|
+
Portable `.afb` archives back up the entire database: its table catalog,
|
|
448
|
+
schemas, documents, indexes, enrichments, and constraint records. Call backup
|
|
449
|
+
on the database handle. Restore publishes all tables together into either
|
|
450
|
+
Lite or directory storage; import requires an empty database with no open
|
|
451
|
+
table handles, SQL sessions, or cursors. Table handles cannot export or import
|
|
452
|
+
backups.
|
|
453
|
+
|
|
454
|
+
See [the native SQL contract](../../../zig/CAPI.md#database-sql) for
|
|
455
|
+
READ COMMITTED, savepoints, transactional DDL restrictions, and commit outcomes.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// ../../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/esm_shims.js
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
var getFilename = () => fileURLToPath(import.meta.url);
|
|
5
|
+
var __filename = /* @__PURE__ */ getFilename();
|
|
6
|
+
|
|
7
|
+
// src/sql-types.ts
|
|
8
|
+
var SqlError = class extends Error {
|
|
9
|
+
constructor(diagnostic, transactionId) {
|
|
10
|
+
super(`${diagnostic.code}: ${diagnostic.message}`);
|
|
11
|
+
this.diagnostic = diagnostic;
|
|
12
|
+
this.transactionId = transactionId;
|
|
13
|
+
this.name = "SqlError";
|
|
14
|
+
this.sqlstate = diagnostic.code;
|
|
15
|
+
}
|
|
16
|
+
diagnostic;
|
|
17
|
+
transactionId;
|
|
18
|
+
sqlstate;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// src/sql.ts
|
|
22
|
+
function request(statement, parameters, session, streaming = false) {
|
|
23
|
+
return JSON.stringify(
|
|
24
|
+
{ statement, parameters, session_id: session, limit: streaming ? void 0 : 4096 },
|
|
25
|
+
(_key, value) => {
|
|
26
|
+
if (typeof value === "bigint") {
|
|
27
|
+
if (value < -(1n << 63n) || value >= 1n << 63n)
|
|
28
|
+
throw new RangeError("integer parameter is outside the signed 64-bit range");
|
|
29
|
+
return value.toString();
|
|
30
|
+
}
|
|
31
|
+
if (typeof value === "number" && (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)))
|
|
32
|
+
throw new RangeError("use bigint for integer parameters outside JavaScript's safe range");
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
function result(wire) {
|
|
38
|
+
return {
|
|
39
|
+
columns: wire.columns,
|
|
40
|
+
commandTag: wire.command_tag,
|
|
41
|
+
rowsAffected: BigInt(wire.rows_affected),
|
|
42
|
+
rows: wire.rows.map(
|
|
43
|
+
(row, rowIndex) => Object.fromEntries(
|
|
44
|
+
wire.columns.map((column, index) => [
|
|
45
|
+
column.name,
|
|
46
|
+
wire.sql_nulls?.[rowIndex]?.[index] ? null : column.type === "integer" && row[index] !== null ? BigInt(row[index]) : row[index]
|
|
47
|
+
])
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
var Connection = class _Connection {
|
|
53
|
+
constructor(database, session, direct = false) {
|
|
54
|
+
this.database = database;
|
|
55
|
+
this.session = session;
|
|
56
|
+
this.direct = direct;
|
|
57
|
+
}
|
|
58
|
+
database;
|
|
59
|
+
session;
|
|
60
|
+
direct;
|
|
61
|
+
#pending = Promise.resolve();
|
|
62
|
+
#closed = false;
|
|
63
|
+
static async open(database) {
|
|
64
|
+
return new _Connection(database, await database.openSqlSession());
|
|
65
|
+
}
|
|
66
|
+
#run(operation) {
|
|
67
|
+
if (this.#closed) return Promise.reject(new Error("SQL connection is closed"));
|
|
68
|
+
if (this.direct) return operation();
|
|
69
|
+
const work = this.#pending.then(operation);
|
|
70
|
+
this.#pending = work.catch(() => void 0);
|
|
71
|
+
return work;
|
|
72
|
+
}
|
|
73
|
+
execute(statement, parameters = []) {
|
|
74
|
+
return this.#run(
|
|
75
|
+
async () => result(
|
|
76
|
+
await this.database.sqlJson(request(statement, parameters, this.session))
|
|
77
|
+
)
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
query(statement, parameters = []) {
|
|
81
|
+
return this.#run(async () => {
|
|
82
|
+
let cursor;
|
|
83
|
+
try {
|
|
84
|
+
cursor = await this.database.openSqlCursor(
|
|
85
|
+
request(statement, parameters, this.session, true)
|
|
86
|
+
);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (!(error instanceof SqlError) || error.sqlstate !== "0A000") throw error;
|
|
89
|
+
return result(
|
|
90
|
+
await this.database.sqlJson(request(statement, parameters, this.session))
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
let output;
|
|
94
|
+
try {
|
|
95
|
+
while (true) {
|
|
96
|
+
const page = await this.database.fetchSqlCursor(cursor);
|
|
97
|
+
const decoded = result(page.result);
|
|
98
|
+
if (output) output.rows.push(...decoded.rows);
|
|
99
|
+
else output = decoded;
|
|
100
|
+
if (page.exhausted) return output;
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
await this.database.closeSqlCursor(cursor);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
async *stream(statement, parameters = [], chunkSize = 128) {
|
|
108
|
+
if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > 4096)
|
|
109
|
+
throw new RangeError("chunkSize must be 1..4096");
|
|
110
|
+
if (this.#closed) throw new Error("SQL connection is closed");
|
|
111
|
+
const previous = this.#pending;
|
|
112
|
+
let release = () => {
|
|
113
|
+
};
|
|
114
|
+
if (!this.direct)
|
|
115
|
+
this.#pending = new Promise((resolve) => {
|
|
116
|
+
release = resolve;
|
|
117
|
+
});
|
|
118
|
+
await previous;
|
|
119
|
+
let cursor;
|
|
120
|
+
try {
|
|
121
|
+
cursor = await this.database.openSqlCursor(
|
|
122
|
+
request(statement, parameters, this.session, true)
|
|
123
|
+
);
|
|
124
|
+
while (true) {
|
|
125
|
+
const page = await this.database.fetchSqlCursor(cursor, chunkSize);
|
|
126
|
+
yield result(page.result);
|
|
127
|
+
if (page.exhausted) break;
|
|
128
|
+
}
|
|
129
|
+
} finally {
|
|
130
|
+
try {
|
|
131
|
+
if (cursor !== void 0) await this.database.closeSqlCursor(cursor);
|
|
132
|
+
} finally {
|
|
133
|
+
release();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
transaction(operation) {
|
|
138
|
+
return this.#run(async () => {
|
|
139
|
+
const transaction = new _Connection(this.database, this.session, true);
|
|
140
|
+
await transaction.execute("BEGIN ISOLATION LEVEL READ COMMITTED");
|
|
141
|
+
try {
|
|
142
|
+
const value = await operation(transaction);
|
|
143
|
+
await transaction.execute("COMMIT");
|
|
144
|
+
return value;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
try {
|
|
147
|
+
await transaction.execute("ROLLBACK");
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
throw error;
|
|
151
|
+
} finally {
|
|
152
|
+
transaction.#closed = true;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
async close() {
|
|
157
|
+
if (this.#closed) return;
|
|
158
|
+
this.#closed = true;
|
|
159
|
+
await this.#pending;
|
|
160
|
+
await this.database.closeSqlSession(this.session);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
export {
|
|
165
|
+
__filename,
|
|
166
|
+
SqlError,
|
|
167
|
+
Connection
|
|
168
|
+
};
|