@hakodb/client 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -1,1627 +1,1627 @@
1
- import { loadNativeBindings, type NativeBindings, type WatchCallback } from './native';
2
-
3
- // 1. UPDATED: Recursive Type Definitions to support Nested Maps and Arrays
4
- // export type Primitive = string | number | boolean | null | Uint8Array | Date | HakoDocData | Array<any>;
5
- export type Primitive =
6
- | string
7
- | number
8
- | boolean
9
- | null
10
- | Uint8Array
11
- | Date
12
- | HakoReference
13
- | { [key: string]: Primitive }
14
- | Primitive[];
15
-
16
-
17
- export type HakoDocData = { [key: string]: Primitive };
18
-
19
- /** Distance metric for vector indexes (matches core Metric::from_u32). */
20
- export type VectorMetric = 'cosine' | 'l2';
21
-
22
- /** One KNN hit: doc id, exact metric distance, and the doc itself. */
23
- export interface NearHit {
24
- id: string;
25
- score: number;
26
- doc: HakoDocData;
27
- }
28
-
29
- /** Traversal direction (matches core TraverseDir::from_u32). */
30
- export type TraverseDirection = 'outgoing' | 'incoming' | 'both';
31
-
32
- /** One graph hit: collection + id (paths cross collections), BFS depth, doc. */
33
- export interface PathHit {
34
- collection: string;
35
- id: string;
36
- depth: number;
37
- cost?: number;
38
- doc: HakoDocData;
39
- /** Route projections, only present when opted in via PathOptions. */
40
- path?: string[];
41
- /** Edge docs as JSON strings; null for anonymous edges. */
42
- via?: (string | null)[];
43
- }
44
-
45
- /** A predicate: docs whose `field` equals `equals` travel (or stop). */
46
- export interface PathFilter {
47
- field: string;
48
- equals: unknown;
49
- }
50
-
51
- /** v0.19 traverse extensions shared by findPathsFull/shortestPathsFull/exportGraph/graphAnalysis. */
52
- export interface PathOptions {
53
- direction?: TraverseDirection;
54
- edge?: string | null;
55
- via?: string | null;
56
- maxDepth?: number;
57
- k?: number;
58
- includePath?: boolean;
59
- includeVia?: boolean;
60
- nodeFilter?: PathFilter;
61
- edgeType?: PathFilter;
62
- edgeMatch?: PathFilter;
63
- /** Shortest paths only: numeric prop name on edge docs (null = uniform 1.0). */
64
- weight?: string | null;
65
- }
66
-
67
- function resolvePathOptions(opts: PathOptions) {
68
- const f = (p?: PathFilter) => (p ? { field: p.field, json: JSON.stringify(p.equals ?? null) } : { field: null, json: null });
69
- const node = f(opts.nodeFilter);
70
- const type = f(opts.edgeType);
71
- const match = f(opts.edgeMatch);
72
- return {
73
- direction: opts.direction === 'incoming' ? 1 : opts.direction === 'both' ? 2 : 0,
74
- edge: opts.edge ?? null,
75
- via: opts.via ?? null,
76
- maxDepth: opts.maxDepth ?? 10,
77
- k: opts.k ?? 100,
78
- includePath: opts.includePath ?? false,
79
- includeVia: opts.includeVia ?? false,
80
- nodeField: node.field,
81
- nodeJSON: node.json,
82
- typeField: type.field,
83
- typeJSON: type.json,
84
- matchField: match.field,
85
- matchJSON: match.json,
86
- weight: opts.weight ?? null,
87
- };
88
- }
89
-
90
- const SERVER_TIMESTAMP_SENTINEL = "__FL_SERVER_TIMESTAMP__";
91
-
92
- export class HakoReference {
93
- constructor(public readonly collection: string, public readonly id: string) {}
94
- }
95
-
96
- export enum DurabilityMode {
97
- Always = 0,
98
- Interval = 1,
99
- Manual = 2,
100
- OnCommit = 3,
101
- }
102
-
103
- export enum CloudSyncMode {
104
- Server = 0,
105
- Client = 1,
106
- }
107
-
108
- export interface HakoClientOptions {
109
- libraryPath?: string;
110
- native?: NativeBindings;
111
- config?: HakoConfig;
112
- }
113
-
114
- // 2. FIXED: Added 'in' to the interface to match the Query class
115
- export interface QueryConstraint {
116
- field: string;
117
- op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any' | 'elemMatch' | 'arrayAllEq';
118
- value: any; // Use any because 'in' takes an array
119
- }
120
-
121
- /** One element-relative predicate for whereElemMatch (F3). */
122
- export interface ElemFilter {
123
- field: string;
124
- op: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'match' | 'match_prefix' | 'contains' | 'starts_with' | 'in' | 'not_in' | 'array_contains' | 'array_contains_any' | 'array_all_eq';
125
- value: unknown;
126
- }
127
-
128
- export interface QueryOrder {
129
- field: string;
130
- ascending: boolean;
131
- }
132
-
133
- /** One declared field rule (F8). Kind names match the core wire format. */
134
- export interface HakoFieldRule {
135
- name: string;
136
- kind: 'string' | 'int' | 'float' | 'bool' | 'null' | 'array' | 'map' | 'bytes' | 'timestamp' | 'any';
137
- required?: boolean;
138
- default?: unknown;
139
- }
140
-
141
- /** Per-collection schema declaration (F8). Empty fields = no constraints. */
142
- export interface HakoSchema {
143
- fields: HakoFieldRule[];
144
- }
145
-
146
- export type Unsubscribe = () => Promise<void>;
147
-
148
- /**
149
- * Advanced Configuration Builder
150
- */
151
- export class HakoConfig {
152
- private _handle: unknown;
153
- private _native: NativeBindings;
154
-
155
- constructor(native: NativeBindings) {
156
- this._native = native;
157
- this._handle = native.configNew();
158
- }
159
-
160
- /** Reuse these bindings instead of loading the DLL twice in one process
161
- * (koffi rejects duplicate type registration on a second load). */
162
- getNativeBindings(): NativeBindings {
163
- return this._native;
164
- }
165
-
166
- setDurability(mode: DurabilityMode): this {
167
- this._native.configSetDurability(this._handle, mode);
168
- return this;
169
- }
170
-
171
- setEncryptionKey(key: string): this {
172
- this._native.configSetEncryptionKey(this._handle, key);
173
- return this;
174
- }
175
-
176
- setAuditLog(enabled: boolean, path: string | null = null): this {
177
- this._native.configSetAuditLog(this._handle, enabled, path);
178
- return this;
179
- }
180
-
181
- setQueryWorkers(count: number): this {
182
- this._native.configSetQueryWorkers(this._handle, count);
183
- return this;
184
- }
185
-
186
- setMemoryLimits(mmapBytes: number, maxInlinedBytes: number): this {
187
- this._native.configSetMemoryLimits(this._handle, mmapBytes, maxInlinedBytes);
188
- return this;
189
- }
190
-
191
- setStorageTuning(pageSize: number, threshold: number, groupCommitMaxOps: number): this {
192
- this._native.configSetStorageTuning(this._handle, pageSize, threshold, groupCommitMaxOps);
193
- return this;
194
- }
195
-
196
- setEncryptedCollections(collections: string[]): this {
197
- ensureOk(this._native.configSetEncryptedCollections(this._handle, JSON.stringify(collections)), this._native, 'setEncryptedCollections');
198
- return this;
199
- }
200
-
201
- setBlobThreshold(thresholdBytes: number): this {
202
- this._native.configSetBlobThreshold(this._handle, thresholdBytes);
203
- return this;
204
- }
205
-
206
- setCompression(enabled: boolean, level: number = 3): this {
207
- this._native.configSetCompression(this._handle, enabled, level);
208
- return this;
209
- }
210
-
211
- setGroupCommitIntervalMs(ms: number): this {
212
- this._native.configSetGroupCommitIntervalMs(this._handle, ms);
213
- return this;
214
- }
215
-
216
- setPageCacheCapacity(capacity: number): this {
217
- this._native.configSetPageCacheCapacity(this._handle, capacity);
218
- return this;
219
- }
220
-
221
- setSyncExcluded(...collections: string[]): this {
222
- ensureOk(this._native.configSetSyncExcluded(this._handle, JSON.stringify(collections)), this._native, 'configSetSyncExcluded');
223
- return this;
224
- }
225
-
226
- setLazyCollections(...collections: string[]): this {
227
- ensureOk(this._native.configSetLazyCollections(this._handle, JSON.stringify(collections)), this._native, 'configSetLazyCollections');
228
- return this;
229
- }
230
-
231
- setReplicationCollections(...collections: string[]): this {
232
- ensureOk(this._native.configSetReplicationCollections(this._handle, JSON.stringify(collections)), this._native, 'configSetReplicationCollections');
233
- return this;
234
- }
235
-
236
- getHandle(): unknown {
237
- return this._handle;
238
- }
239
- }
240
-
241
- function ensureOk(code: number, native: NativeBindings, ctx: string): void {
242
- if (code !== 0) {
243
- throw new Error(`${ctx}: ${native.lastError()}`);
244
- }
245
- }
246
-
247
- function parseDocJson(json: string | null): HakoDocData {
248
- if (!json) return {};
249
- return JSON.parse(json) as HakoDocData;
250
- }
251
-
252
- function parseQueryRows(json: string | null): HakoDocData[] {
253
- if (!json) return [];
254
- const parsed = JSON.parse(json);
255
- return Array.isArray(parsed) ? (parsed as HakoDocData[]) : [];
256
- }
257
-
258
- /**
259
- * Recursive field inserter (v0.5.9)
260
- */
261
- function insertField(native: NativeBindings, handle: unknown, key: string, value: Primitive): void {
262
- if (value === SERVER_TIMESTAMP_SENTINEL) {
263
- ensureOk(native.docInsertServerTimestamp(handle, key), native, 'serverTimestamp');
264
- return;
265
- }
266
- if (value instanceof Date) {
267
- native.docInsertTimestamp(handle, key, BigInt(value.getTime()) * 1000n);
268
- return;
269
- }
270
- if (value instanceof Uint8Array) {
271
- ensureOk(native.docInsertBin(handle, key, value), native, 'insertBin');
272
- return;
273
- }
274
- if (value instanceof HakoReference) {
275
- ensureOk(native.docInsertReference(handle, key, value.collection, value.id), native, 'insertReference');
276
- return;
277
- }
278
-
279
- if (Array.isArray(value)) {
280
- const arrHandle = native.arrayNew();
281
- for (const item of value) {
282
- if (typeof item === 'string') native.arrayAppendStr(arrHandle, item);
283
- else if (typeof item === 'number') native.arrayAppendInt(arrHandle, item);
284
- else if (typeof item === 'object' && item !== null) {
285
- const tempDoc = toNativeDoc(native, item as HakoDocData);
286
- native.arrayAppendDoc(arrHandle, tempDoc);
287
- native.docFree(tempDoc); // FFI copies data into the array
288
- }
289
- }
290
- // ownership transfers to parent doc handle
291
- ensureOk(native.docInsertArray(handle, key, arrHandle), native, 'insertArray');
292
- return;
293
- }
294
-
295
- if (typeof value === 'object' && value !== null) {
296
- const childDocHandle = toNativeDoc(native, value as HakoDocData);
297
- ensureOk(native.docInsertDoc(handle, key, childDocHandle), native, 'insertDoc');
298
- native.docFree(childDocHandle); // FFI copies data into the parent
299
- return;
300
- }
301
-
302
- // Primitives (string, number, bool, null)
303
- if (typeof value === 'string') {
304
- ensureOk(native.docInsertStr(handle, key, value), native, 'insertStr');
305
- } else if (typeof value === 'number') {
306
- if (Number.isInteger(value)) ensureOk(native.docInsertInt(handle, key, value), native, 'insertInt');
307
- else ensureOk(native.docInsertFloat(handle, key, value), native, 'insertFloat');
308
- } else if (typeof value === 'boolean') {
309
- ensureOk(native.docInsertBool(handle, key, value), native, 'insertBool');
310
- } else if (value === null) {
311
- ensureOk(native.docInsertNull(handle, key), native, 'insertNull');
312
- }
313
- }
314
-
315
- function toNativeDoc(native: NativeBindings, data: HakoDocData): unknown {
316
- const doc = native.docNew();
317
- if (!doc) throw new Error(`docNew failed: ${native.lastError()}`);
318
- try {
319
- for (const [key, value] of Object.entries(data)) {
320
- insertField(native, doc, key, value);
321
- }
322
- return doc;
323
- } catch (err) {
324
- native.docFree(doc);
325
- throw err;
326
- }
327
- }
328
-
329
- export class DocumentSnapshot {
330
- constructor(
331
- public readonly id: string,
332
- public readonly exists: boolean,
333
- private readonly payload?: HakoDocData,
334
- public readonly _nativeHandle?: unknown
335
- ) { }
336
-
337
- data(): HakoDocData | undefined {
338
- return this.payload;
339
- }
340
- }
341
-
342
- /**
343
- * One raw page: pinned storage bytes per row (v0.8.3+). Decode nothing
344
- * up front — resolve() only rows you touch, page with
345
- * Query.startAfterRaw() (no decode at all). Free when done; rows die
346
- * with the page.
347
- */
348
- export class RawQuerySnapshot {
349
- private freed = false;
350
-
351
- constructor(
352
- private readonly client: HakoClient,
353
- private readonly collection: string,
354
- private readonly handle: unknown
355
- ) { }
356
-
357
- get count(): number {
358
- return this.client.nativeBindings().rawResultCount(this.handle);
359
- }
360
-
361
- /** Decode + inflate one row. Prefer resolving only rows you touch. */
362
- async resolve(index: number): Promise<HakoDocData | undefined> {
363
- const native = this.client.nativeBindings();
364
- const doc = native.rawDocToDoc(this.client.engineHandle(), this.rawHandleAt(index), this.collection);
365
- if (!doc) return undefined;
366
- try {
367
- return parseDocJson(native.docToJson(doc));
368
- } finally {
369
- native.docFree(doc);
370
- }
371
- }
372
-
373
- /** Borrowed native raw handle. Valid until free(). Internal. */
374
- rawHandleAt(index: number): unknown {
375
- return this.client.nativeBindings().rawResultGet(this.handle, index);
376
- }
377
-
378
- free(): void {
379
- if (!this.freed) {
380
- this.freed = true;
381
- this.client.nativeBindings().rawResultFree(this.handle);
382
- }
383
- }
384
- }
385
-
386
- /**
387
- * One borrowed row (v0.8.11+): lazy numeric/bool pulls with no decode
388
- * and no JSON. Strings stay on resolve() (no backend memory reads).
389
- * Free when done.
390
- */
391
- export class ViewDocSnapshot {
392
- private freed = false;
393
-
394
- constructor(
395
- private readonly client: HakoClient,
396
- private readonly collection: string,
397
- private readonly docId: string,
398
- private readonly handle: unknown
399
- ) { }
400
-
401
- get id(): string {
402
- return this.docId;
403
- }
404
-
405
- get fieldCount(): number {
406
- return this.client.nativeBindings().viewFieldCount(this.handle);
407
- }
408
-
409
- has(field: string): boolean {
410
- return this.client.nativeBindings().viewHasField(this.handle, field);
411
- }
412
-
413
- getInt(field: string): number | bigint | null {
414
- return this.client.nativeBindings().viewGetInt(this.handle, field);
415
- }
416
-
417
- getFloat(field: string): number | null {
418
- return this.client.nativeBindings().viewGetFloat(this.handle, field);
419
- }
420
-
421
- getBool(field: string): boolean | null {
422
- return this.client.nativeBindings().viewGetBool(this.handle, field);
423
- }
424
-
425
- /** Dotted-path pulls (core 0.18+): `a.b.c` reads without a full decode. */
426
- getPathInt(path: string): number | bigint | null {
427
- return this.client.nativeBindings().viewGetPathInt(this.handle, path);
428
- }
429
-
430
- getPathFloat(path: string): number | null {
431
- return this.client.nativeBindings().viewGetPathFloat(this.handle, path);
432
- }
433
-
434
- getPathBool(path: string): boolean | null {
435
- return this.client.nativeBindings().viewGetPathBool(this.handle, path);
436
- }
437
-
438
- getPathString(path: string): string | null {
439
- return this.client.nativeBindings().viewGetPathStr(this.handle, path);
440
- }
441
-
442
- getPathBytes(path: string): Uint8Array | null {
443
- return this.client.nativeBindings().viewGetPathBytes(this.handle, path);
444
- }
445
-
446
- /** Full decode + inflate. Prefer pulls for sparse reads. */
447
- async resolve(): Promise<HakoDocData | undefined> {
448
- const native = this.client.nativeBindings();
449
- const doc = native.viewToDoc(this.handle, this.docId);
450
- if (!doc) return undefined;
451
- try {
452
- return parseDocJson(native.docToJson(doc));
453
- } finally {
454
- native.docFree(doc);
455
- }
456
- }
457
-
458
- free(): void {
459
- if (!this.freed) {
460
- this.freed = true;
461
- this.client.nativeBindings().viewFree(this.handle);
462
- }
463
- }
464
- }
465
-
466
- export class HakoClient {
467
- private readonly native: NativeBindings;
468
- private readonly engine: unknown;
469
- private isClosed = false;
470
-
471
- private constructor(native: NativeBindings, engine: unknown) {
472
- this.native = native;
473
- this.engine = engine;
474
- }
475
-
476
- static async open(path: string, options?: HakoClientOptions): Promise<HakoClient> {
477
- const native = options?.native
478
- ?? options?.config?.getNativeBindings()
479
- ?? (await loadNativeBindings(options?.libraryPath));
480
-
481
- let engine: unknown;
482
- if (options?.config) {
483
- engine = native.engineOpenWithConfig(path, options.config.getHandle());
484
- } else {
485
- engine = native.engineOpen(path);
486
- }
487
-
488
- if (!engine) {
489
- throw new Error(`Failed to open HakoDB: ${native.lastError()}`);
490
- }
491
- return new HakoClient(native, engine);
492
- }
493
-
494
- static serverTimestamp(): any {
495
- return SERVER_TIMESTAMP_SENTINEL;
496
- }
497
-
498
- static async createConfig(libraryPath?: string): Promise<HakoConfig> {
499
- const native = await loadNativeBindings(libraryPath);
500
- return new HakoConfig(native);
501
- }
502
-
503
- collection(name: string): CollectionReference {
504
- this.assertOpen();
505
- return new CollectionReference(this, name);
506
- }
507
-
508
- batch(): WriteBatch {
509
- this.assertOpen();
510
- return new WriteBatch(this);
511
- }
512
-
513
- async listCollections(): Promise<string[]> {
514
- this.assertOpen();
515
- const json = this.native.engineListCollections(this.engine);
516
- return json ? JSON.parse(json) : [];
517
- }
518
-
519
- /** Declare or replace a collection schema (F8). */
520
- async setSchema(collection: string, schema: HakoSchema): Promise<void> {
521
- this.assertOpen();
522
- ensureOk(this.native.engineSetSchema(this.engine, collection, JSON.stringify(schema)), this.native, 'engineSetSchema');
523
- }
524
-
525
- /** Absent collection returns null, not an error. */
526
- async getSchema(collection: string): Promise<HakoSchema | null> {
527
- this.assertOpen();
528
- const json = this.native.engineGetSchema(this.engine, collection);
529
- return json ? (JSON.parse(json) as HakoSchema) : null;
530
- }
531
-
532
- async clearSchema(collection: string): Promise<void> {
533
- this.assertOpen();
534
- ensureOk(this.native.engineClearSchema(this.engine, collection), this.native, 'engineClearSchema');
535
- }
536
-
537
- async listSchemas(): Promise<Record<string, HakoSchema>> {
538
- this.assertOpen();
539
- const json = this.native.engineListSchemas(this.engine);
540
- return json ? (JSON.parse(json) as Record<string, HakoSchema>) : {};
541
- }
542
-
543
- /** Read a doc and the commit version it was read at (F5). */
544
- async getVersioned(collection: string, docId: string): Promise<{ snapshot: DocumentSnapshot; version: bigint } | null> {
545
- this.assertOpen();
546
- const { doc, version } = this.native.engineGetVersioned(this.engine, collection, docId);
547
- if (!doc) return null;
548
- const json = this.native.docToJson(doc);
549
- return { snapshot: new DocumentSnapshot(docId, true, parseDocJson(json), doc), version };
550
- }
551
-
552
- /** Wait for background index/blob/maintenance work, bounded by timeoutMs. */
553
- async awaitQuiescent(timeoutMs: number = 5000): Promise<boolean> {
554
- this.assertOpen();
555
- return this.native.engineAwaitQuiescent(this.engine, timeoutMs);
556
- }
557
-
558
- async quiescenceStatus(): Promise<Record<string, unknown> | null> {
559
- this.assertOpen();
560
- const json = this.native.engineQuiescenceStatus(this.engine);
561
- return json ? (JSON.parse(json) as Record<string, unknown>) : null;
562
- }
563
-
564
- createNetSyncer(name: string, roomKey: string): NetSyncer {
565
- this.assertOpen();
566
- const handle = this.native.netSyncerNew(this.engine, name, roomKey);
567
- if (!handle) {
568
- throw new Error(`netSyncerNew failed: ${this.native.lastError()}`);
569
- }
570
- return new NetSyncer(this.native, handle);
571
- }
572
-
573
- createCloudSync(
574
- mode: CloudSyncMode,
575
- clientId: string | null = null,
576
- roomName: string | null = null,
577
- roomKey: string | null = null,
578
- authToken: string | null = null
579
- ): CloudSync {
580
- this.assertOpen();
581
- const handle = this.native.cloudSyncNew(this.engine, mode, clientId, roomName, roomKey, authToken);
582
- if (!handle) {
583
- throw new Error(`cloudSyncNew failed: ${this.native.lastError()}`);
584
- }
585
- return new CloudSync(this.native, handle);
586
- }
587
-
588
- /**
589
- * Creates a room-agnostic cloud SERVER ("big cloud server storage"). It is
590
- * not bound to any room: clients choose their room (and this server) and the
591
- * server accepts and persists any (roomName, roomKey) pair, storing each
592
- * room's collections under its own storage prefix and relaying sync only to
593
- * the members of that room.
594
- */
595
- createCloudSyncServer(serverId: string | null = null, authToken: string | null = null, roomName: string | null = null, roomKey: string | null = null): CloudSync {
596
- this.assertOpen();
597
- const handle = this.native.cloudSyncServerNew(this.engine, serverId, authToken, roomName, roomKey);
598
- if (!handle) {
599
- throw new Error(`cloudSyncServerNew failed: ${this.native.lastError()}`);
600
- }
601
- return new CloudSync(this.native, handle);
602
- }
603
-
604
- /**
605
- * Creates an offline-first cloud CLIENT bound to a room of the caller's
606
- * choosing. The client picks the room (roomName + roomKey) and later picks
607
- * the server via `CloudSync.start()`.
608
- */
609
- createCloudSyncClient(
610
- clientId: string | null = null,
611
- roomName: string | null = null,
612
- roomKey: string | null = null,
613
- authToken: string | null = null
614
- ): CloudSync {
615
- this.assertOpen();
616
- const handle = this.native.cloudSyncClientNew(this.engine, clientId, roomName, roomKey, authToken);
617
- if (!handle) {
618
- throw new Error(`cloudSyncClientNew failed: ${this.native.lastError()}`);
619
- }
620
- return new CloudSync(this.native, handle);
621
- }
622
-
623
- isIndexesReady(): boolean {
624
- this.assertOpen();
625
- return this.native.engineIsIndexesReady(this.engine);
626
- }
627
-
628
- async compact(): Promise<void> {
629
- this.assertOpen();
630
- ensureOk(this.native.engineCompact(this.engine), this.native, 'engineCompact');
631
- }
632
-
633
- async getStats(): Promise<Record<string, unknown>> {
634
- this.assertOpen();
635
- const raw = this.native.engineGetStats(this.engine);
636
- return raw ? JSON.parse(raw) : {};
637
- }
638
-
639
- async getAuditLog(): Promise<unknown[]> {
640
- this.assertOpen();
641
- const raw = this.native.engineGetAuditLog(this.engine);
642
- return raw ? JSON.parse(raw) : [];
643
- }
644
-
645
- async snapshotIndices(): Promise<void> {
646
- this.assertOpen();
647
- ensureOk(this.native.engineSnapshotIndices(this.engine), this.native, 'engineSnapshotIndices');
648
- }
649
-
650
- async listIndexes(collection: string | null = null): Promise<unknown> {
651
- this.assertOpen();
652
- const raw = this.native.engineListIndexes(this.engine, collection);
653
- return raw ? JSON.parse(raw) : null;
654
- }
655
-
656
- async patch(collection: string, docId: string, data: HakoDocData): Promise<void> {
657
- this.assertOpen();
658
- const updates = toNativeDoc(this.native, data);
659
- try {
660
- ensureOk(this.native.enginePatch(this.engine, collection, docId, updates), this.native, 'enginePatch');
661
- } finally {
662
- this.native.docFree(updates);
663
- }
664
- }
665
-
666
- async insertSubDoc(col: string, id: string, subCol: string, subId: string, data: HakoDocData): Promise<void> {
667
- this.assertOpen();
668
- const doc = toNativeDoc(this.native, data);
669
- try {
670
- ensureOk(this.native.engineInsertSubDoc(this.engine, col, id, subCol, subId, doc), this.native, 'engineInsertSubDoc');
671
- } finally {
672
- this.native.docFree(doc);
673
- }
674
- }
675
-
676
- async getByReference(doc: DocumentSnapshot, fieldKey: string): Promise<DocumentSnapshot | null> {
677
- this.assertOpen();
678
- if (!doc._nativeHandle) return null;
679
- const target = this.native.engineGetByRef(this.engine, doc._nativeHandle, fieldKey);
680
- if (!target) return null;
681
- const json = this.native.docToJson(target);
682
- this.native.docFree(target);
683
- return new DocumentSnapshot(fieldKey, true, parseDocJson(json));
684
- }
685
-
686
- async createCompositeIndex(collection: string, fields: { field: string; desc?: boolean }[]): Promise<number> {
687
- this.assertOpen();
688
- const id = this.native.engineCreateIndex(this.engine, collection, JSON.stringify(fields.map(f => ({ field: f.field, desc: !!f.desc }))));
689
- if (id === 0) throw new Error(`engineCreateIndex failed: ${this.native.lastError()}`);
690
- return id;
691
- }
692
-
693
- async runTransaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
694
- this.assertOpen();
695
- const tx = new Transaction(this.native, this.engine);
696
- try {
697
- const result = await fn(tx);
698
- ensureOk(this.native.transactionCommit(this.engine, tx.handle), this.native, 'transactionCommit');
699
- return result;
700
- } finally {
701
- tx.dispose();
702
- }
703
- }
704
-
705
- async backup(destinationPath: string): Promise<void> {
706
- this.assertOpen();
707
- ensureOk(this.native.engineBackup(this.engine, destinationPath), this.native, 'engineBackup');
708
- }
709
-
710
- async close(): Promise<void> {
711
- if (this.isClosed) return;
712
- this.native.engineFree(this.engine);
713
- this.isClosed = true;
714
- }
715
-
716
- async set(collection: string, docId: string, data: HakoDocData): Promise<void> {
717
- this.assertOpen();
718
- const doc = toNativeDoc(this.native, data);
719
- try {
720
- ensureOk(this.native.engineInsert(this.engine, collection, docId, doc), this.native, 'engineInsert');
721
- } finally {
722
- this.native.docFree(doc);
723
- }
724
- }
725
-
726
- async get(collection: string, docId: string): Promise<DocumentSnapshot> {
727
- this.assertOpen();
728
- const doc = this.native.engineGet(this.engine, collection, docId);
729
- if (!doc) return new DocumentSnapshot(docId, false);
730
-
731
- const json = this.native.docToJson(doc);
732
- // Keep 'doc' handle for startAfter. Native memory management should be handled
733
- // by engineFree or manual free if the user keeps thousands of snapshots.
734
- return new DocumentSnapshot(docId, true, parseDocJson(json), doc);
735
- }
736
-
737
- /**
738
- * P2 fast path (core 0.18+): JSON straight from the pinned bytes, no
739
- * owned doc handle. Blob links are resolved, so the shape matches get().
740
- */
741
- async getJson(collection: string, docId: string): Promise<HakoDocData | null> {
742
- this.assertOpen();
743
- const json = this.native.engineGetJson(this.engine, collection, docId);
744
- return json ? (parseDocJson(json) as HakoDocData) : null;
745
- }
746
-
747
- /**
748
- * Borrowed point view (v0.8.11+): lazy numeric/bool pulls with no decode
749
- * and no JSON. Returns null when missing. Free the snapshot when done.
750
- */
751
- async viewDoc(collection: string, docId: string): Promise<ViewDocSnapshot | null> {
752
- this.assertOpen();
753
- const view = this.native.viewGet(this.engine, collection, docId);
754
- if (!view) return null;
755
- return new ViewDocSnapshot(this, collection, docId, view);
756
- }
757
-
758
- async delete(collection: string, docId: string): Promise<void> {
759
- this.assertOpen();
760
- ensureOk(this.native.engineDelete(this.engine, collection, docId), this.native, 'engineDelete');
761
- }
762
-
763
- /** Local-only delete: never leaves this device (no sync tailer or handshake transmits it). */
764
- async deleteLocal(collection: string, docId: string): Promise<void> {
765
- this.assertOpen();
766
- ensureOk(this.native.engineDeleteLocal(this.engine, collection, docId), this.native, 'engineDeleteLocal');
767
- }
768
-
769
- /** Delete with an explicit mode: force=true reproduces the legacy
770
- * tombstone-only shape. Default `delete` is soft since core 0.20.0
771
- * (restoreable via restore() until the sweeper purges the record). */
772
- async deleteEx(collection: string, docId: string, force: boolean): Promise<void> {
773
- this.assertOpen();
774
- ensureOk(this.native.engineDeleteEx(this.engine, collection, docId, force), this.native, 'engineDeleteEx');
775
- }
776
-
777
- /** Restore a soft-deleted doc from its retention record (fresh version;
778
- * consumes the record). Refuses when the id was re-put (cancel rule) or
779
- * no record exists. */
780
- async restore(collection: string, docId: string): Promise<void> {
781
- this.assertOpen();
782
- ensureOk(this.native.engineRestore(this.engine, collection, docId), this.native, 'engineRestore');
783
- }
784
-
785
- /** Restoreable records, all collections or one (soft-delete retention queue). */
786
- async restoreAvailable(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
787
- this.assertOpen();
788
- return JSON.parse(this.native.engineRestoreAvailable(this.engine, collection ?? null) ?? '[]');
789
- }
790
-
791
- /** Due-for-sweep subset of the retention queue (same shape as restoreAvailable). */
792
- async deleteQueue(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
793
- this.assertOpen();
794
- return JSON.parse(this.native.engineDeleteQueue(this.engine, collection ?? null) ?? '[]');
795
- }
796
-
797
- /** Run one retention sweep pass now; returns the purged record count. */
798
- async sweepNow(): Promise<number> {
799
- this.assertOpen();
800
- const n = this.native.engineSweepNow(this.engine);
801
- if (n < 0) {
802
- throw new Error(`engineSweepNow: ${this.native.lastError()}`);
803
- }
804
- return n;
805
- }
806
-
807
- /** Mark a collection local-only (never syncs) or rejoin it with `local=false`. */
808
- async setCollectionLocal(collection: string, local: boolean): Promise<void> {
809
- this.assertOpen();
810
- ensureOk(this.native.engineSetCollectionLocal(this.engine, collection, local ? 1 : 0), this.native, 'engineSetCollectionLocal');
811
- }
812
-
813
- /** Opt a key back into replication (future ops only). */
814
- async replicateKey(collection: string, docId: string): Promise<void> {
815
- this.assertOpen();
816
- ensureOk(this.native.engineReplicateKey(this.engine, collection, docId), this.native, 'engineReplicateKey');
817
- }
818
-
819
- /** Opt a whole collection back into replication. */
820
- async replicateCollection(collection: string): Promise<void> {
821
- this.assertOpen();
822
- ensureOk(this.native.engineReplicateCollection(this.engine, collection), this.native, 'engineReplicateCollection');
823
- }
824
-
825
- /** Vacuum: purge tombstones (never replicates); next handshake pulls peer state. */
826
- async vacuumCollection(collection: string): Promise<number> {
827
- this.assertOpen();
828
- const n = this.native.engineVacuumCollection(this.engine, collection);
829
- if (n < 0) throw new Error(`engineVacuumCollection failed: ${this.native.lastError()}`);
830
- return n;
831
- }
832
-
833
- /** Relocate docs by id src -> dst. Returns {moved, missing}; refusals throw. */
834
- async relocateDocs(src: string, dst: string, ids: string[]): Promise<{ moved: string[]; missing: string[] }> {
835
- this.assertOpen();
836
- const json = this.native.engineRelocateDocs(this.engine, src, dst, JSON.stringify(ids));
837
- if (!json) throw new Error(`engineRelocateDocs failed: ${this.native.lastError()}`);
838
- return JSON.parse(json);
839
- }
840
-
841
- /** Load a lazy collection's snapshot into the index now. */
842
- async loadCollection(collection: string): Promise<void> {
843
- this.assertOpen();
844
- ensureOk(this.native.engineLoadCollection(this.engine, collection), this.native, 'engineLoadCollection');
845
- }
846
-
847
- /** Unload a lazy collection (frees RAM; snapshot stays). Refuses non-lazy. */
848
- async unloadCollection(collection: string): Promise<void> {
849
- this.assertOpen();
850
- ensureOk(this.native.engineUnloadCollection(this.engine, collection), this.native, 'engineUnloadCollection');
851
- }
852
-
853
- /** Lazy collections currently out of the index. */
854
- async unloadedCollections(): Promise<string[]> {
855
- this.assertOpen();
856
- const json = this.native.engineUnloadedCollections(this.engine);
857
- return json ? JSON.parse(json) : [];
858
- }
859
-
860
- nativeBindings(): NativeBindings { return this.native; }
861
- engineHandle(): unknown { return this.engine; }
862
-
863
- private assertOpen(): void {
864
- if (this.isClosed) throw new Error('HakoClient is already closed');
865
- }
866
- }
867
-
868
- export class NetSyncer {
869
- private closed = false;
870
-
871
- constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
872
-
873
- async start(port: number): Promise<void> {
874
- ensureOk(this.native.netSyncerStart(this.handle, port), this.native, 'netSyncerStart');
875
- }
876
-
877
- /**
878
- * Discovery transports: 0 = mDNS (desktop default), 1 = UDP broadcast
879
- * (mobile default, no multicast), 2 = both (mixed groups). Takes effect
880
- * at start(). Mirrors the CLI `--discovery` flag.
881
- */
882
- async setDiscoveryMode(mode: 0 | 1 | 2): Promise<void> {
883
- ensureOk(this.native.netSyncerSetDiscovery(this.handle, mode), this.native, 'netSyncerSetDiscovery');
884
- }
885
-
886
- async status<T = unknown>(): Promise<T | null> {
887
- const raw = this.native.netSyncerStatus(this.handle);
888
- return raw ? (JSON.parse(raw) as T) : null;
889
- }
890
-
891
- async close(): Promise<void> {
892
- if (this.closed) return;
893
- this.native.netSyncerFree(this.handle);
894
- this.closed = true;
895
- }
896
- }
897
-
898
- export class CloudSync {
899
- private closed = false;
900
-
901
- constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
902
-
903
- async start(address: string): Promise<void> {
904
- ensureOk(this.native.cloudSyncStart(this.handle, address), this.native, 'cloudSyncStart');
905
- }
906
-
907
- async status<T = unknown>(): Promise<T | null> {
908
- const raw = this.native.cloudSyncStatus(this.handle);
909
- return raw ? (JSON.parse(raw) as T) : null;
910
- }
911
-
912
- stop(): void {
913
- if (this.closed) return;
914
- this.native.cloudSyncStop(this.handle);
915
- }
916
-
917
- close(): void {
918
- this.stop();
919
- this.native.cloudSyncFree(this.handle);
920
- this.closed = true;
921
- }
922
- }
923
-
924
- export class Transaction {
925
- private disposed = false;
926
-
927
- constructor(
928
- private readonly native: NativeBindings,
929
- private readonly engine: unknown,
930
- readonly handle: unknown = native.transactionBegin(engine)
931
- ) {
932
- if (!handle) throw new Error(`transactionBegin failed: ${native.lastError()}`);
933
- }
934
-
935
- async get(collection: string, docId: string): Promise<DocumentSnapshot> {
936
- this.ensureActive();
937
- const doc = this.native.transactionGet(this.engine, this.handle, collection, docId);
938
- if (!doc) return new DocumentSnapshot(docId, false);
939
- const json = this.native.docToJson(doc);
940
- this.native.docFree(doc);
941
- return new DocumentSnapshot(docId, true, parseDocJson(json));
942
- }
943
-
944
- /** Batched read: one snapshot, output aligned with ids; missing ids are null. */
945
- async getMany(collection: string, ids: string[]): Promise<(HakoDocData | null)[]> {
946
- this.ensureActive();
947
- const json = this.native.transactionGetMany(this.engine, this.handle, collection, JSON.stringify(ids));
948
- if (json === null) throw new Error(`transactionGetMany: ${this.native.lastError()}`);
949
- return JSON.parse(json) as (HakoDocData | null)[];
950
- }
951
-
952
- /** Merge-patch a doc inside the transaction (F5). */
953
- patch(collection: string, docId: string, data: HakoDocData): this {
954
- this.ensureActive();
955
- ensureOk(this.native.transactionPatch(this.engine, this.handle, collection, docId, JSON.stringify(data)), this.native, 'transactionPatch');
956
- return this;
957
- }
958
-
959
- set(collection: string, docId: string, data: HakoDocData): this {
960
- this.ensureActive();
961
- const doc = toNativeDoc(this.native, data);
962
- try {
963
- ensureOk(this.native.transactionSet(this.handle, collection, docId, doc), this.native, 'transactionSet');
964
- } finally {
965
- this.native.docFree(doc);
966
- }
967
- return this;
968
- }
969
-
970
- dispose(): void {
971
- if (this.disposed) return;
972
- this.native.transactionFree(this.handle);
973
- this.disposed = true;
974
- }
975
-
976
- private ensureActive(): void {
977
- if (this.disposed) throw new Error('Transaction has already been committed/disposed');
978
- }
979
- }
980
-
981
- export class CollectionReference {
982
- constructor(private readonly client: HakoClient, private readonly name: string) { }
983
-
984
- doc(id: string): DocumentReference {
985
- return new DocumentReference(this.client, this.name, id);
986
- }
987
-
988
- onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
989
- return new Query(this.client, this.name).onSnapshot(callback);
990
- }
991
-
992
- // 3. FIXED: Updated 'op' signature to include 'in'
993
- where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
994
- return new Query(this.client, this.name).where(field, op, value);
995
- }
996
-
997
- orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
998
- return new Query(this.client, this.name).orderBy(field, direction);
999
- }
1000
-
1001
- limit(max: number): Query {
1002
- return new Query(this.client, this.name).limit(max);
1003
- }
1004
-
1005
- select(...fields: string[]): Query {
1006
- return new Query(this.client, this.name).select(...fields);
1007
- }
1008
-
1009
- async get(): Promise<HakoDocData[]> {
1010
- return new Query(this.client, this.name).get();
1011
- }
1012
-
1013
- async count(): Promise<number> {
1014
- return new Query(this.client, this.name).count();
1015
- }
1016
-
1017
- whereElemMatch(field: string, filters: ElemFilter[]): Query {
1018
- return new Query(this.client, this.name).whereElemMatch(field, filters);
1019
- }
1020
-
1021
- whereArrayAllEq(field: string, value: unknown): Query {
1022
- return new Query(this.client, this.name).whereArrayAllEq(field, value);
1023
- }
1024
-
1025
- whereNear(field: string, vec: number[] | Float32Array): Query {
1026
- return new Query(this.client, this.name).whereNear(field, vec);
1027
- }
1028
-
1029
- whereTraverse(
1030
- startCol: string,
1031
- startId: string,
1032
- direction: TraverseDirection = 'outgoing',
1033
- edge: string | null = null,
1034
- maxDepth = 3
1035
- ): Query {
1036
- return new Query(this.client, this.name).whereTraverse(startCol, startId, direction, edge, maxDepth);
1037
- }
1038
-
1039
- async createIndex(field: string): Promise<void> {
1040
- ensureOk(this.client.nativeBindings().createSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createIndex');
1041
- }
1042
-
1043
- async createVectorIndex(field: string, dim: number, metric: VectorMetric = 'cosine'): Promise<void> {
1044
- ensureOk(this.client.nativeBindings().createVectorIndex(this.client.engineHandle(), this.name, field, dim, metric === 'l2' ? 1 : 0), this.client.nativeBindings(), 'createVectorIndex');
1045
- }
1046
-
1047
- /** KNN search: nearest-first [{id, score, doc}]. Embeddings are stored as binary LE-f32 (insert a Uint8Array of Float32 bytes). */
1048
- async findNear(field: string, query: number[] | Float32Array, k = 10): Promise<NearHit[]> {
1049
- const native = this.client.nativeBindings();
1050
- const vec = query instanceof Float32Array ? query : Float32Array.from(query);
1051
- const json = native.engineFindNear(this.client.engineHandle(), this.name, field, vec, k);
1052
- if (json === null) throw new Error(`findNear failed: ${native.lastError()}`);
1053
- return JSON.parse(json) as NearHit[];
1054
- }
1055
-
1056
- async createTraverseIndex(): Promise<void> {
1057
- ensureOk(this.client.nativeBindings().createTraverseIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'createTraverseIndex');
1058
- }
1059
-
1060
- /** Graph BFS from a doc in this collection: [{collection, id, depth, doc}]. edge null = any ref field. */
1061
- async findPaths(id: string, direction: TraverseDirection = 'outgoing', edge: string | null = null, maxDepth = 10, k = 100): Promise<PathHit[]> {
1062
- const native = this.client.nativeBindings();
1063
- const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1064
- const json = native.engineFindPaths(this.client.engineHandle(), this.name, id, dir, edge, maxDepth, k);
1065
- if (json === null) throw new Error(`findPaths failed: ${native.lastError()}`);
1066
- return JSON.parse(json) as PathHit[];
1067
- }
1068
-
1069
- async createEdgeIndex(): Promise<void> {
1070
- ensureOk(this.client.nativeBindings().createEdgeIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'createEdgeIndex');
1071
- }
1072
-
1073
- /** Weighted shortest paths via an edge collection: cost-ordered [{collection, id, depth, cost, doc}]. */
1074
- async shortestPaths(id: string, via: string, weight: string | null = null, direction: TraverseDirection = 'outgoing', edge: string | null = null, maxDepth = 10, k = 100): Promise<PathHit[]> {
1075
- const native = this.client.nativeBindings();
1076
- const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1077
- const json = native.engineShortestPaths(this.client.engineHandle(), this.name, id, dir, edge, via, weight, maxDepth, k);
1078
- if (json === null) throw new Error(`shortestPaths failed: ${native.lastError()}`);
1079
- return JSON.parse(json) as PathHit[];
1080
- }
1081
-
1082
- async createFtsIndex(field: string): Promise<void> {
1083
- ensureOk(this.client.nativeBindings().createFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createFtsIndex');
1084
- }
1085
-
1086
- async createCompositeIndex(fields: { field: string; desc?: boolean }[]): Promise<number> {
1087
- return this.client.createCompositeIndex(this.name, fields);
1088
- }
1089
-
1090
- /** Drop indexes (v0.19.6 parity). Composite drops by the id createCompositeIndex returned. */
1091
- async dropIndex(field: string): Promise<void> {
1092
- ensureOk(this.client.nativeBindings().dropSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropIndex');
1093
- }
1094
-
1095
- async dropVectorIndex(field: string): Promise<void> {
1096
- ensureOk(this.client.nativeBindings().dropVectorIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropVectorIndex');
1097
- }
1098
-
1099
- async dropCompositeIndex(id: number): Promise<void> {
1100
- ensureOk(this.client.nativeBindings().dropCompositeIndex(this.client.engineHandle(), this.name, id), this.client.nativeBindings(), 'dropCompositeIndex');
1101
- }
1102
-
1103
- async dropEdgeIndex(): Promise<void> {
1104
- ensureOk(this.client.nativeBindings().dropEdgeIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'dropEdgeIndex');
1105
- }
1106
-
1107
- async dropFtsIndex(field: string): Promise<void> {
1108
- ensureOk(this.client.nativeBindings().dropFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropFtsIndex');
1109
- }
1110
-
1111
- async dropTraverseIndex(): Promise<void> {
1112
- ensureOk(this.client.nativeBindings().dropTraverseIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'dropTraverseIndex');
1113
- }
1114
-
1115
- /** HNSW-tuned vector index (m = edges per node, efConstruction = build beam, efSearch = query beam; 0 = engine default). */
1116
- async createVectorIndexV2(field: string, dim: number, metric: VectorMetric = 'cosine', m = 0, efConstruction = 0, efSearch = 0): Promise<void> {
1117
- ensureOk(this.client.nativeBindings().createVectorIndexV2(this.client.engineHandle(), this.name, field, dim, metric === 'l2' ? 1 : 0, m, efConstruction, efSearch), this.client.nativeBindings(), 'createVectorIndexV2');
1118
- }
1119
-
1120
- /** Graph BFS with the v0.19 extensions: via-edge hops, node/edge predicates, opt-in path/via projections. */
1121
- async findPathsFull(id: string, opts: PathOptions = {}): Promise<PathHit[]> {
1122
- const native = this.client.nativeBindings();
1123
- const o = resolvePathOptions(opts);
1124
- const json = native.findPathsFull(this.client.engineHandle(), this.name, id, o.direction, o.edge, o.via, o.maxDepth, o.k, o.includePath, o.includeVia, o.nodeField, o.nodeJSON, o.typeField, o.typeJSON, o.matchField, o.matchJSON);
1125
- if (json === null) throw new Error(`findPathsFull failed: ${native.lastError()}`);
1126
- return JSON.parse(json) as PathHit[];
1127
- }
1128
-
1129
- /** Weighted shortest paths with the same extensions as findPathsFull. */
1130
- async shortestPathsFull(id: string, via: string | null, opts: PathOptions = {}): Promise<PathHit[]> {
1131
- const native = this.client.nativeBindings();
1132
- const o = resolvePathOptions(opts);
1133
- const json = native.simplePathsFull(this.client.engineHandle(), this.name, id, o.direction, o.edge, via, o.weight ?? null, o.maxDepth, o.k, o.includePath, o.includeVia, o.nodeField, o.nodeJSON, o.typeField, o.typeJSON, o.matchField, o.matchJSON);
1134
- if (json === null) throw new Error(`shortestPathsFull failed: ${native.lastError()}`);
1135
- return JSON.parse(json) as PathHit[];
1136
- }
1137
-
1138
- /** Serialize the collection's ref graph (nodes + edges) as JSON. */
1139
- async exportGraph(opts: PathOptions = {}): Promise<unknown> {
1140
- const native = this.client.nativeBindings();
1141
- const o = resolvePathOptions(opts);
1142
- const json = native.exportGraph(this.client.engineHandle(), this.name, o.direction, o.edge, o.via, o.nodeField, o.nodeJSON);
1143
- if (json === null) throw new Error(`exportGraph failed: ${native.lastError()}`);
1144
- return JSON.parse(json);
1145
- }
1146
-
1147
- /** Whole-graph analysis: "components" | "cycle" | "topo". */
1148
- async graphAnalysis(op: 'components' | 'cycle' | 'topo', opts: PathOptions = {}): Promise<unknown> {
1149
- const native = this.client.nativeBindings();
1150
- const o = resolvePathOptions(opts);
1151
- const json = native.graphAnalysis(this.client.engineHandle(), this.name, op, o.direction, o.edge, o.via, o.nodeField, o.nodeJSON);
1152
- if (json === null) throw new Error(`graphAnalysis failed: ${native.lastError()}`);
1153
- return JSON.parse(json);
1154
- }
1155
- }
1156
-
1157
- export class DocumentReference {
1158
- constructor(private readonly client: HakoClient, readonly _collection: string, readonly _id: string) { }
1159
-
1160
- async set(data: HakoDocData): Promise<void> {
1161
- await this.client.set(this._collection, this._id, data);
1162
- }
1163
-
1164
- async update(data: HakoDocData): Promise<void> {
1165
- await this.client.patch(this._collection, this._id, data);
1166
- }
1167
-
1168
- async get(): Promise<DocumentSnapshot> {
1169
- return this.client.get(this._collection, this._id);
1170
- }
1171
-
1172
- async delete(): Promise<void> {
1173
- await this.client.delete(this._collection, this._id);
1174
- }
1175
-
1176
- async getByReference(fieldKey: string): Promise<DocumentSnapshot | null> {
1177
- const snap = await this.get();
1178
- if (!snap.exists) return null;
1179
- return this.client.getByReference(snap, fieldKey);
1180
- }
1181
- }
1182
-
1183
- export class Query {
1184
- private _startAfterSnapshot?: DocumentSnapshot;
1185
- private _startAtSnapshot?: DocumentSnapshot;
1186
- private _endAtSnapshot?: DocumentSnapshot;
1187
- private _endBeforeSnapshot?: DocumentSnapshot;
1188
- private _startAfterRawAnchor?: { snap: RawQuerySnapshot; index: number };
1189
- private readonly filters: QueryConstraint[] = [];
1190
- private readonly orFilters: QueryConstraint[] = [];
1191
- private order?: QueryOrder;
1192
- private queryLimit?: number;
1193
- private queryOffset?: number;
1194
- private projection: string[] = [];
1195
- private deferBlobsDef = false;
1196
- private near?: { field: string; vec: Float32Array };
1197
- private traverse?: { startCol: string; startId: string; direction: number; edge: string | null; maxDepth: number };
1198
-
1199
- constructor(private readonly client: HakoClient, private readonly collection: string) { }
1200
-
1201
- where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
1202
- this.filters.push({ field, op, value });
1203
- return this;
1204
- }
1205
-
1206
- orWhere(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith', value: any): Query {
1207
- this.orFilters.push({ field, op, value });
1208
- return this;
1209
- }
1210
-
1211
- startAfter(snapshot: DocumentSnapshot): Query {
1212
- this._startAfterSnapshot = snapshot;
1213
- return this;
1214
- }
1215
-
1216
- /** Keyset anchor from a raw row — no decode. Prefer one anchor kind. */
1217
- startAfterRaw(snap: RawQuerySnapshot, index: number): Query {
1218
- this._startAfterRawAnchor = { snap, index };
1219
- return this;
1220
- }
1221
-
1222
- startAt(snapshot: DocumentSnapshot): Query {
1223
- this._startAtSnapshot = snapshot;
1224
- return this;
1225
- }
1226
-
1227
- endAt(snapshot: DocumentSnapshot): Query {
1228
- this._endAtSnapshot = snapshot;
1229
- return this;
1230
- }
1231
-
1232
- endBefore(snapshot: DocumentSnapshot): Query {
1233
- this._endBeforeSnapshot = snapshot;
1234
- return this;
1235
- }
1236
-
1237
- orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
1238
- this.order = { field, ascending: direction === 'asc' };
1239
- return this;
1240
- }
1241
-
1242
- limit(max: number): Query {
1243
- this.queryLimit = max;
1244
- return this;
1245
- }
1246
-
1247
- offset(skip: number): Query {
1248
- this.queryOffset = skip;
1249
- return this;
1250
- }
1251
-
1252
- select(...fields: string[]): Query {
1253
- this.projection = fields;
1254
- return this;
1255
- }
1256
-
1257
- deferBlobs(defer = true): Query {
1258
- this.deferBlobsDef = defer;
1259
- return this;
1260
- }
1261
-
1262
- /** Array-of-objects predicate: every element must match all filters (F3). */
1263
- whereElemMatch(field: string, filters: ElemFilter[]): Query {
1264
- this.filters.push({ field, op: 'elemMatch', value: filters });
1265
- return this;
1266
- }
1267
-
1268
- /** Array predicate: every element equals value (scalar JSON) (F3). */
1269
- whereArrayAllEq(field: string, value: unknown): Query {
1270
- this.filters.push({ field, op: 'arrayAllEq', value });
1271
- return this;
1272
- }
1273
-
1274
- /** KNN marker; the result cap rides limit() (F3). */
1275
- whereNear(field: string, vec: number[] | Float32Array): Query {
1276
- this.near = { field, vec: vec instanceof Float32Array ? vec : Float32Array.from(vec) };
1277
- return this;
1278
- }
1279
-
1280
- /** BFS graph marker; edge null = any reference field (F3). */
1281
- whereTraverse(
1282
- startCol: string,
1283
- startId: string,
1284
- direction: TraverseDirection = 'outgoing',
1285
- edge: string | null = null,
1286
- maxDepth = 3
1287
- ): Query {
1288
- const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1289
- this.traverse = { startCol, startId, direction: dir, edge, maxDepth };
1290
- return this;
1291
- }
1292
-
1293
- private prepareNativeQuery(): unknown {
1294
- const native = this.client.nativeBindings();
1295
- const handle = native.queryNew(this.collection);
1296
- if (!handle) throw new Error(`queryNew failed: ${native.lastError()}`);
1297
-
1298
- try {
1299
- for (const filter of this.filters) {
1300
- switch (filter.op) {
1301
- case '==':
1302
- if (typeof filter.value === 'string') {
1303
- ensureOk(native.queryWhereEqStr(handle, filter.field, filter.value), native, 'queryWhereEqStr');
1304
- } else if (typeof filter.value === 'boolean') {
1305
- ensureOk(native.queryWhereEqBool(handle, filter.field, filter.value), native, 'queryWhereEqBool');
1306
- } else {
1307
- ensureOk(native.queryWhereEqInt(handle, filter.field, filter.value), native, 'queryWhereEqInt');
1308
- }
1309
- break;
1310
- case '!=':
1311
- case '>':
1312
- case '>=':
1313
- case '<':
1314
- case '<=':
1315
- if (typeof filter.value === 'string') {
1316
- if (filter.op === '!=') ensureOk(native.queryWhereNeStr(handle, filter.field, filter.value), native, 'queryWhereNeStr');
1317
- else if (filter.op === '>') ensureOk(native.queryWhereGtStr(handle, filter.field, filter.value), native, 'queryWhereGtStr');
1318
- else if (filter.op === '>=') ensureOk(native.queryWhereGteStr(handle, filter.field, filter.value), native, 'queryWhereGteStr');
1319
- else if (filter.op === '<') ensureOk(native.queryWhereLtStr(handle, filter.field, filter.value), native, 'queryWhereLtStr');
1320
- else ensureOk(native.queryWhereLteStr(handle, filter.field, filter.value), native, 'queryWhereLteStr');
1321
- } else {
1322
- if (filter.op === '!=') ensureOk(native.queryWhereNeInt(handle, filter.field, filter.value), native, 'queryWhereNeInt');
1323
- else if (filter.op === '>') ensureOk(native.queryWhereGtInt(handle, filter.field, filter.value), native, 'queryWhereGtInt');
1324
- else if (filter.op === '>=') ensureOk(native.queryWhereGteInt(handle, filter.field, filter.value), native, 'queryWhereGteInt');
1325
- else if (filter.op === '<') ensureOk(native.queryWhereLtInt(handle, filter.field, filter.value), native, 'queryWhereLtInt');
1326
- else ensureOk(native.queryWhereLteInt(handle, filter.field, filter.value), native, 'queryWhereLteInt');
1327
- }
1328
- break;
1329
- case 'match':
1330
- ensureOk(native.queryWhereMatch(handle, filter.field, String(filter.value)), native, 'queryWhereMatch');
1331
- break;
1332
- case 'matchPrefix':
1333
- ensureOk(native.queryWhereMatchPrefix(handle, filter.field, String(filter.value)), native, 'queryWhereMatchPrefix');
1334
- break;
1335
- case 'contains':
1336
- ensureOk(native.queryWhereContains(handle, filter.field, String(filter.value)), native, 'queryWhereContains');
1337
- break;
1338
- case 'startsWith':
1339
- ensureOk(native.queryWhereStartsWith(handle, filter.field, String(filter.value)), native, 'queryWhereStartsWith');
1340
- break;
1341
- case 'in':
1342
- case 'not-in':
1343
- case 'array-contains-any':
1344
- const arr = native.arrayNew();
1345
- (filter.value as any[]).forEach(v => {
1346
- if (typeof v === 'string') native.arrayAppendStr(arr, v);
1347
- else native.arrayAppendInt(arr, v);
1348
- });
1349
- if (filter.op === 'in') ensureOk(native.queryWhereIn(handle, filter.field, arr), native, 'queryWhereIn');
1350
- else if (filter.op === 'not-in') ensureOk(native.queryWhereNotIn(handle, filter.field, arr), native, 'queryWhereNotIn');
1351
- else ensureOk(native.queryWhereArrayContainsAny(handle, filter.field, arr), native, 'queryWhereArrayContainsAny');
1352
- break;
1353
- case 'array-contains':
1354
- if (typeof filter.value === 'string') ensureOk(native.queryWhereArrayContainsStr(handle, filter.field, filter.value), native, 'queryWhereArrayContainsStr');
1355
- else ensureOk(native.queryWhereArrayContainsInt(handle, filter.field, filter.value), native, 'queryWhereArrayContainsInt');
1356
- break;
1357
- case 'elemMatch':
1358
- ensureOk(native.queryWhereElemMatch(handle, filter.field, JSON.stringify(filter.value)), native, 'queryWhereElemMatch');
1359
- break;
1360
- case 'arrayAllEq':
1361
- ensureOk(native.queryWhereArrayAllEq(handle, filter.field, JSON.stringify(filter.value)), native, 'queryWhereArrayAllEq');
1362
- break;
1363
- }
1364
- }
1365
-
1366
- for (const filter of this.orFilters) {
1367
- if (typeof filter.value === 'string') {
1368
- ensureOk(native.queryWhereOrStr(handle, filter.field, filter.value), native, 'queryWhereOrStr');
1369
- } else {
1370
- ensureOk(native.queryWhereOrInt(handle, filter.field, filter.value), native, 'queryWhereOrInt');
1371
- }
1372
- }
1373
-
1374
- if (this._startAtSnapshot?._nativeHandle) {
1375
- ensureOk(native.queryStartAt(handle, this._startAtSnapshot._nativeHandle), native, 'queryStartAt');
1376
- }
1377
- if (this._startAfterSnapshot?._nativeHandle) {
1378
- ensureOk(native.queryStartAfter(handle, this._startAfterSnapshot._nativeHandle), native, 'queryStartAfter');
1379
- }
1380
- if (this._startAfterRawAnchor) {
1381
- ensureOk(native.queryStartAfterRaw(handle, this._startAfterRawAnchor.snap.rawHandleAt(this._startAfterRawAnchor.index)), native, 'queryStartAfterRaw');
1382
- }
1383
- if (this._endAtSnapshot?._nativeHandle) {
1384
- ensureOk(native.queryEndAt(handle, this._endAtSnapshot._nativeHandle), native, 'queryEndAt');
1385
- }
1386
- if (this._endBeforeSnapshot?._nativeHandle) {
1387
- ensureOk(native.queryEndBefore(handle, this._endBeforeSnapshot._nativeHandle), native, 'queryEndBefore');
1388
- }
1389
-
1390
- if (this.near) ensureOk(native.queryWhereNear(handle, this.near.field, this.near.vec), native, 'queryWhereNear');
1391
- if (this.traverse) {
1392
- const t = this.traverse;
1393
- ensureOk(native.queryWhereTraverse(handle, t.startCol, t.startId, t.direction, t.edge, t.maxDepth), native, 'queryWhereTraverse');
1394
- }
1395
-
1396
- if (this.order) ensureOk(native.queryOrderBy(handle, this.order.field, this.order.ascending), native, 'queryOrderBy');
1397
- if (this.queryLimit !== undefined) ensureOk(native.queryLimit(handle, this.queryLimit), native, 'queryLimit');
1398
- if (this.queryOffset !== undefined) ensureOk(native.queryOffset(handle, this.queryOffset), native, 'queryOffset');
1399
- for (const field of this.projection) ensureOk(native.querySelectField(handle, field), native, 'querySelectField');
1400
- if (this.deferBlobsDef) ensureOk(native.queryDeferBlobs(handle, true), native, 'queryDeferBlobs');
1401
-
1402
- return handle;
1403
- } catch (err) {
1404
- native.queryFree(handle);
1405
- throw err;
1406
- }
1407
- }
1408
-
1409
- async get(): Promise<HakoDocData[]> {
1410
- const native = this.client.nativeBindings();
1411
- const handle = this.prepareNativeQuery();
1412
- try {
1413
- return parseQueryRows(native.queryExecute(this.client.engineHandle(), handle));
1414
- } finally {
1415
- native.queryFree(handle);
1416
- }
1417
- }
1418
-
1419
- /**
1420
- * P2 fast path (core 0.18+): rows serialized from pinned bytes, same
1421
- * shape as get(). Projections keep the projected executor's shape.
1422
- */
1423
- async getJson(): Promise<HakoDocData[]> {
1424
- const native = this.client.nativeBindings();
1425
- const handle = this.prepareNativeQuery();
1426
- try {
1427
- return parseQueryRows(native.queryExecuteJson(this.client.engineHandle(), handle));
1428
- } finally {
1429
- native.queryFree(handle);
1430
- }
1431
- }
1432
-
1433
- /** Query plan JSON without executing the scan (F7). */
1434
- async explain(): Promise<Record<string, unknown> | null> {
1435
- const native = this.client.nativeBindings();
1436
- const handle = this.prepareNativeQuery();
1437
- try {
1438
- const json = native.queryExplain(this.client.engineHandle(), handle);
1439
- return json ? (JSON.parse(json) as Record<string, unknown>) : null;
1440
- } finally {
1441
- native.queryFree(handle);
1442
- }
1443
- }
1444
-
1445
- /**
1446
- * Raw page: no decode, no JSON. Walk it with count/resolve, page with
1447
- * startAfterRaw, free when done. Scan-many/touch-few is the shape this
1448
- * pays for; resolving every row costs the same as get().
1449
- */
1450
- async getRaw(): Promise<RawQuerySnapshot> {
1451
- const native = this.client.nativeBindings();
1452
- const handle = this.prepareNativeQuery();
1453
- try {
1454
- const rs = native.queryExecuteRaw(this.client.engineHandle(), handle);
1455
- if (!rs) throw new Error(`queryExecuteRaw failed: ${native.lastError()}`);
1456
- return new RawQuerySnapshot(this.client, this.collection, rs);
1457
- } finally {
1458
- native.queryFree(handle);
1459
- }
1460
- }
1461
-
1462
- async delete(): Promise<number> {
1463
- const native = this.client.nativeBindings();
1464
- const handle = this.prepareNativeQuery();
1465
- try {
1466
- const n = native.queryDelete(this.client.engineHandle(), handle);
1467
- if (n < 0) throw new Error(`queryDelete failed: ${native.lastError()}`);
1468
- return n;
1469
- } finally {
1470
- native.queryFree(handle);
1471
- }
1472
- }
1473
-
1474
- /** Local-only mass delete: matched docs never leave this device. */
1475
- async deleteLocal(): Promise<number> {
1476
- const native = this.client.nativeBindings();
1477
- const handle = this.prepareNativeQuery();
1478
- try {
1479
- const n = native.queryDeleteLocal(this.client.engineHandle(), handle);
1480
- if (n < 0) throw new Error(`queryDeleteLocal failed: ${native.lastError()}`);
1481
- return n;
1482
- } finally {
1483
- native.queryFree(handle);
1484
- }
1485
- }
1486
-
1487
- async patch(data: HakoDocData): Promise<number> {
1488
- const native = this.client.nativeBindings();
1489
- const handle = this.prepareNativeQuery();
1490
- const patchDoc = toNativeDoc(native, data);
1491
- try {
1492
- const n = native.queryPatch(this.client.engineHandle(), handle, patchDoc);
1493
- if (n < 0) throw new Error(`queryPatch failed: ${native.lastError()}`);
1494
- return n;
1495
- } finally {
1496
- native.docFree(patchDoc);
1497
- native.queryFree(handle);
1498
- }
1499
- }
1500
-
1501
- async count(): Promise<number> {
1502
- const native = this.client.nativeBindings();
1503
- const handle = this.prepareNativeQuery();
1504
- try {
1505
- ensureOk(native.queryAggregateCount(handle), native, 'queryAggregateCount');
1506
- const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1507
- return json ? (JSON.parse(json).count || 0) : 0;
1508
- } finally {
1509
- native.queryFree(handle);
1510
- }
1511
- }
1512
-
1513
- async sum(field: string): Promise<number> {
1514
- const native = this.client.nativeBindings();
1515
- const handle = this.prepareNativeQuery();
1516
- try {
1517
- ensureOk(native.queryAggregateSum(handle, field), native, 'queryAggregateSum');
1518
- const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1519
- return json ? (JSON.parse(json)[`sum_${field}`] || 0) : 0;
1520
- } finally {
1521
- native.queryFree(handle);
1522
- }
1523
- }
1524
-
1525
- async avg(field: string): Promise<number> {
1526
- const native = this.client.nativeBindings();
1527
- const handle = this.prepareNativeQuery();
1528
- try {
1529
- ensureOk(native.queryAggregateAvg(handle, field), native, 'queryAggregateAvg');
1530
- const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1531
- return json ? (JSON.parse(json)[`avg_${field}`] || 0) : 0;
1532
- } finally {
1533
- native.queryFree(handle);
1534
- }
1535
- }
1536
-
1537
- /** `null` when no matching document has a numeric `field`. */
1538
- async min(field: string): Promise<number | null> {
1539
- const native = this.client.nativeBindings();
1540
- const handle = this.prepareNativeQuery();
1541
- try {
1542
- ensureOk(native.queryAggregateMin(handle, field), native, 'queryAggregateMin');
1543
- const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1544
- return json ? (JSON.parse(json)[`min_${field}`] ?? null) : null;
1545
- } finally {
1546
- native.queryFree(handle);
1547
- }
1548
- }
1549
-
1550
- /** `null` when no matching document has a numeric `field`. */
1551
- async max(field: string): Promise<number | null> {
1552
- const native = this.client.nativeBindings();
1553
- const handle = this.prepareNativeQuery();
1554
- try {
1555
- ensureOk(native.queryAggregateMax(handle, field), native, 'queryAggregateMax');
1556
- const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1557
- return json ? (JSON.parse(json)[`max_${field}`] ?? null) : null;
1558
- } finally {
1559
- native.queryFree(handle);
1560
- }
1561
- }
1562
-
1563
- onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
1564
- const native = this.client.nativeBindings();
1565
- const internalWatcher: WatchCallback = async () => {
1566
- const data = await this.get();
1567
- callback(data);
1568
- };
1569
- const watchHandle = native.engineWatch(this.client.engineHandle(), this.collection, internalWatcher);
1570
- this.get().then(callback);
1571
- return async () => { native.watchFree(watchHandle); };
1572
- }
1573
- }
1574
-
1575
- export class WriteBatch {
1576
- private readonly native: NativeBindings;
1577
- private readonly handle: unknown;
1578
- private committed = false;
1579
-
1580
- constructor(private readonly client: HakoClient) {
1581
- this.native = client.nativeBindings();
1582
- this.handle = this.native.batchNew();
1583
- if (!this.handle) throw new Error(`batchNew failed: ${this.native.lastError()}`);
1584
- }
1585
-
1586
- set(docRef: DocumentReference, data: HakoDocData): WriteBatch {
1587
- this.ensureActive();
1588
- const doc = toNativeDoc(this.native, data);
1589
- try {
1590
- ensureOk(this.native.batchSet(this.handle, docRef._collection, docRef._id, doc), this.native, 'batchSet');
1591
- return this;
1592
- } finally {
1593
- this.native.docFree(doc);
1594
- }
1595
- }
1596
-
1597
- delete(docRef: DocumentReference): WriteBatch {
1598
- this.ensureActive();
1599
- ensureOk(this.native.batchDelete(this.handle, docRef._collection, docRef._id), this.native, 'batchDelete');
1600
- return this;
1601
- }
1602
-
1603
- /** Batch delete with an explicit mode: 0/soft = restoreable, force = legacy
1604
- * tombstone-only. batchDelete() keeps legacy/force for frozen contracts. */
1605
- deleteEx(docRef: DocumentReference, force: boolean): WriteBatch {
1606
- this.ensureActive();
1607
- ensureOk(this.native.batchDeleteEx(this.handle, docRef._collection, docRef._id, force), this.native, 'batchDeleteEx');
1608
- return this;
1609
- }
1610
-
1611
- async commit(): Promise<void> {
1612
- this.ensureActive();
1613
- ensureOk(this.native.batchCommit(this.client.engineHandle(), this.handle), this.native, 'batchCommit');
1614
- this.native.batchFree(this.handle);
1615
- this.committed = true;
1616
- }
1617
-
1618
- dispose(): void {
1619
- if (this.committed) return;
1620
- this.native.batchFree(this.handle);
1621
- this.committed = true;
1622
- }
1623
-
1624
- private ensureActive(): void {
1625
- if (this.committed) throw new Error('WriteBatch is already committed/disposed');
1626
- }
1627
- }
1
+ import { loadNativeBindings, type NativeBindings, type WatchCallback } from './native';
2
+
3
+ // 1. UPDATED: Recursive Type Definitions to support Nested Maps and Arrays
4
+ // export type Primitive = string | number | boolean | null | Uint8Array | Date | HakoDocData | Array<any>;
5
+ export type Primitive =
6
+ | string
7
+ | number
8
+ | boolean
9
+ | null
10
+ | Uint8Array
11
+ | Date
12
+ | HakoReference
13
+ | { [key: string]: Primitive }
14
+ | Primitive[];
15
+
16
+
17
+ export type HakoDocData = { [key: string]: Primitive };
18
+
19
+ /** Distance metric for vector indexes (matches core Metric::from_u32). */
20
+ export type VectorMetric = 'cosine' | 'l2';
21
+
22
+ /** One KNN hit: doc id, exact metric distance, and the doc itself. */
23
+ export interface NearHit {
24
+ id: string;
25
+ score: number;
26
+ doc: HakoDocData;
27
+ }
28
+
29
+ /** Traversal direction (matches core TraverseDir::from_u32). */
30
+ export type TraverseDirection = 'outgoing' | 'incoming' | 'both';
31
+
32
+ /** One graph hit: collection + id (paths cross collections), BFS depth, doc. */
33
+ export interface PathHit {
34
+ collection: string;
35
+ id: string;
36
+ depth: number;
37
+ cost?: number;
38
+ doc: HakoDocData;
39
+ /** Route projections, only present when opted in via PathOptions. */
40
+ path?: string[];
41
+ /** Edge docs as JSON strings; null for anonymous edges. */
42
+ via?: (string | null)[];
43
+ }
44
+
45
+ /** A predicate: docs whose `field` equals `equals` travel (or stop). */
46
+ export interface PathFilter {
47
+ field: string;
48
+ equals: unknown;
49
+ }
50
+
51
+ /** v0.19 traverse extensions shared by findPathsFull/shortestPathsFull/exportGraph/graphAnalysis. */
52
+ export interface PathOptions {
53
+ direction?: TraverseDirection;
54
+ edge?: string | null;
55
+ via?: string | null;
56
+ maxDepth?: number;
57
+ k?: number;
58
+ includePath?: boolean;
59
+ includeVia?: boolean;
60
+ nodeFilter?: PathFilter;
61
+ edgeType?: PathFilter;
62
+ edgeMatch?: PathFilter;
63
+ /** Shortest paths only: numeric prop name on edge docs (null = uniform 1.0). */
64
+ weight?: string | null;
65
+ }
66
+
67
+ function resolvePathOptions(opts: PathOptions) {
68
+ const f = (p?: PathFilter) => (p ? { field: p.field, json: JSON.stringify(p.equals ?? null) } : { field: null, json: null });
69
+ const node = f(opts.nodeFilter);
70
+ const type = f(opts.edgeType);
71
+ const match = f(opts.edgeMatch);
72
+ return {
73
+ direction: opts.direction === 'incoming' ? 1 : opts.direction === 'both' ? 2 : 0,
74
+ edge: opts.edge ?? null,
75
+ via: opts.via ?? null,
76
+ maxDepth: opts.maxDepth ?? 10,
77
+ k: opts.k ?? 100,
78
+ includePath: opts.includePath ?? false,
79
+ includeVia: opts.includeVia ?? false,
80
+ nodeField: node.field,
81
+ nodeJSON: node.json,
82
+ typeField: type.field,
83
+ typeJSON: type.json,
84
+ matchField: match.field,
85
+ matchJSON: match.json,
86
+ weight: opts.weight ?? null,
87
+ };
88
+ }
89
+
90
+ const SERVER_TIMESTAMP_SENTINEL = "__FL_SERVER_TIMESTAMP__";
91
+
92
+ export class HakoReference {
93
+ constructor(public readonly collection: string, public readonly id: string) {}
94
+ }
95
+
96
+ export enum DurabilityMode {
97
+ Always = 0,
98
+ Interval = 1,
99
+ Manual = 2,
100
+ OnCommit = 3,
101
+ }
102
+
103
+ export enum CloudSyncMode {
104
+ Server = 0,
105
+ Client = 1,
106
+ }
107
+
108
+ export interface HakoClientOptions {
109
+ libraryPath?: string;
110
+ native?: NativeBindings;
111
+ config?: HakoConfig;
112
+ }
113
+
114
+ // 2. FIXED: Added 'in' to the interface to match the Query class
115
+ export interface QueryConstraint {
116
+ field: string;
117
+ op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any' | 'elemMatch' | 'arrayAllEq';
118
+ value: any; // Use any because 'in' takes an array
119
+ }
120
+
121
+ /** One element-relative predicate for whereElemMatch (F3). */
122
+ export interface ElemFilter {
123
+ field: string;
124
+ op: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'match' | 'match_prefix' | 'contains' | 'starts_with' | 'in' | 'not_in' | 'array_contains' | 'array_contains_any' | 'array_all_eq';
125
+ value: unknown;
126
+ }
127
+
128
+ export interface QueryOrder {
129
+ field: string;
130
+ ascending: boolean;
131
+ }
132
+
133
+ /** One declared field rule (F8). Kind names match the core wire format. */
134
+ export interface HakoFieldRule {
135
+ name: string;
136
+ kind: 'string' | 'int' | 'float' | 'bool' | 'null' | 'array' | 'map' | 'bytes' | 'timestamp' | 'any';
137
+ required?: boolean;
138
+ default?: unknown;
139
+ }
140
+
141
+ /** Per-collection schema declaration (F8). Empty fields = no constraints. */
142
+ export interface HakoSchema {
143
+ fields: HakoFieldRule[];
144
+ }
145
+
146
+ export type Unsubscribe = () => Promise<void>;
147
+
148
+ /**
149
+ * Advanced Configuration Builder
150
+ */
151
+ export class HakoConfig {
152
+ private _handle: unknown;
153
+ private _native: NativeBindings;
154
+
155
+ constructor(native: NativeBindings) {
156
+ this._native = native;
157
+ this._handle = native.configNew();
158
+ }
159
+
160
+ /** Reuse these bindings instead of loading the DLL twice in one process
161
+ * (koffi rejects duplicate type registration on a second load). */
162
+ getNativeBindings(): NativeBindings {
163
+ return this._native;
164
+ }
165
+
166
+ setDurability(mode: DurabilityMode): this {
167
+ this._native.configSetDurability(this._handle, mode);
168
+ return this;
169
+ }
170
+
171
+ setEncryptionKey(key: string): this {
172
+ this._native.configSetEncryptionKey(this._handle, key);
173
+ return this;
174
+ }
175
+
176
+ setAuditLog(enabled: boolean, path: string | null = null): this {
177
+ this._native.configSetAuditLog(this._handle, enabled, path);
178
+ return this;
179
+ }
180
+
181
+ setQueryWorkers(count: number): this {
182
+ this._native.configSetQueryWorkers(this._handle, count);
183
+ return this;
184
+ }
185
+
186
+ setMemoryLimits(mmapBytes: number, maxInlinedBytes: number): this {
187
+ this._native.configSetMemoryLimits(this._handle, mmapBytes, maxInlinedBytes);
188
+ return this;
189
+ }
190
+
191
+ setStorageTuning(pageSize: number, threshold: number, groupCommitMaxOps: number): this {
192
+ this._native.configSetStorageTuning(this._handle, pageSize, threshold, groupCommitMaxOps);
193
+ return this;
194
+ }
195
+
196
+ setEncryptedCollections(collections: string[]): this {
197
+ ensureOk(this._native.configSetEncryptedCollections(this._handle, JSON.stringify(collections)), this._native, 'setEncryptedCollections');
198
+ return this;
199
+ }
200
+
201
+ setBlobThreshold(thresholdBytes: number): this {
202
+ this._native.configSetBlobThreshold(this._handle, thresholdBytes);
203
+ return this;
204
+ }
205
+
206
+ setCompression(enabled: boolean, level: number = 3): this {
207
+ this._native.configSetCompression(this._handle, enabled, level);
208
+ return this;
209
+ }
210
+
211
+ setGroupCommitIntervalMs(ms: number): this {
212
+ this._native.configSetGroupCommitIntervalMs(this._handle, ms);
213
+ return this;
214
+ }
215
+
216
+ setPageCacheCapacity(capacity: number): this {
217
+ this._native.configSetPageCacheCapacity(this._handle, capacity);
218
+ return this;
219
+ }
220
+
221
+ setSyncExcluded(...collections: string[]): this {
222
+ ensureOk(this._native.configSetSyncExcluded(this._handle, JSON.stringify(collections)), this._native, 'configSetSyncExcluded');
223
+ return this;
224
+ }
225
+
226
+ setLazyCollections(...collections: string[]): this {
227
+ ensureOk(this._native.configSetLazyCollections(this._handle, JSON.stringify(collections)), this._native, 'configSetLazyCollections');
228
+ return this;
229
+ }
230
+
231
+ setReplicationCollections(...collections: string[]): this {
232
+ ensureOk(this._native.configSetReplicationCollections(this._handle, JSON.stringify(collections)), this._native, 'configSetReplicationCollections');
233
+ return this;
234
+ }
235
+
236
+ getHandle(): unknown {
237
+ return this._handle;
238
+ }
239
+ }
240
+
241
+ function ensureOk(code: number, native: NativeBindings, ctx: string): void {
242
+ if (code !== 0) {
243
+ throw new Error(`${ctx}: ${native.lastError()}`);
244
+ }
245
+ }
246
+
247
+ function parseDocJson(json: string | null): HakoDocData {
248
+ if (!json) return {};
249
+ return JSON.parse(json) as HakoDocData;
250
+ }
251
+
252
+ function parseQueryRows(json: string | null): HakoDocData[] {
253
+ if (!json) return [];
254
+ const parsed = JSON.parse(json);
255
+ return Array.isArray(parsed) ? (parsed as HakoDocData[]) : [];
256
+ }
257
+
258
+ /**
259
+ * Recursive field inserter (v0.5.9)
260
+ */
261
+ function insertField(native: NativeBindings, handle: unknown, key: string, value: Primitive): void {
262
+ if (value === SERVER_TIMESTAMP_SENTINEL) {
263
+ ensureOk(native.docInsertServerTimestamp(handle, key), native, 'serverTimestamp');
264
+ return;
265
+ }
266
+ if (value instanceof Date) {
267
+ native.docInsertTimestamp(handle, key, BigInt(value.getTime()) * 1000n);
268
+ return;
269
+ }
270
+ if (value instanceof Uint8Array) {
271
+ ensureOk(native.docInsertBin(handle, key, value), native, 'insertBin');
272
+ return;
273
+ }
274
+ if (value instanceof HakoReference) {
275
+ ensureOk(native.docInsertReference(handle, key, value.collection, value.id), native, 'insertReference');
276
+ return;
277
+ }
278
+
279
+ if (Array.isArray(value)) {
280
+ const arrHandle = native.arrayNew();
281
+ for (const item of value) {
282
+ if (typeof item === 'string') native.arrayAppendStr(arrHandle, item);
283
+ else if (typeof item === 'number') native.arrayAppendInt(arrHandle, item);
284
+ else if (typeof item === 'object' && item !== null) {
285
+ const tempDoc = toNativeDoc(native, item as HakoDocData);
286
+ native.arrayAppendDoc(arrHandle, tempDoc);
287
+ native.docFree(tempDoc); // FFI copies data into the array
288
+ }
289
+ }
290
+ // ownership transfers to parent doc handle
291
+ ensureOk(native.docInsertArray(handle, key, arrHandle), native, 'insertArray');
292
+ return;
293
+ }
294
+
295
+ if (typeof value === 'object' && value !== null) {
296
+ const childDocHandle = toNativeDoc(native, value as HakoDocData);
297
+ ensureOk(native.docInsertDoc(handle, key, childDocHandle), native, 'insertDoc');
298
+ native.docFree(childDocHandle); // FFI copies data into the parent
299
+ return;
300
+ }
301
+
302
+ // Primitives (string, number, bool, null)
303
+ if (typeof value === 'string') {
304
+ ensureOk(native.docInsertStr(handle, key, value), native, 'insertStr');
305
+ } else if (typeof value === 'number') {
306
+ if (Number.isInteger(value)) ensureOk(native.docInsertInt(handle, key, value), native, 'insertInt');
307
+ else ensureOk(native.docInsertFloat(handle, key, value), native, 'insertFloat');
308
+ } else if (typeof value === 'boolean') {
309
+ ensureOk(native.docInsertBool(handle, key, value), native, 'insertBool');
310
+ } else if (value === null) {
311
+ ensureOk(native.docInsertNull(handle, key), native, 'insertNull');
312
+ }
313
+ }
314
+
315
+ function toNativeDoc(native: NativeBindings, data: HakoDocData): unknown {
316
+ const doc = native.docNew();
317
+ if (!doc) throw new Error(`docNew failed: ${native.lastError()}`);
318
+ try {
319
+ for (const [key, value] of Object.entries(data)) {
320
+ insertField(native, doc, key, value);
321
+ }
322
+ return doc;
323
+ } catch (err) {
324
+ native.docFree(doc);
325
+ throw err;
326
+ }
327
+ }
328
+
329
+ export class DocumentSnapshot {
330
+ constructor(
331
+ public readonly id: string,
332
+ public readonly exists: boolean,
333
+ private readonly payload?: HakoDocData,
334
+ public readonly _nativeHandle?: unknown
335
+ ) { }
336
+
337
+ data(): HakoDocData | undefined {
338
+ return this.payload;
339
+ }
340
+ }
341
+
342
+ /**
343
+ * One raw page: pinned storage bytes per row (v0.8.3+). Decode nothing
344
+ * up front — resolve() only rows you touch, page with
345
+ * Query.startAfterRaw() (no decode at all). Free when done; rows die
346
+ * with the page.
347
+ */
348
+ export class RawQuerySnapshot {
349
+ private freed = false;
350
+
351
+ constructor(
352
+ private readonly client: HakoClient,
353
+ private readonly collection: string,
354
+ private readonly handle: unknown
355
+ ) { }
356
+
357
+ get count(): number {
358
+ return this.client.nativeBindings().rawResultCount(this.handle);
359
+ }
360
+
361
+ /** Decode + inflate one row. Prefer resolving only rows you touch. */
362
+ async resolve(index: number): Promise<HakoDocData | undefined> {
363
+ const native = this.client.nativeBindings();
364
+ const doc = native.rawDocToDoc(this.client.engineHandle(), this.rawHandleAt(index), this.collection);
365
+ if (!doc) return undefined;
366
+ try {
367
+ return parseDocJson(native.docToJson(doc));
368
+ } finally {
369
+ native.docFree(doc);
370
+ }
371
+ }
372
+
373
+ /** Borrowed native raw handle. Valid until free(). Internal. */
374
+ rawHandleAt(index: number): unknown {
375
+ return this.client.nativeBindings().rawResultGet(this.handle, index);
376
+ }
377
+
378
+ free(): void {
379
+ if (!this.freed) {
380
+ this.freed = true;
381
+ this.client.nativeBindings().rawResultFree(this.handle);
382
+ }
383
+ }
384
+ }
385
+
386
+ /**
387
+ * One borrowed row (v0.8.11+): lazy numeric/bool pulls with no decode
388
+ * and no JSON. Strings stay on resolve() (no backend memory reads).
389
+ * Free when done.
390
+ */
391
+ export class ViewDocSnapshot {
392
+ private freed = false;
393
+
394
+ constructor(
395
+ private readonly client: HakoClient,
396
+ private readonly collection: string,
397
+ private readonly docId: string,
398
+ private readonly handle: unknown
399
+ ) { }
400
+
401
+ get id(): string {
402
+ return this.docId;
403
+ }
404
+
405
+ get fieldCount(): number {
406
+ return this.client.nativeBindings().viewFieldCount(this.handle);
407
+ }
408
+
409
+ has(field: string): boolean {
410
+ return this.client.nativeBindings().viewHasField(this.handle, field);
411
+ }
412
+
413
+ getInt(field: string): number | bigint | null {
414
+ return this.client.nativeBindings().viewGetInt(this.handle, field);
415
+ }
416
+
417
+ getFloat(field: string): number | null {
418
+ return this.client.nativeBindings().viewGetFloat(this.handle, field);
419
+ }
420
+
421
+ getBool(field: string): boolean | null {
422
+ return this.client.nativeBindings().viewGetBool(this.handle, field);
423
+ }
424
+
425
+ /** Dotted-path pulls (core 0.18+): `a.b.c` reads without a full decode. */
426
+ getPathInt(path: string): number | bigint | null {
427
+ return this.client.nativeBindings().viewGetPathInt(this.handle, path);
428
+ }
429
+
430
+ getPathFloat(path: string): number | null {
431
+ return this.client.nativeBindings().viewGetPathFloat(this.handle, path);
432
+ }
433
+
434
+ getPathBool(path: string): boolean | null {
435
+ return this.client.nativeBindings().viewGetPathBool(this.handle, path);
436
+ }
437
+
438
+ getPathString(path: string): string | null {
439
+ return this.client.nativeBindings().viewGetPathStr(this.handle, path);
440
+ }
441
+
442
+ getPathBytes(path: string): Uint8Array | null {
443
+ return this.client.nativeBindings().viewGetPathBytes(this.handle, path);
444
+ }
445
+
446
+ /** Full decode + inflate. Prefer pulls for sparse reads. */
447
+ async resolve(): Promise<HakoDocData | undefined> {
448
+ const native = this.client.nativeBindings();
449
+ const doc = native.viewToDoc(this.handle, this.docId);
450
+ if (!doc) return undefined;
451
+ try {
452
+ return parseDocJson(native.docToJson(doc));
453
+ } finally {
454
+ native.docFree(doc);
455
+ }
456
+ }
457
+
458
+ free(): void {
459
+ if (!this.freed) {
460
+ this.freed = true;
461
+ this.client.nativeBindings().viewFree(this.handle);
462
+ }
463
+ }
464
+ }
465
+
466
+ export class HakoClient {
467
+ private readonly native: NativeBindings;
468
+ private readonly engine: unknown;
469
+ private isClosed = false;
470
+
471
+ private constructor(native: NativeBindings, engine: unknown) {
472
+ this.native = native;
473
+ this.engine = engine;
474
+ }
475
+
476
+ static async open(path: string, options?: HakoClientOptions): Promise<HakoClient> {
477
+ const native = options?.native
478
+ ?? options?.config?.getNativeBindings()
479
+ ?? (await loadNativeBindings(options?.libraryPath));
480
+
481
+ let engine: unknown;
482
+ if (options?.config) {
483
+ engine = native.engineOpenWithConfig(path, options.config.getHandle());
484
+ } else {
485
+ engine = native.engineOpen(path);
486
+ }
487
+
488
+ if (!engine) {
489
+ throw new Error(`Failed to open HakoDB: ${native.lastError()}`);
490
+ }
491
+ return new HakoClient(native, engine);
492
+ }
493
+
494
+ static serverTimestamp(): any {
495
+ return SERVER_TIMESTAMP_SENTINEL;
496
+ }
497
+
498
+ static async createConfig(libraryPath?: string): Promise<HakoConfig> {
499
+ const native = await loadNativeBindings(libraryPath);
500
+ return new HakoConfig(native);
501
+ }
502
+
503
+ collection(name: string): CollectionReference {
504
+ this.assertOpen();
505
+ return new CollectionReference(this, name);
506
+ }
507
+
508
+ batch(): WriteBatch {
509
+ this.assertOpen();
510
+ return new WriteBatch(this);
511
+ }
512
+
513
+ async listCollections(): Promise<string[]> {
514
+ this.assertOpen();
515
+ const json = this.native.engineListCollections(this.engine);
516
+ return json ? JSON.parse(json) : [];
517
+ }
518
+
519
+ /** Declare or replace a collection schema (F8). */
520
+ async setSchema(collection: string, schema: HakoSchema): Promise<void> {
521
+ this.assertOpen();
522
+ ensureOk(this.native.engineSetSchema(this.engine, collection, JSON.stringify(schema)), this.native, 'engineSetSchema');
523
+ }
524
+
525
+ /** Absent collection returns null, not an error. */
526
+ async getSchema(collection: string): Promise<HakoSchema | null> {
527
+ this.assertOpen();
528
+ const json = this.native.engineGetSchema(this.engine, collection);
529
+ return json ? (JSON.parse(json) as HakoSchema) : null;
530
+ }
531
+
532
+ async clearSchema(collection: string): Promise<void> {
533
+ this.assertOpen();
534
+ ensureOk(this.native.engineClearSchema(this.engine, collection), this.native, 'engineClearSchema');
535
+ }
536
+
537
+ async listSchemas(): Promise<Record<string, HakoSchema>> {
538
+ this.assertOpen();
539
+ const json = this.native.engineListSchemas(this.engine);
540
+ return json ? (JSON.parse(json) as Record<string, HakoSchema>) : {};
541
+ }
542
+
543
+ /** Read a doc and the commit version it was read at (F5). */
544
+ async getVersioned(collection: string, docId: string): Promise<{ snapshot: DocumentSnapshot; version: bigint } | null> {
545
+ this.assertOpen();
546
+ const { doc, version } = this.native.engineGetVersioned(this.engine, collection, docId);
547
+ if (!doc) return null;
548
+ const json = this.native.docToJson(doc);
549
+ return { snapshot: new DocumentSnapshot(docId, true, parseDocJson(json), doc), version };
550
+ }
551
+
552
+ /** Wait for background index/blob/maintenance work, bounded by timeoutMs. */
553
+ async awaitQuiescent(timeoutMs: number = 5000): Promise<boolean> {
554
+ this.assertOpen();
555
+ return this.native.engineAwaitQuiescent(this.engine, timeoutMs);
556
+ }
557
+
558
+ async quiescenceStatus(): Promise<Record<string, unknown> | null> {
559
+ this.assertOpen();
560
+ const json = this.native.engineQuiescenceStatus(this.engine);
561
+ return json ? (JSON.parse(json) as Record<string, unknown>) : null;
562
+ }
563
+
564
+ createNetSyncer(name: string, roomKey: string): NetSyncer {
565
+ this.assertOpen();
566
+ const handle = this.native.netSyncerNew(this.engine, name, roomKey);
567
+ if (!handle) {
568
+ throw new Error(`netSyncerNew failed: ${this.native.lastError()}`);
569
+ }
570
+ return new NetSyncer(this.native, handle);
571
+ }
572
+
573
+ createCloudSync(
574
+ mode: CloudSyncMode,
575
+ clientId: string | null = null,
576
+ roomName: string | null = null,
577
+ roomKey: string | null = null,
578
+ authToken: string | null = null
579
+ ): CloudSync {
580
+ this.assertOpen();
581
+ const handle = this.native.cloudSyncNew(this.engine, mode, clientId, roomName, roomKey, authToken);
582
+ if (!handle) {
583
+ throw new Error(`cloudSyncNew failed: ${this.native.lastError()}`);
584
+ }
585
+ return new CloudSync(this.native, handle);
586
+ }
587
+
588
+ /**
589
+ * Creates a room-agnostic cloud SERVER ("big cloud server storage"). It is
590
+ * not bound to any room: clients choose their room (and this server) and the
591
+ * server accepts and persists any (roomName, roomKey) pair, storing each
592
+ * room's collections under its own storage prefix and relaying sync only to
593
+ * the members of that room.
594
+ */
595
+ createCloudSyncServer(serverId: string | null = null, authToken: string | null = null, roomName: string | null = null, roomKey: string | null = null): CloudSync {
596
+ this.assertOpen();
597
+ const handle = this.native.cloudSyncServerNew(this.engine, serverId, authToken, roomName, roomKey);
598
+ if (!handle) {
599
+ throw new Error(`cloudSyncServerNew failed: ${this.native.lastError()}`);
600
+ }
601
+ return new CloudSync(this.native, handle);
602
+ }
603
+
604
+ /**
605
+ * Creates an offline-first cloud CLIENT bound to a room of the caller's
606
+ * choosing. The client picks the room (roomName + roomKey) and later picks
607
+ * the server via `CloudSync.start()`.
608
+ */
609
+ createCloudSyncClient(
610
+ clientId: string | null = null,
611
+ roomName: string | null = null,
612
+ roomKey: string | null = null,
613
+ authToken: string | null = null
614
+ ): CloudSync {
615
+ this.assertOpen();
616
+ const handle = this.native.cloudSyncClientNew(this.engine, clientId, roomName, roomKey, authToken);
617
+ if (!handle) {
618
+ throw new Error(`cloudSyncClientNew failed: ${this.native.lastError()}`);
619
+ }
620
+ return new CloudSync(this.native, handle);
621
+ }
622
+
623
+ isIndexesReady(): boolean {
624
+ this.assertOpen();
625
+ return this.native.engineIsIndexesReady(this.engine);
626
+ }
627
+
628
+ async compact(): Promise<void> {
629
+ this.assertOpen();
630
+ ensureOk(this.native.engineCompact(this.engine), this.native, 'engineCompact');
631
+ }
632
+
633
+ async getStats(): Promise<Record<string, unknown>> {
634
+ this.assertOpen();
635
+ const raw = this.native.engineGetStats(this.engine);
636
+ return raw ? JSON.parse(raw) : {};
637
+ }
638
+
639
+ async getAuditLog(): Promise<unknown[]> {
640
+ this.assertOpen();
641
+ const raw = this.native.engineGetAuditLog(this.engine);
642
+ return raw ? JSON.parse(raw) : [];
643
+ }
644
+
645
+ async snapshotIndices(): Promise<void> {
646
+ this.assertOpen();
647
+ ensureOk(this.native.engineSnapshotIndices(this.engine), this.native, 'engineSnapshotIndices');
648
+ }
649
+
650
+ async listIndexes(collection: string | null = null): Promise<unknown> {
651
+ this.assertOpen();
652
+ const raw = this.native.engineListIndexes(this.engine, collection);
653
+ return raw ? JSON.parse(raw) : null;
654
+ }
655
+
656
+ async patch(collection: string, docId: string, data: HakoDocData): Promise<void> {
657
+ this.assertOpen();
658
+ const updates = toNativeDoc(this.native, data);
659
+ try {
660
+ ensureOk(this.native.enginePatch(this.engine, collection, docId, updates), this.native, 'enginePatch');
661
+ } finally {
662
+ this.native.docFree(updates);
663
+ }
664
+ }
665
+
666
+ async insertSubDoc(col: string, id: string, subCol: string, subId: string, data: HakoDocData): Promise<void> {
667
+ this.assertOpen();
668
+ const doc = toNativeDoc(this.native, data);
669
+ try {
670
+ ensureOk(this.native.engineInsertSubDoc(this.engine, col, id, subCol, subId, doc), this.native, 'engineInsertSubDoc');
671
+ } finally {
672
+ this.native.docFree(doc);
673
+ }
674
+ }
675
+
676
+ async getByReference(doc: DocumentSnapshot, fieldKey: string): Promise<DocumentSnapshot | null> {
677
+ this.assertOpen();
678
+ if (!doc._nativeHandle) return null;
679
+ const target = this.native.engineGetByRef(this.engine, doc._nativeHandle, fieldKey);
680
+ if (!target) return null;
681
+ const json = this.native.docToJson(target);
682
+ this.native.docFree(target);
683
+ return new DocumentSnapshot(fieldKey, true, parseDocJson(json));
684
+ }
685
+
686
+ async createCompositeIndex(collection: string, fields: { field: string; desc?: boolean }[]): Promise<number> {
687
+ this.assertOpen();
688
+ const id = this.native.engineCreateIndex(this.engine, collection, JSON.stringify(fields.map(f => ({ field: f.field, desc: !!f.desc }))));
689
+ if (id === 0) throw new Error(`engineCreateIndex failed: ${this.native.lastError()}`);
690
+ return id;
691
+ }
692
+
693
+ async runTransaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
694
+ this.assertOpen();
695
+ const tx = new Transaction(this.native, this.engine);
696
+ try {
697
+ const result = await fn(tx);
698
+ ensureOk(this.native.transactionCommit(this.engine, tx.handle), this.native, 'transactionCommit');
699
+ return result;
700
+ } finally {
701
+ tx.dispose();
702
+ }
703
+ }
704
+
705
+ async backup(destinationPath: string): Promise<void> {
706
+ this.assertOpen();
707
+ ensureOk(this.native.engineBackup(this.engine, destinationPath), this.native, 'engineBackup');
708
+ }
709
+
710
+ async close(): Promise<void> {
711
+ if (this.isClosed) return;
712
+ this.native.engineFree(this.engine);
713
+ this.isClosed = true;
714
+ }
715
+
716
+ async set(collection: string, docId: string, data: HakoDocData): Promise<void> {
717
+ this.assertOpen();
718
+ const doc = toNativeDoc(this.native, data);
719
+ try {
720
+ ensureOk(this.native.engineInsert(this.engine, collection, docId, doc), this.native, 'engineInsert');
721
+ } finally {
722
+ this.native.docFree(doc);
723
+ }
724
+ }
725
+
726
+ async get(collection: string, docId: string): Promise<DocumentSnapshot> {
727
+ this.assertOpen();
728
+ const doc = this.native.engineGet(this.engine, collection, docId);
729
+ if (!doc) return new DocumentSnapshot(docId, false);
730
+
731
+ const json = this.native.docToJson(doc);
732
+ // Keep 'doc' handle for startAfter. Native memory management should be handled
733
+ // by engineFree or manual free if the user keeps thousands of snapshots.
734
+ return new DocumentSnapshot(docId, true, parseDocJson(json), doc);
735
+ }
736
+
737
+ /**
738
+ * P2 fast path (core 0.18+): JSON straight from the pinned bytes, no
739
+ * owned doc handle. Blob links are resolved, so the shape matches get().
740
+ */
741
+ async getJson(collection: string, docId: string): Promise<HakoDocData | null> {
742
+ this.assertOpen();
743
+ const json = this.native.engineGetJson(this.engine, collection, docId);
744
+ return json ? (parseDocJson(json) as HakoDocData) : null;
745
+ }
746
+
747
+ /**
748
+ * Borrowed point view (v0.8.11+): lazy numeric/bool pulls with no decode
749
+ * and no JSON. Returns null when missing. Free the snapshot when done.
750
+ */
751
+ async viewDoc(collection: string, docId: string): Promise<ViewDocSnapshot | null> {
752
+ this.assertOpen();
753
+ const view = this.native.viewGet(this.engine, collection, docId);
754
+ if (!view) return null;
755
+ return new ViewDocSnapshot(this, collection, docId, view);
756
+ }
757
+
758
+ async delete(collection: string, docId: string): Promise<void> {
759
+ this.assertOpen();
760
+ ensureOk(this.native.engineDelete(this.engine, collection, docId), this.native, 'engineDelete');
761
+ }
762
+
763
+ /** Local-only delete: never leaves this device (no sync tailer or handshake transmits it). */
764
+ async deleteLocal(collection: string, docId: string): Promise<void> {
765
+ this.assertOpen();
766
+ ensureOk(this.native.engineDeleteLocal(this.engine, collection, docId), this.native, 'engineDeleteLocal');
767
+ }
768
+
769
+ /** Delete with an explicit mode: force=true reproduces the legacy
770
+ * tombstone-only shape. Default `delete` is soft since core 0.20.0
771
+ * (restoreable via restore() until the sweeper purges the record). */
772
+ async deleteEx(collection: string, docId: string, force: boolean): Promise<void> {
773
+ this.assertOpen();
774
+ ensureOk(this.native.engineDeleteEx(this.engine, collection, docId, force), this.native, 'engineDeleteEx');
775
+ }
776
+
777
+ /** Restore a soft-deleted doc from its retention record (fresh version;
778
+ * consumes the record). Refuses when the id was re-put (cancel rule) or
779
+ * no record exists. */
780
+ async restore(collection: string, docId: string): Promise<void> {
781
+ this.assertOpen();
782
+ ensureOk(this.native.engineRestore(this.engine, collection, docId), this.native, 'engineRestore');
783
+ }
784
+
785
+ /** Restoreable records, all collections or one (soft-delete retention queue). */
786
+ async restoreAvailable(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
787
+ this.assertOpen();
788
+ return JSON.parse(this.native.engineRestoreAvailable(this.engine, collection ?? null) ?? '[]');
789
+ }
790
+
791
+ /** Due-for-sweep subset of the retention queue (same shape as restoreAvailable). */
792
+ async deleteQueue(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
793
+ this.assertOpen();
794
+ return JSON.parse(this.native.engineDeleteQueue(this.engine, collection ?? null) ?? '[]');
795
+ }
796
+
797
+ /** Run one retention sweep pass now; returns the purged record count. */
798
+ async sweepNow(): Promise<number> {
799
+ this.assertOpen();
800
+ const n = this.native.engineSweepNow(this.engine);
801
+ if (n < 0) {
802
+ throw new Error(`engineSweepNow: ${this.native.lastError()}`);
803
+ }
804
+ return n;
805
+ }
806
+
807
+ /** Mark a collection local-only (never syncs) or rejoin it with `local=false`. */
808
+ async setCollectionLocal(collection: string, local: boolean): Promise<void> {
809
+ this.assertOpen();
810
+ ensureOk(this.native.engineSetCollectionLocal(this.engine, collection, local ? 1 : 0), this.native, 'engineSetCollectionLocal');
811
+ }
812
+
813
+ /** Opt a key back into replication (future ops only). */
814
+ async replicateKey(collection: string, docId: string): Promise<void> {
815
+ this.assertOpen();
816
+ ensureOk(this.native.engineReplicateKey(this.engine, collection, docId), this.native, 'engineReplicateKey');
817
+ }
818
+
819
+ /** Opt a whole collection back into replication. */
820
+ async replicateCollection(collection: string): Promise<void> {
821
+ this.assertOpen();
822
+ ensureOk(this.native.engineReplicateCollection(this.engine, collection), this.native, 'engineReplicateCollection');
823
+ }
824
+
825
+ /** Vacuum: purge tombstones (never replicates); next handshake pulls peer state. */
826
+ async vacuumCollection(collection: string): Promise<number> {
827
+ this.assertOpen();
828
+ const n = this.native.engineVacuumCollection(this.engine, collection);
829
+ if (n < 0) throw new Error(`engineVacuumCollection failed: ${this.native.lastError()}`);
830
+ return n;
831
+ }
832
+
833
+ /** Relocate docs by id src -> dst. Returns {moved, missing}; refusals throw. */
834
+ async relocateDocs(src: string, dst: string, ids: string[]): Promise<{ moved: string[]; missing: string[] }> {
835
+ this.assertOpen();
836
+ const json = this.native.engineRelocateDocs(this.engine, src, dst, JSON.stringify(ids));
837
+ if (!json) throw new Error(`engineRelocateDocs failed: ${this.native.lastError()}`);
838
+ return JSON.parse(json);
839
+ }
840
+
841
+ /** Load a lazy collection's snapshot into the index now. */
842
+ async loadCollection(collection: string): Promise<void> {
843
+ this.assertOpen();
844
+ ensureOk(this.native.engineLoadCollection(this.engine, collection), this.native, 'engineLoadCollection');
845
+ }
846
+
847
+ /** Unload a lazy collection (frees RAM; snapshot stays). Refuses non-lazy. */
848
+ async unloadCollection(collection: string): Promise<void> {
849
+ this.assertOpen();
850
+ ensureOk(this.native.engineUnloadCollection(this.engine, collection), this.native, 'engineUnloadCollection');
851
+ }
852
+
853
+ /** Lazy collections currently out of the index. */
854
+ async unloadedCollections(): Promise<string[]> {
855
+ this.assertOpen();
856
+ const json = this.native.engineUnloadedCollections(this.engine);
857
+ return json ? JSON.parse(json) : [];
858
+ }
859
+
860
+ nativeBindings(): NativeBindings { return this.native; }
861
+ engineHandle(): unknown { return this.engine; }
862
+
863
+ private assertOpen(): void {
864
+ if (this.isClosed) throw new Error('HakoClient is already closed');
865
+ }
866
+ }
867
+
868
+ export class NetSyncer {
869
+ private closed = false;
870
+
871
+ constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
872
+
873
+ async start(port: number): Promise<void> {
874
+ ensureOk(this.native.netSyncerStart(this.handle, port), this.native, 'netSyncerStart');
875
+ }
876
+
877
+ /**
878
+ * Discovery transports: 0 = mDNS (desktop default), 1 = UDP broadcast
879
+ * (mobile default, no multicast), 2 = both (mixed groups). Takes effect
880
+ * at start(). Mirrors the CLI `--discovery` flag.
881
+ */
882
+ async setDiscoveryMode(mode: 0 | 1 | 2): Promise<void> {
883
+ ensureOk(this.native.netSyncerSetDiscovery(this.handle, mode), this.native, 'netSyncerSetDiscovery');
884
+ }
885
+
886
+ async status<T = unknown>(): Promise<T | null> {
887
+ const raw = this.native.netSyncerStatus(this.handle);
888
+ return raw ? (JSON.parse(raw) as T) : null;
889
+ }
890
+
891
+ async close(): Promise<void> {
892
+ if (this.closed) return;
893
+ this.native.netSyncerFree(this.handle);
894
+ this.closed = true;
895
+ }
896
+ }
897
+
898
+ export class CloudSync {
899
+ private closed = false;
900
+
901
+ constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
902
+
903
+ async start(address: string): Promise<void> {
904
+ ensureOk(this.native.cloudSyncStart(this.handle, address), this.native, 'cloudSyncStart');
905
+ }
906
+
907
+ async status<T = unknown>(): Promise<T | null> {
908
+ const raw = this.native.cloudSyncStatus(this.handle);
909
+ return raw ? (JSON.parse(raw) as T) : null;
910
+ }
911
+
912
+ stop(): void {
913
+ if (this.closed) return;
914
+ this.native.cloudSyncStop(this.handle);
915
+ }
916
+
917
+ close(): void {
918
+ this.stop();
919
+ this.native.cloudSyncFree(this.handle);
920
+ this.closed = true;
921
+ }
922
+ }
923
+
924
+ export class Transaction {
925
+ private disposed = false;
926
+
927
+ constructor(
928
+ private readonly native: NativeBindings,
929
+ private readonly engine: unknown,
930
+ readonly handle: unknown = native.transactionBegin(engine)
931
+ ) {
932
+ if (!handle) throw new Error(`transactionBegin failed: ${native.lastError()}`);
933
+ }
934
+
935
+ async get(collection: string, docId: string): Promise<DocumentSnapshot> {
936
+ this.ensureActive();
937
+ const doc = this.native.transactionGet(this.engine, this.handle, collection, docId);
938
+ if (!doc) return new DocumentSnapshot(docId, false);
939
+ const json = this.native.docToJson(doc);
940
+ this.native.docFree(doc);
941
+ return new DocumentSnapshot(docId, true, parseDocJson(json));
942
+ }
943
+
944
+ /** Batched read: one snapshot, output aligned with ids; missing ids are null. */
945
+ async getMany(collection: string, ids: string[]): Promise<(HakoDocData | null)[]> {
946
+ this.ensureActive();
947
+ const json = this.native.transactionGetMany(this.engine, this.handle, collection, JSON.stringify(ids));
948
+ if (json === null) throw new Error(`transactionGetMany: ${this.native.lastError()}`);
949
+ return JSON.parse(json) as (HakoDocData | null)[];
950
+ }
951
+
952
+ /** Merge-patch a doc inside the transaction (F5). */
953
+ patch(collection: string, docId: string, data: HakoDocData): this {
954
+ this.ensureActive();
955
+ ensureOk(this.native.transactionPatch(this.engine, this.handle, collection, docId, JSON.stringify(data)), this.native, 'transactionPatch');
956
+ return this;
957
+ }
958
+
959
+ set(collection: string, docId: string, data: HakoDocData): this {
960
+ this.ensureActive();
961
+ const doc = toNativeDoc(this.native, data);
962
+ try {
963
+ ensureOk(this.native.transactionSet(this.handle, collection, docId, doc), this.native, 'transactionSet');
964
+ } finally {
965
+ this.native.docFree(doc);
966
+ }
967
+ return this;
968
+ }
969
+
970
+ dispose(): void {
971
+ if (this.disposed) return;
972
+ this.native.transactionFree(this.handle);
973
+ this.disposed = true;
974
+ }
975
+
976
+ private ensureActive(): void {
977
+ if (this.disposed) throw new Error('Transaction has already been committed/disposed');
978
+ }
979
+ }
980
+
981
+ export class CollectionReference {
982
+ constructor(private readonly client: HakoClient, private readonly name: string) { }
983
+
984
+ doc(id: string): DocumentReference {
985
+ return new DocumentReference(this.client, this.name, id);
986
+ }
987
+
988
+ onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
989
+ return new Query(this.client, this.name).onSnapshot(callback);
990
+ }
991
+
992
+ // 3. FIXED: Updated 'op' signature to include 'in'
993
+ where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
994
+ return new Query(this.client, this.name).where(field, op, value);
995
+ }
996
+
997
+ orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
998
+ return new Query(this.client, this.name).orderBy(field, direction);
999
+ }
1000
+
1001
+ limit(max: number): Query {
1002
+ return new Query(this.client, this.name).limit(max);
1003
+ }
1004
+
1005
+ select(...fields: string[]): Query {
1006
+ return new Query(this.client, this.name).select(...fields);
1007
+ }
1008
+
1009
+ async get(): Promise<HakoDocData[]> {
1010
+ return new Query(this.client, this.name).get();
1011
+ }
1012
+
1013
+ async count(): Promise<number> {
1014
+ return new Query(this.client, this.name).count();
1015
+ }
1016
+
1017
+ whereElemMatch(field: string, filters: ElemFilter[]): Query {
1018
+ return new Query(this.client, this.name).whereElemMatch(field, filters);
1019
+ }
1020
+
1021
+ whereArrayAllEq(field: string, value: unknown): Query {
1022
+ return new Query(this.client, this.name).whereArrayAllEq(field, value);
1023
+ }
1024
+
1025
+ whereNear(field: string, vec: number[] | Float32Array): Query {
1026
+ return new Query(this.client, this.name).whereNear(field, vec);
1027
+ }
1028
+
1029
+ whereTraverse(
1030
+ startCol: string,
1031
+ startId: string,
1032
+ direction: TraverseDirection = 'outgoing',
1033
+ edge: string | null = null,
1034
+ maxDepth = 3
1035
+ ): Query {
1036
+ return new Query(this.client, this.name).whereTraverse(startCol, startId, direction, edge, maxDepth);
1037
+ }
1038
+
1039
+ async createIndex(field: string): Promise<void> {
1040
+ ensureOk(this.client.nativeBindings().createSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createIndex');
1041
+ }
1042
+
1043
+ async createVectorIndex(field: string, dim: number, metric: VectorMetric = 'cosine'): Promise<void> {
1044
+ ensureOk(this.client.nativeBindings().createVectorIndex(this.client.engineHandle(), this.name, field, dim, metric === 'l2' ? 1 : 0), this.client.nativeBindings(), 'createVectorIndex');
1045
+ }
1046
+
1047
+ /** KNN search: nearest-first [{id, score, doc}]. Embeddings are stored as binary LE-f32 (insert a Uint8Array of Float32 bytes). */
1048
+ async findNear(field: string, query: number[] | Float32Array, k = 10): Promise<NearHit[]> {
1049
+ const native = this.client.nativeBindings();
1050
+ const vec = query instanceof Float32Array ? query : Float32Array.from(query);
1051
+ const json = native.engineFindNear(this.client.engineHandle(), this.name, field, vec, k);
1052
+ if (json === null) throw new Error(`findNear failed: ${native.lastError()}`);
1053
+ return JSON.parse(json) as NearHit[];
1054
+ }
1055
+
1056
+ async createTraverseIndex(): Promise<void> {
1057
+ ensureOk(this.client.nativeBindings().createTraverseIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'createTraverseIndex');
1058
+ }
1059
+
1060
+ /** Graph BFS from a doc in this collection: [{collection, id, depth, doc}]. edge null = any ref field. */
1061
+ async findPaths(id: string, direction: TraverseDirection = 'outgoing', edge: string | null = null, maxDepth = 10, k = 100): Promise<PathHit[]> {
1062
+ const native = this.client.nativeBindings();
1063
+ const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1064
+ const json = native.engineFindPaths(this.client.engineHandle(), this.name, id, dir, edge, maxDepth, k);
1065
+ if (json === null) throw new Error(`findPaths failed: ${native.lastError()}`);
1066
+ return JSON.parse(json) as PathHit[];
1067
+ }
1068
+
1069
+ async createEdgeIndex(): Promise<void> {
1070
+ ensureOk(this.client.nativeBindings().createEdgeIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'createEdgeIndex');
1071
+ }
1072
+
1073
+ /** Weighted shortest paths via an edge collection: cost-ordered [{collection, id, depth, cost, doc}]. */
1074
+ async shortestPaths(id: string, via: string, weight: string | null = null, direction: TraverseDirection = 'outgoing', edge: string | null = null, maxDepth = 10, k = 100): Promise<PathHit[]> {
1075
+ const native = this.client.nativeBindings();
1076
+ const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1077
+ const json = native.engineShortestPaths(this.client.engineHandle(), this.name, id, dir, edge, via, weight, maxDepth, k);
1078
+ if (json === null) throw new Error(`shortestPaths failed: ${native.lastError()}`);
1079
+ return JSON.parse(json) as PathHit[];
1080
+ }
1081
+
1082
+ async createFtsIndex(field: string): Promise<void> {
1083
+ ensureOk(this.client.nativeBindings().createFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createFtsIndex');
1084
+ }
1085
+
1086
+ async createCompositeIndex(fields: { field: string; desc?: boolean }[]): Promise<number> {
1087
+ return this.client.createCompositeIndex(this.name, fields);
1088
+ }
1089
+
1090
+ /** Drop indexes (v0.19.6 parity). Composite drops by the id createCompositeIndex returned. */
1091
+ async dropIndex(field: string): Promise<void> {
1092
+ ensureOk(this.client.nativeBindings().dropSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropIndex');
1093
+ }
1094
+
1095
+ async dropVectorIndex(field: string): Promise<void> {
1096
+ ensureOk(this.client.nativeBindings().dropVectorIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropVectorIndex');
1097
+ }
1098
+
1099
+ async dropCompositeIndex(id: number): Promise<void> {
1100
+ ensureOk(this.client.nativeBindings().dropCompositeIndex(this.client.engineHandle(), this.name, id), this.client.nativeBindings(), 'dropCompositeIndex');
1101
+ }
1102
+
1103
+ async dropEdgeIndex(): Promise<void> {
1104
+ ensureOk(this.client.nativeBindings().dropEdgeIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'dropEdgeIndex');
1105
+ }
1106
+
1107
+ async dropFtsIndex(field: string): Promise<void> {
1108
+ ensureOk(this.client.nativeBindings().dropFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'dropFtsIndex');
1109
+ }
1110
+
1111
+ async dropTraverseIndex(): Promise<void> {
1112
+ ensureOk(this.client.nativeBindings().dropTraverseIndex(this.client.engineHandle(), this.name), this.client.nativeBindings(), 'dropTraverseIndex');
1113
+ }
1114
+
1115
+ /** HNSW-tuned vector index (m = edges per node, efConstruction = build beam, efSearch = query beam; 0 = engine default). */
1116
+ async createVectorIndexV2(field: string, dim: number, metric: VectorMetric = 'cosine', m = 0, efConstruction = 0, efSearch = 0): Promise<void> {
1117
+ ensureOk(this.client.nativeBindings().createVectorIndexV2(this.client.engineHandle(), this.name, field, dim, metric === 'l2' ? 1 : 0, m, efConstruction, efSearch), this.client.nativeBindings(), 'createVectorIndexV2');
1118
+ }
1119
+
1120
+ /** Graph BFS with the v0.19 extensions: via-edge hops, node/edge predicates, opt-in path/via projections. */
1121
+ async findPathsFull(id: string, opts: PathOptions = {}): Promise<PathHit[]> {
1122
+ const native = this.client.nativeBindings();
1123
+ const o = resolvePathOptions(opts);
1124
+ const json = native.findPathsFull(this.client.engineHandle(), this.name, id, o.direction, o.edge, o.via, o.maxDepth, o.k, o.includePath, o.includeVia, o.nodeField, o.nodeJSON, o.typeField, o.typeJSON, o.matchField, o.matchJSON);
1125
+ if (json === null) throw new Error(`findPathsFull failed: ${native.lastError()}`);
1126
+ return JSON.parse(json) as PathHit[];
1127
+ }
1128
+
1129
+ /** Weighted shortest paths with the same extensions as findPathsFull. */
1130
+ async shortestPathsFull(id: string, via: string | null, opts: PathOptions = {}): Promise<PathHit[]> {
1131
+ const native = this.client.nativeBindings();
1132
+ const o = resolvePathOptions(opts);
1133
+ const json = native.simplePathsFull(this.client.engineHandle(), this.name, id, o.direction, o.edge, via, o.weight ?? null, o.maxDepth, o.k, o.includePath, o.includeVia, o.nodeField, o.nodeJSON, o.typeField, o.typeJSON, o.matchField, o.matchJSON);
1134
+ if (json === null) throw new Error(`shortestPathsFull failed: ${native.lastError()}`);
1135
+ return JSON.parse(json) as PathHit[];
1136
+ }
1137
+
1138
+ /** Serialize the collection's ref graph (nodes + edges) as JSON. */
1139
+ async exportGraph(opts: PathOptions = {}): Promise<unknown> {
1140
+ const native = this.client.nativeBindings();
1141
+ const o = resolvePathOptions(opts);
1142
+ const json = native.exportGraph(this.client.engineHandle(), this.name, o.direction, o.edge, o.via, o.nodeField, o.nodeJSON);
1143
+ if (json === null) throw new Error(`exportGraph failed: ${native.lastError()}`);
1144
+ return JSON.parse(json);
1145
+ }
1146
+
1147
+ /** Whole-graph analysis: "components" | "cycle" | "topo". */
1148
+ async graphAnalysis(op: 'components' | 'cycle' | 'topo', opts: PathOptions = {}): Promise<unknown> {
1149
+ const native = this.client.nativeBindings();
1150
+ const o = resolvePathOptions(opts);
1151
+ const json = native.graphAnalysis(this.client.engineHandle(), this.name, op, o.direction, o.edge, o.via, o.nodeField, o.nodeJSON);
1152
+ if (json === null) throw new Error(`graphAnalysis failed: ${native.lastError()}`);
1153
+ return JSON.parse(json);
1154
+ }
1155
+ }
1156
+
1157
+ export class DocumentReference {
1158
+ constructor(private readonly client: HakoClient, readonly _collection: string, readonly _id: string) { }
1159
+
1160
+ async set(data: HakoDocData): Promise<void> {
1161
+ await this.client.set(this._collection, this._id, data);
1162
+ }
1163
+
1164
+ async update(data: HakoDocData): Promise<void> {
1165
+ await this.client.patch(this._collection, this._id, data);
1166
+ }
1167
+
1168
+ async get(): Promise<DocumentSnapshot> {
1169
+ return this.client.get(this._collection, this._id);
1170
+ }
1171
+
1172
+ async delete(): Promise<void> {
1173
+ await this.client.delete(this._collection, this._id);
1174
+ }
1175
+
1176
+ async getByReference(fieldKey: string): Promise<DocumentSnapshot | null> {
1177
+ const snap = await this.get();
1178
+ if (!snap.exists) return null;
1179
+ return this.client.getByReference(snap, fieldKey);
1180
+ }
1181
+ }
1182
+
1183
+ export class Query {
1184
+ private _startAfterSnapshot?: DocumentSnapshot;
1185
+ private _startAtSnapshot?: DocumentSnapshot;
1186
+ private _endAtSnapshot?: DocumentSnapshot;
1187
+ private _endBeforeSnapshot?: DocumentSnapshot;
1188
+ private _startAfterRawAnchor?: { snap: RawQuerySnapshot; index: number };
1189
+ private readonly filters: QueryConstraint[] = [];
1190
+ private readonly orFilters: QueryConstraint[] = [];
1191
+ private order?: QueryOrder;
1192
+ private queryLimit?: number;
1193
+ private queryOffset?: number;
1194
+ private projection: string[] = [];
1195
+ private deferBlobsDef = false;
1196
+ private near?: { field: string; vec: Float32Array };
1197
+ private traverse?: { startCol: string; startId: string; direction: number; edge: string | null; maxDepth: number };
1198
+
1199
+ constructor(private readonly client: HakoClient, private readonly collection: string) { }
1200
+
1201
+ where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
1202
+ this.filters.push({ field, op, value });
1203
+ return this;
1204
+ }
1205
+
1206
+ orWhere(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith', value: any): Query {
1207
+ this.orFilters.push({ field, op, value });
1208
+ return this;
1209
+ }
1210
+
1211
+ startAfter(snapshot: DocumentSnapshot): Query {
1212
+ this._startAfterSnapshot = snapshot;
1213
+ return this;
1214
+ }
1215
+
1216
+ /** Keyset anchor from a raw row — no decode. Prefer one anchor kind. */
1217
+ startAfterRaw(snap: RawQuerySnapshot, index: number): Query {
1218
+ this._startAfterRawAnchor = { snap, index };
1219
+ return this;
1220
+ }
1221
+
1222
+ startAt(snapshot: DocumentSnapshot): Query {
1223
+ this._startAtSnapshot = snapshot;
1224
+ return this;
1225
+ }
1226
+
1227
+ endAt(snapshot: DocumentSnapshot): Query {
1228
+ this._endAtSnapshot = snapshot;
1229
+ return this;
1230
+ }
1231
+
1232
+ endBefore(snapshot: DocumentSnapshot): Query {
1233
+ this._endBeforeSnapshot = snapshot;
1234
+ return this;
1235
+ }
1236
+
1237
+ orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
1238
+ this.order = { field, ascending: direction === 'asc' };
1239
+ return this;
1240
+ }
1241
+
1242
+ limit(max: number): Query {
1243
+ this.queryLimit = max;
1244
+ return this;
1245
+ }
1246
+
1247
+ offset(skip: number): Query {
1248
+ this.queryOffset = skip;
1249
+ return this;
1250
+ }
1251
+
1252
+ select(...fields: string[]): Query {
1253
+ this.projection = fields;
1254
+ return this;
1255
+ }
1256
+
1257
+ deferBlobs(defer = true): Query {
1258
+ this.deferBlobsDef = defer;
1259
+ return this;
1260
+ }
1261
+
1262
+ /** Array-of-objects predicate: every element must match all filters (F3). */
1263
+ whereElemMatch(field: string, filters: ElemFilter[]): Query {
1264
+ this.filters.push({ field, op: 'elemMatch', value: filters });
1265
+ return this;
1266
+ }
1267
+
1268
+ /** Array predicate: every element equals value (scalar JSON) (F3). */
1269
+ whereArrayAllEq(field: string, value: unknown): Query {
1270
+ this.filters.push({ field, op: 'arrayAllEq', value });
1271
+ return this;
1272
+ }
1273
+
1274
+ /** KNN marker; the result cap rides limit() (F3). */
1275
+ whereNear(field: string, vec: number[] | Float32Array): Query {
1276
+ this.near = { field, vec: vec instanceof Float32Array ? vec : Float32Array.from(vec) };
1277
+ return this;
1278
+ }
1279
+
1280
+ /** BFS graph marker; edge null = any reference field (F3). */
1281
+ whereTraverse(
1282
+ startCol: string,
1283
+ startId: string,
1284
+ direction: TraverseDirection = 'outgoing',
1285
+ edge: string | null = null,
1286
+ maxDepth = 3
1287
+ ): Query {
1288
+ const dir = direction === 'incoming' ? 1 : direction === 'both' ? 2 : 0;
1289
+ this.traverse = { startCol, startId, direction: dir, edge, maxDepth };
1290
+ return this;
1291
+ }
1292
+
1293
+ private prepareNativeQuery(): unknown {
1294
+ const native = this.client.nativeBindings();
1295
+ const handle = native.queryNew(this.collection);
1296
+ if (!handle) throw new Error(`queryNew failed: ${native.lastError()}`);
1297
+
1298
+ try {
1299
+ for (const filter of this.filters) {
1300
+ switch (filter.op) {
1301
+ case '==':
1302
+ if (typeof filter.value === 'string') {
1303
+ ensureOk(native.queryWhereEqStr(handle, filter.field, filter.value), native, 'queryWhereEqStr');
1304
+ } else if (typeof filter.value === 'boolean') {
1305
+ ensureOk(native.queryWhereEqBool(handle, filter.field, filter.value), native, 'queryWhereEqBool');
1306
+ } else {
1307
+ ensureOk(native.queryWhereEqInt(handle, filter.field, filter.value), native, 'queryWhereEqInt');
1308
+ }
1309
+ break;
1310
+ case '!=':
1311
+ case '>':
1312
+ case '>=':
1313
+ case '<':
1314
+ case '<=':
1315
+ if (typeof filter.value === 'string') {
1316
+ if (filter.op === '!=') ensureOk(native.queryWhereNeStr(handle, filter.field, filter.value), native, 'queryWhereNeStr');
1317
+ else if (filter.op === '>') ensureOk(native.queryWhereGtStr(handle, filter.field, filter.value), native, 'queryWhereGtStr');
1318
+ else if (filter.op === '>=') ensureOk(native.queryWhereGteStr(handle, filter.field, filter.value), native, 'queryWhereGteStr');
1319
+ else if (filter.op === '<') ensureOk(native.queryWhereLtStr(handle, filter.field, filter.value), native, 'queryWhereLtStr');
1320
+ else ensureOk(native.queryWhereLteStr(handle, filter.field, filter.value), native, 'queryWhereLteStr');
1321
+ } else {
1322
+ if (filter.op === '!=') ensureOk(native.queryWhereNeInt(handle, filter.field, filter.value), native, 'queryWhereNeInt');
1323
+ else if (filter.op === '>') ensureOk(native.queryWhereGtInt(handle, filter.field, filter.value), native, 'queryWhereGtInt');
1324
+ else if (filter.op === '>=') ensureOk(native.queryWhereGteInt(handle, filter.field, filter.value), native, 'queryWhereGteInt');
1325
+ else if (filter.op === '<') ensureOk(native.queryWhereLtInt(handle, filter.field, filter.value), native, 'queryWhereLtInt');
1326
+ else ensureOk(native.queryWhereLteInt(handle, filter.field, filter.value), native, 'queryWhereLteInt');
1327
+ }
1328
+ break;
1329
+ case 'match':
1330
+ ensureOk(native.queryWhereMatch(handle, filter.field, String(filter.value)), native, 'queryWhereMatch');
1331
+ break;
1332
+ case 'matchPrefix':
1333
+ ensureOk(native.queryWhereMatchPrefix(handle, filter.field, String(filter.value)), native, 'queryWhereMatchPrefix');
1334
+ break;
1335
+ case 'contains':
1336
+ ensureOk(native.queryWhereContains(handle, filter.field, String(filter.value)), native, 'queryWhereContains');
1337
+ break;
1338
+ case 'startsWith':
1339
+ ensureOk(native.queryWhereStartsWith(handle, filter.field, String(filter.value)), native, 'queryWhereStartsWith');
1340
+ break;
1341
+ case 'in':
1342
+ case 'not-in':
1343
+ case 'array-contains-any':
1344
+ const arr = native.arrayNew();
1345
+ (filter.value as any[]).forEach(v => {
1346
+ if (typeof v === 'string') native.arrayAppendStr(arr, v);
1347
+ else native.arrayAppendInt(arr, v);
1348
+ });
1349
+ if (filter.op === 'in') ensureOk(native.queryWhereIn(handle, filter.field, arr), native, 'queryWhereIn');
1350
+ else if (filter.op === 'not-in') ensureOk(native.queryWhereNotIn(handle, filter.field, arr), native, 'queryWhereNotIn');
1351
+ else ensureOk(native.queryWhereArrayContainsAny(handle, filter.field, arr), native, 'queryWhereArrayContainsAny');
1352
+ break;
1353
+ case 'array-contains':
1354
+ if (typeof filter.value === 'string') ensureOk(native.queryWhereArrayContainsStr(handle, filter.field, filter.value), native, 'queryWhereArrayContainsStr');
1355
+ else ensureOk(native.queryWhereArrayContainsInt(handle, filter.field, filter.value), native, 'queryWhereArrayContainsInt');
1356
+ break;
1357
+ case 'elemMatch':
1358
+ ensureOk(native.queryWhereElemMatch(handle, filter.field, JSON.stringify(filter.value)), native, 'queryWhereElemMatch');
1359
+ break;
1360
+ case 'arrayAllEq':
1361
+ ensureOk(native.queryWhereArrayAllEq(handle, filter.field, JSON.stringify(filter.value)), native, 'queryWhereArrayAllEq');
1362
+ break;
1363
+ }
1364
+ }
1365
+
1366
+ for (const filter of this.orFilters) {
1367
+ if (typeof filter.value === 'string') {
1368
+ ensureOk(native.queryWhereOrStr(handle, filter.field, filter.value), native, 'queryWhereOrStr');
1369
+ } else {
1370
+ ensureOk(native.queryWhereOrInt(handle, filter.field, filter.value), native, 'queryWhereOrInt');
1371
+ }
1372
+ }
1373
+
1374
+ if (this._startAtSnapshot?._nativeHandle) {
1375
+ ensureOk(native.queryStartAt(handle, this._startAtSnapshot._nativeHandle), native, 'queryStartAt');
1376
+ }
1377
+ if (this._startAfterSnapshot?._nativeHandle) {
1378
+ ensureOk(native.queryStartAfter(handle, this._startAfterSnapshot._nativeHandle), native, 'queryStartAfter');
1379
+ }
1380
+ if (this._startAfterRawAnchor) {
1381
+ ensureOk(native.queryStartAfterRaw(handle, this._startAfterRawAnchor.snap.rawHandleAt(this._startAfterRawAnchor.index)), native, 'queryStartAfterRaw');
1382
+ }
1383
+ if (this._endAtSnapshot?._nativeHandle) {
1384
+ ensureOk(native.queryEndAt(handle, this._endAtSnapshot._nativeHandle), native, 'queryEndAt');
1385
+ }
1386
+ if (this._endBeforeSnapshot?._nativeHandle) {
1387
+ ensureOk(native.queryEndBefore(handle, this._endBeforeSnapshot._nativeHandle), native, 'queryEndBefore');
1388
+ }
1389
+
1390
+ if (this.near) ensureOk(native.queryWhereNear(handle, this.near.field, this.near.vec), native, 'queryWhereNear');
1391
+ if (this.traverse) {
1392
+ const t = this.traverse;
1393
+ ensureOk(native.queryWhereTraverse(handle, t.startCol, t.startId, t.direction, t.edge, t.maxDepth), native, 'queryWhereTraverse');
1394
+ }
1395
+
1396
+ if (this.order) ensureOk(native.queryOrderBy(handle, this.order.field, this.order.ascending), native, 'queryOrderBy');
1397
+ if (this.queryLimit !== undefined) ensureOk(native.queryLimit(handle, this.queryLimit), native, 'queryLimit');
1398
+ if (this.queryOffset !== undefined) ensureOk(native.queryOffset(handle, this.queryOffset), native, 'queryOffset');
1399
+ for (const field of this.projection) ensureOk(native.querySelectField(handle, field), native, 'querySelectField');
1400
+ if (this.deferBlobsDef) ensureOk(native.queryDeferBlobs(handle, true), native, 'queryDeferBlobs');
1401
+
1402
+ return handle;
1403
+ } catch (err) {
1404
+ native.queryFree(handle);
1405
+ throw err;
1406
+ }
1407
+ }
1408
+
1409
+ async get(): Promise<HakoDocData[]> {
1410
+ const native = this.client.nativeBindings();
1411
+ const handle = this.prepareNativeQuery();
1412
+ try {
1413
+ return parseQueryRows(native.queryExecute(this.client.engineHandle(), handle));
1414
+ } finally {
1415
+ native.queryFree(handle);
1416
+ }
1417
+ }
1418
+
1419
+ /**
1420
+ * P2 fast path (core 0.18+): rows serialized from pinned bytes, same
1421
+ * shape as get(). Projections keep the projected executor's shape.
1422
+ */
1423
+ async getJson(): Promise<HakoDocData[]> {
1424
+ const native = this.client.nativeBindings();
1425
+ const handle = this.prepareNativeQuery();
1426
+ try {
1427
+ return parseQueryRows(native.queryExecuteJson(this.client.engineHandle(), handle));
1428
+ } finally {
1429
+ native.queryFree(handle);
1430
+ }
1431
+ }
1432
+
1433
+ /** Query plan JSON without executing the scan (F7). */
1434
+ async explain(): Promise<Record<string, unknown> | null> {
1435
+ const native = this.client.nativeBindings();
1436
+ const handle = this.prepareNativeQuery();
1437
+ try {
1438
+ const json = native.queryExplain(this.client.engineHandle(), handle);
1439
+ return json ? (JSON.parse(json) as Record<string, unknown>) : null;
1440
+ } finally {
1441
+ native.queryFree(handle);
1442
+ }
1443
+ }
1444
+
1445
+ /**
1446
+ * Raw page: no decode, no JSON. Walk it with count/resolve, page with
1447
+ * startAfterRaw, free when done. Scan-many/touch-few is the shape this
1448
+ * pays for; resolving every row costs the same as get().
1449
+ */
1450
+ async getRaw(): Promise<RawQuerySnapshot> {
1451
+ const native = this.client.nativeBindings();
1452
+ const handle = this.prepareNativeQuery();
1453
+ try {
1454
+ const rs = native.queryExecuteRaw(this.client.engineHandle(), handle);
1455
+ if (!rs) throw new Error(`queryExecuteRaw failed: ${native.lastError()}`);
1456
+ return new RawQuerySnapshot(this.client, this.collection, rs);
1457
+ } finally {
1458
+ native.queryFree(handle);
1459
+ }
1460
+ }
1461
+
1462
+ async delete(): Promise<number> {
1463
+ const native = this.client.nativeBindings();
1464
+ const handle = this.prepareNativeQuery();
1465
+ try {
1466
+ const n = native.queryDelete(this.client.engineHandle(), handle);
1467
+ if (n < 0) throw new Error(`queryDelete failed: ${native.lastError()}`);
1468
+ return n;
1469
+ } finally {
1470
+ native.queryFree(handle);
1471
+ }
1472
+ }
1473
+
1474
+ /** Local-only mass delete: matched docs never leave this device. */
1475
+ async deleteLocal(): Promise<number> {
1476
+ const native = this.client.nativeBindings();
1477
+ const handle = this.prepareNativeQuery();
1478
+ try {
1479
+ const n = native.queryDeleteLocal(this.client.engineHandle(), handle);
1480
+ if (n < 0) throw new Error(`queryDeleteLocal failed: ${native.lastError()}`);
1481
+ return n;
1482
+ } finally {
1483
+ native.queryFree(handle);
1484
+ }
1485
+ }
1486
+
1487
+ async patch(data: HakoDocData): Promise<number> {
1488
+ const native = this.client.nativeBindings();
1489
+ const handle = this.prepareNativeQuery();
1490
+ const patchDoc = toNativeDoc(native, data);
1491
+ try {
1492
+ const n = native.queryPatch(this.client.engineHandle(), handle, patchDoc);
1493
+ if (n < 0) throw new Error(`queryPatch failed: ${native.lastError()}`);
1494
+ return n;
1495
+ } finally {
1496
+ native.docFree(patchDoc);
1497
+ native.queryFree(handle);
1498
+ }
1499
+ }
1500
+
1501
+ async count(): Promise<number> {
1502
+ const native = this.client.nativeBindings();
1503
+ const handle = this.prepareNativeQuery();
1504
+ try {
1505
+ ensureOk(native.queryAggregateCount(handle), native, 'queryAggregateCount');
1506
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1507
+ return json ? (JSON.parse(json).count || 0) : 0;
1508
+ } finally {
1509
+ native.queryFree(handle);
1510
+ }
1511
+ }
1512
+
1513
+ async sum(field: string): Promise<number> {
1514
+ const native = this.client.nativeBindings();
1515
+ const handle = this.prepareNativeQuery();
1516
+ try {
1517
+ ensureOk(native.queryAggregateSum(handle, field), native, 'queryAggregateSum');
1518
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1519
+ return json ? (JSON.parse(json)[`sum_${field}`] || 0) : 0;
1520
+ } finally {
1521
+ native.queryFree(handle);
1522
+ }
1523
+ }
1524
+
1525
+ async avg(field: string): Promise<number> {
1526
+ const native = this.client.nativeBindings();
1527
+ const handle = this.prepareNativeQuery();
1528
+ try {
1529
+ ensureOk(native.queryAggregateAvg(handle, field), native, 'queryAggregateAvg');
1530
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1531
+ return json ? (JSON.parse(json)[`avg_${field}`] || 0) : 0;
1532
+ } finally {
1533
+ native.queryFree(handle);
1534
+ }
1535
+ }
1536
+
1537
+ /** `null` when no matching document has a numeric `field`. */
1538
+ async min(field: string): Promise<number | null> {
1539
+ const native = this.client.nativeBindings();
1540
+ const handle = this.prepareNativeQuery();
1541
+ try {
1542
+ ensureOk(native.queryAggregateMin(handle, field), native, 'queryAggregateMin');
1543
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1544
+ return json ? (JSON.parse(json)[`min_${field}`] ?? null) : null;
1545
+ } finally {
1546
+ native.queryFree(handle);
1547
+ }
1548
+ }
1549
+
1550
+ /** `null` when no matching document has a numeric `field`. */
1551
+ async max(field: string): Promise<number | null> {
1552
+ const native = this.client.nativeBindings();
1553
+ const handle = this.prepareNativeQuery();
1554
+ try {
1555
+ ensureOk(native.queryAggregateMax(handle, field), native, 'queryAggregateMax');
1556
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1557
+ return json ? (JSON.parse(json)[`max_${field}`] ?? null) : null;
1558
+ } finally {
1559
+ native.queryFree(handle);
1560
+ }
1561
+ }
1562
+
1563
+ onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
1564
+ const native = this.client.nativeBindings();
1565
+ const internalWatcher: WatchCallback = async () => {
1566
+ const data = await this.get();
1567
+ callback(data);
1568
+ };
1569
+ const watchHandle = native.engineWatch(this.client.engineHandle(), this.collection, internalWatcher);
1570
+ this.get().then(callback);
1571
+ return async () => { native.watchFree(watchHandle); };
1572
+ }
1573
+ }
1574
+
1575
+ export class WriteBatch {
1576
+ private readonly native: NativeBindings;
1577
+ private readonly handle: unknown;
1578
+ private committed = false;
1579
+
1580
+ constructor(private readonly client: HakoClient) {
1581
+ this.native = client.nativeBindings();
1582
+ this.handle = this.native.batchNew();
1583
+ if (!this.handle) throw new Error(`batchNew failed: ${this.native.lastError()}`);
1584
+ }
1585
+
1586
+ set(docRef: DocumentReference, data: HakoDocData): WriteBatch {
1587
+ this.ensureActive();
1588
+ const doc = toNativeDoc(this.native, data);
1589
+ try {
1590
+ ensureOk(this.native.batchSet(this.handle, docRef._collection, docRef._id, doc), this.native, 'batchSet');
1591
+ return this;
1592
+ } finally {
1593
+ this.native.docFree(doc);
1594
+ }
1595
+ }
1596
+
1597
+ delete(docRef: DocumentReference): WriteBatch {
1598
+ this.ensureActive();
1599
+ ensureOk(this.native.batchDelete(this.handle, docRef._collection, docRef._id), this.native, 'batchDelete');
1600
+ return this;
1601
+ }
1602
+
1603
+ /** Batch delete with an explicit mode: 0/soft = restoreable, force = legacy
1604
+ * tombstone-only. batchDelete() keeps legacy/force for frozen contracts. */
1605
+ deleteEx(docRef: DocumentReference, force: boolean): WriteBatch {
1606
+ this.ensureActive();
1607
+ ensureOk(this.native.batchDeleteEx(this.handle, docRef._collection, docRef._id, force), this.native, 'batchDeleteEx');
1608
+ return this;
1609
+ }
1610
+
1611
+ async commit(): Promise<void> {
1612
+ this.ensureActive();
1613
+ ensureOk(this.native.batchCommit(this.client.engineHandle(), this.handle), this.native, 'batchCommit');
1614
+ this.native.batchFree(this.handle);
1615
+ this.committed = true;
1616
+ }
1617
+
1618
+ dispose(): void {
1619
+ if (this.committed) return;
1620
+ this.native.batchFree(this.handle);
1621
+ this.committed = true;
1622
+ }
1623
+
1624
+ private ensureActive(): void {
1625
+ if (this.committed) throw new Error('WriteBatch is already committed/disposed');
1626
+ }
1627
+ }