@hakodb/client 0.5.14 → 0.5.16

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.
@@ -0,0 +1,31 @@
1
+ # Quick gate for branch protection (required check on main).
2
+ # Typecheck only (no build step in these packages).
3
+
4
+ name: ci-quick
5
+
6
+ on:
7
+ pull_request:
8
+ branches: [main]
9
+ push:
10
+ branches: [main]
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ check:
17
+ name: quick-check
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - uses: actions/setup-node@v4
23
+ with:
24
+ node-version: 22
25
+ cache: npm
26
+
27
+ - name: install
28
+ run: npm ci
29
+
30
+ - name: typecheck
31
+ run: npx tsc --noEmit -p tsconfig.json
package/README.md CHANGED
@@ -1,27 +1,29 @@
1
- # hakojs
2
-
3
- > Part of [**HakoDB**](https://github.com/hakodb/hakodb) — embedded Firestore-style document DB in Rust. The engine + C ABI live in `hakodb/hakodb`; this repo holds the JavaScript/TypeScript SDK.
4
-
5
- JavaScript/TypeScript SDK for HakoDB:
6
- high-level client (`client.ts`: `HakoClient`, `HakoConfig`) and native
7
- FFI bindings over koffi/Bun (`native.ts`). Tauri lives in `@hakodb/tauri`
8
- (sibling repo [`hakodb/hakotaurits`](https://github.com/hakodb/hakotaurits)).
9
-
10
- ## Compatibility
11
-
12
- | hakojs | hako core |
13
- |---|---|
14
- | 0.5.13 | `cloud_sync` branch / `v0.8.21`+ release asset |
15
-
16
- ## Setup — native library
17
-
18
- `native.ts` loads the HakoDB cdylib. Resolution order:
19
- `loadNativeBindings(explicitPath)` → `HAKODB_LIB_PATH` env →
20
- `./native/<lib>`. Populate it with the sync script:
21
-
22
- ```powershell
23
- .\sync-native.ps1 -CoreDir C:\Dev\libs\firelite
24
- .\sync-native.ps1 -Tag v0.8.21
25
- ```
26
-
27
- Binaries under `native/` are git-ignored.
1
+ # hakojs
2
+
3
+ > Part of [**HakoDB**](https://github.com/hakodb/hakodb) — embedded Firestore-style document DB in Rust. The engine + C ABI live in `hakodb/hakodb`; this repo holds the JavaScript/TypeScript SDK.
4
+
5
+ JavaScript/TypeScript SDK for HakoDB:
6
+ high-level client (`client.ts`: `HakoClient`, `HakoConfig`) and native
7
+ FFI bindings over koffi/Bun (`native.ts`). Tauri lives in `@hakodb/tauri`
8
+ (sibling repo [`hakodb/hakotaurits`](https://github.com/hakodb/hakotaurits)).
9
+
10
+ ## Compatibility
11
+
12
+ | hakojs | hako core |
13
+ |---|---|
14
+ | 0.5.13 | `cloud_sync` branch / `v0.8.21`+ release asset |
15
+ | 0.5.15 | `hakodb v0.12.3` (archive: `relocateDocs`/`load`/`unload`/`unloadedCollections`) |
16
+ | 0.5.16 | `hakodb v0.13.3` (`createVectorIndex` + `findNear` KNN over `hk_engine_find_near`) |
17
+
18
+ ## Setup — native library
19
+
20
+ `native.ts` loads the HakoDB cdylib. Resolution order:
21
+ `loadNativeBindings(explicitPath)` → `HAKODB_LIB_PATH` env →
22
+ `./native/<lib>`. Populate it with the sync script:
23
+
24
+ ```powershell
25
+ .\sync-native.ps1 -CoreDir C:\Dev\libs\firelite
26
+ .\sync-native.ps1 -Tag v0.8.21
27
+ ```
28
+
29
+ Binaries under `native/` are git-ignored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hakodb/client",
3
- "version": "0.5.14",
3
+ "version": "0.5.16",
4
4
  "description": "High-level HakoDB JavaScript/TypeScript client for Node.js and Bun",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/client.ts CHANGED
@@ -16,6 +16,16 @@ export type Primitive =
16
16
 
17
17
  export type HakoDocData = { [key: string]: Primitive };
18
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
+
19
29
  const SERVER_TIMESTAMP_SENTINEL = "__FL_SERVER_TIMESTAMP__";
20
30
 
21
31
  export class HakoReference {
@@ -600,6 +610,33 @@ export class HakoClient {
600
610
  return n;
601
611
  }
602
612
 
613
+ /** Relocate docs by id src -> dst. Returns {moved, missing}; refusals throw. */
614
+ async relocateDocs(src: string, dst: string, ids: string[]): Promise<{ moved: string[]; missing: string[] }> {
615
+ this.assertOpen();
616
+ const json = this.native.engineRelocateDocs(this.engine, src, dst, JSON.stringify(ids));
617
+ if (!json) throw new Error(`engineRelocateDocs failed: ${this.native.lastError()}`);
618
+ return JSON.parse(json);
619
+ }
620
+
621
+ /** Load a lazy collection's snapshot into the index now. */
622
+ async loadCollection(collection: string): Promise<void> {
623
+ this.assertOpen();
624
+ ensureOk(this.native.engineLoadCollection(this.engine, collection), this.native, 'engineLoadCollection');
625
+ }
626
+
627
+ /** Unload a lazy collection (frees RAM; snapshot stays). Refuses non-lazy. */
628
+ async unloadCollection(collection: string): Promise<void> {
629
+ this.assertOpen();
630
+ ensureOk(this.native.engineUnloadCollection(this.engine, collection), this.native, 'engineUnloadCollection');
631
+ }
632
+
633
+ /** Lazy collections currently out of the index. */
634
+ async unloadedCollections(): Promise<string[]> {
635
+ this.assertOpen();
636
+ const json = this.native.engineUnloadedCollections(this.engine);
637
+ return json ? JSON.parse(json) : [];
638
+ }
639
+
603
640
  nativeBindings(): NativeBindings { return this.native; }
604
641
  engineHandle(): unknown { return this.engine; }
605
642
 
@@ -746,6 +783,19 @@ export class CollectionReference {
746
783
  ensureOk(this.client.nativeBindings().createSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createIndex');
747
784
  }
748
785
 
786
+ async createVectorIndex(field: string, dim: number, metric: VectorMetric = 'cosine'): Promise<void> {
787
+ ensureOk(this.client.nativeBindings().createVectorIndex(this.client.engineHandle(), this.name, field, dim, metric === 'l2' ? 1 : 0), this.client.nativeBindings(), 'createVectorIndex');
788
+ }
789
+
790
+ /** KNN search: nearest-first [{id, score, doc}]. Embeddings are stored as binary LE-f32 (insert a Uint8Array of Float32 bytes). */
791
+ async findNear(field: string, query: number[] | Float32Array, k = 10): Promise<NearHit[]> {
792
+ const native = this.client.nativeBindings();
793
+ const vec = query instanceof Float32Array ? query : Float32Array.from(query);
794
+ const json = native.engineFindNear(this.client.engineHandle(), this.name, field, vec, k);
795
+ if (json === null) throw new Error(`findNear failed: ${native.lastError()}`);
796
+ return JSON.parse(json) as NearHit[];
797
+ }
798
+
749
799
  async createFtsIndex(field: string): Promise<void> {
750
800
  ensureOk(this.client.nativeBindings().createFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createFtsIndex');
751
801
  }
package/src/native.ts CHANGED
@@ -65,6 +65,10 @@ export interface NativeBindings {
65
65
  engineReplicateKey(engine: Handle, collection: string, docId: string): number;
66
66
  engineReplicateCollection(engine: Handle, collection: string): number;
67
67
  engineVacuumCollection(engine: Handle, collection: string): number;
68
+ engineRelocateDocs(engine: Handle, src: string, dst: string, idsJson: string): string | null;
69
+ engineLoadCollection(engine: Handle, collection: string): number;
70
+ engineUnloadCollection(engine: Handle, collection: string): number;
71
+ engineUnloadedCollections(engine: Handle): string | null;
68
72
  enginePatch(engine: Handle, collection: string, docId: string, updates: Handle): number;
69
73
  engineInsertSubDoc(engine: Handle, col: string, id: string, subCol: string, subId: string, doc: Handle): number;
70
74
  engineGetByRef(engine: Handle, doc: Handle, fieldKey: string): Handle;
@@ -174,6 +178,12 @@ export interface NativeBindings {
174
178
  // v0.5.9
175
179
  createFtsIndex(engine: Handle, collection: string, field: string): number;
176
180
  createSimpleIndex(engine: Handle, collection: string, field: string): number;
181
+
182
+ // Vector KNN (core >=0.13.3): one-shot search returns owned JSON
183
+ // [{id, score, doc}] (null = hard error, e.g. dim mismatch — read
184
+ // lastError); unindexed field returns "[]".
185
+ createVectorIndex(engine: Handle, collection: string, field: string, dim: number, metric: number): number;
186
+ engineFindNear(engine: Handle, collection: string, field: string, vec: Float32Array, k: number): string | null;
177
187
 
178
188
  // Array API
179
189
  arrayNew(): Handle;
@@ -271,10 +281,16 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
271
281
  hk_engine_replicate_key: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
272
282
  hk_engine_replicate_collection: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
273
283
  hk_engine_vacuum_collection: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
284
+ hk_engine_relocate_docs: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.cstring], returns: FFIType.ptr },
285
+ hk_engine_load_collection: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
286
+ hk_engine_unload_collection: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
287
+ hk_engine_unloaded_collections: { args: [FFIType.ptr], returns: FFIType.ptr },
274
288
  hk_engine_patch: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
275
289
  hk_engine_insert_subdoc: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.cstring, FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
276
290
  hk_engine_get_by_ref: { args: [FFIType.ptr, FFIType.ptr, FFIType.cstring], returns: FFIType.ptr },
277
291
  hk_engine_create_index: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.u32 },
292
+ hk_engine_create_vector_index: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.u32, FFIType.u32], returns: FFIType.i32 },
293
+ hk_engine_find_near: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.ptr, FFIType.usize, FFIType.usize], returns: FFIType.ptr },
278
294
 
279
295
  hk_batch_new: { args: [], returns: FFIType.ptr },
280
296
  hk_batch_free: { args: [FFIType.ptr], returns: FFIType.void },
@@ -452,6 +468,10 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
452
468
  engineReplicateKey: (engine, collection, docId) => symbols.hk_engine_replicate_key(engine, toC(collection), toC(docId)),
453
469
  engineReplicateCollection: (engine, collection) => symbols.hk_engine_replicate_collection(engine, toC(collection)),
454
470
  engineVacuumCollection: (engine, collection) => symbols.hk_engine_vacuum_collection(engine, toC(collection)),
471
+ engineRelocateDocs: (engine, src, dst, idsJson) => ptrToStringAndFree(symbols.hk_engine_relocate_docs(engine, toC(src), toC(dst), toC(idsJson))),
472
+ engineLoadCollection: (engine, collection) => symbols.hk_engine_load_collection(engine, toC(collection)),
473
+ engineUnloadCollection: (engine, collection) => symbols.hk_engine_unload_collection(engine, toC(collection)),
474
+ engineUnloadedCollections: (engine) => ptrToStringAndFree(symbols.hk_engine_unloaded_collections(engine)),
455
475
  enginePatch: (engine, collection, docId, updates) => symbols.hk_engine_patch(engine, toC(collection), toC(docId), updates),
456
476
  engineInsertSubDoc: (engine, col, id, subCol, subId, doc) => symbols.hk_engine_insert_subdoc(engine, toC(col), toC(id), toC(subCol), toC(subId), doc),
457
477
  engineGetByRef: (engine, doc, fieldKey) => symbols.hk_engine_get_by_ref(engine, doc, toC(fieldKey)),
@@ -555,6 +575,10 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
555
575
  // Indexing
556
576
  createFtsIndex: (engine, collection, field) => symbols.hk_engine_create_fts_index(engine, toC(collection), toC(field)),
557
577
  createSimpleIndex: (engine, collection, field) => symbols.hk_engine_create_simple_index(engine, toC(collection), toC(field)),
578
+ createVectorIndex: (engine, collection, field, dim, metric) => symbols.hk_engine_create_vector_index(engine, toC(collection), toC(field), dim, metric),
579
+ // Float32Array crosses as its LE-f32 bytes (bun:ffi takes the typed
580
+ // array as ptr, like docInsertBin takes bytes).
581
+ engineFindNear: (engine, collection, field, vec, k) => ptrToStringAndFree(symbols.hk_engine_find_near(engine, toC(collection), toC(field), vec, vec.length, k)),
558
582
 
559
583
  // Array API
560
584
  arrayNew: () => symbols.hk_array_new(),
@@ -661,10 +685,16 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
661
685
  hk_engine_replicate_key: lib.func('int hk_engine_replicate_key(HK_Engine* engine, const char* collection, const char* doc_id)'),
662
686
  hk_engine_replicate_collection: lib.func('int hk_engine_replicate_collection(HK_Engine* engine, const char* collection)'),
663
687
  hk_engine_vacuum_collection: lib.func('int hk_engine_vacuum_collection(HK_Engine* engine, const char* collection)'),
688
+ hk_engine_relocate_docs: lib.func('HeapStr hk_engine_relocate_docs(HK_Engine* engine, const char* src, const char* dst, const char* ids_json)'),
689
+ hk_engine_load_collection: lib.func('int hk_engine_load_collection(HK_Engine* engine, const char* collection)'),
690
+ hk_engine_unload_collection: lib.func('int hk_engine_unload_collection(HK_Engine* engine, const char* collection)'),
691
+ hk_engine_unloaded_collections: lib.func('HeapStr hk_engine_unloaded_collections(HK_Engine* engine)'),
664
692
  hk_engine_patch: lib.func('int hk_engine_patch(HK_Engine* engine, const char* collection, const char* doc_id, const HK_Doc* updates)'),
665
693
  hk_engine_insert_subdoc: lib.func('int hk_engine_insert_subdoc(HK_Engine* engine, const char* col, const char* id, const char* sub_col, const char* sub_id, const HK_Doc* doc)'),
666
694
  hk_engine_get_by_ref: lib.func('HK_Doc* hk_engine_get_by_ref(HK_Engine* engine, const HK_Doc* doc, const char* field_key)'),
667
695
  hk_engine_create_index: lib.func('uint32_t hk_engine_create_index(HK_Engine* engine, const char* collection, const char* fields_json)'),
696
+ hk_engine_create_vector_index: lib.func('int hk_engine_create_vector_index(HK_Engine* engine, const char* collection, const char* field, uint32_t dim, uint32_t metric)'),
697
+ hk_engine_find_near: lib.func('HeapStr hk_engine_find_near(HK_Engine* engine, const char* collection, const char* field, const float* vec, size_t len, size_t k)'),
668
698
 
669
699
  hk_batch_new: lib.func('HK_Batch* hk_batch_new()'),
670
700
  hk_batch_free: lib.func('void hk_batch_free(HK_Batch* batch)'),
@@ -845,6 +875,10 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
845
875
  engineReplicateKey: (engine, collection, docId) => fn.hk_engine_replicate_key(engine, collection, docId),
846
876
  engineReplicateCollection: (engine, collection) => fn.hk_engine_replicate_collection(engine, collection),
847
877
  engineVacuumCollection: (engine, collection) => fn.hk_engine_vacuum_collection(engine, collection),
878
+ engineRelocateDocs: (engine, src, dst, idsJson) => ptrToStringAndFree(fn.hk_engine_relocate_docs(engine, src, dst, idsJson)),
879
+ engineLoadCollection: (engine, collection) => fn.hk_engine_load_collection(engine, collection),
880
+ engineUnloadCollection: (engine, collection) => fn.hk_engine_unload_collection(engine, collection),
881
+ engineUnloadedCollections: (engine) => ptrToStringAndFree(fn.hk_engine_unloaded_collections(engine)),
848
882
  enginePatch: (engine, collection, docId, updates) => fn.hk_engine_patch(engine, collection, docId, updates),
849
883
  engineInsertSubDoc: (engine, col, id, subCol, subId, doc) => fn.hk_engine_insert_subdoc(engine, col, id, subCol, subId, doc),
850
884
  engineGetByRef: (engine, doc, fieldKey) => fn.hk_engine_get_by_ref(engine, doc, fieldKey),
@@ -948,6 +982,10 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
948
982
  // Indexing
949
983
  createFtsIndex: (engine, collection, field) => fn.hk_engine_create_fts_index(engine, collection, field),
950
984
  createSimpleIndex: (engine, collection, field) => fn.hk_engine_create_simple_index(engine, collection, field),
985
+ createVectorIndex: (engine, collection, field, dim, metric) => fn.hk_engine_create_vector_index(engine, collection, field, dim, metric),
986
+ // LE-f32 bytes via Buffer over the Float32Array (koffi takes Buffer
987
+ // for float*, same as docInsertBin takes Buffer for uint8_t*).
988
+ engineFindNear: (engine, collection, field, vec, k) => fn.hk_engine_find_near(engine, collection, field, Buffer.from(vec.buffer, vec.byteOffset, vec.byteLength), vec.length, k),
951
989
 
952
990
  // Array API
953
991
  arrayNew: () => fn.hk_array_new(),
package/sync-native.ps1 CHANGED
@@ -1,30 +1,55 @@
1
- #Requires -Version 5.1
2
- <#
3
- .SYNOPSIS
4
- Populate native/ from a core checkout or a release tag asset.
5
- .EXAMPLE
6
- .\sync-native.ps1 -CoreDir C:\Dev\libs\firelite
7
- .\sync-native.ps1 -Tag v0.8.20
8
- #>
9
- param(
10
- [string]$CoreDir = "",
11
- [string]$Tag = ""
12
- )
13
-
14
- $ErrorActionPreference = "Stop"
15
- $Root = Split-Path -Parent $MyInvocation.MyCommand.Path
16
- $Native = Join-Path $Root "native"
17
- New-Item -ItemType Directory -Force $Native | Out-Null
18
-
19
- if ($CoreDir -ne "") {
20
- $dll = Join-Path $CoreDir "target\release\hakodb.dll"
21
- if (-not (Test-Path $dll)) { throw "no release DLL at $dll (cargo build --release first)" }
22
- Copy-Item $dll $Native -Force
23
- Write-Output "synced from checkout: $CoreDir"
24
- } elseif ($Tag -ne "") {
25
- $base = "https://github.com/hakodb/hakodb/releases/download/$Tag"
26
- Invoke-WebRequest -Uri "$base/hakodb-x86_64-pc-windows-msvc.dll" -OutFile (Join-Path $Native "hakodb.dll")
27
- Write-Output "synced from release asset: $Tag"
28
- } else {
29
- throw "pass -CoreDir or -Tag"
30
- }
1
+ #Requires -Version 5.1
2
+ <#
3
+ .SYNOPSIS
4
+ Populate native/ from a core checkout or a release tag asset (multi-platform).
5
+ .EXAMPLE
6
+ .\sync-native.ps1 -CoreDir C:\Dev\libs\hakodb
7
+ .\sync-native.ps1 -Tag v0.9.0
8
+ .\sync-native.ps1 -Tag v0.9.0 -Platform linux
9
+ #>
10
+ param(
11
+ [string]$CoreDir = "",
12
+ [string]$Tag = "",
13
+ [string]$Platform = "",
14
+ [string]$LibTag = "linux-glibc2.28-el8"
15
+ )
16
+
17
+ $ErrorActionPreference = "Stop"
18
+ $Root = Split-Path -Parent $MyInvocation.MyCommand.Path
19
+ $Native = Join-Path $Root "native"
20
+ New-Item -ItemType Directory -Force $Native | Out-Null
21
+
22
+ # No macOS prebuilts (no CI job yet): build from source via -CoreDir on a Mac.
23
+
24
+ if ($CoreDir -ne "") {
25
+ $dll = Join-Path $CoreDir "target\release\hakodb.dll"
26
+ $so = Join-Path $CoreDir "target\release\libhakodb.so"
27
+ $dylib = Join-Path $CoreDir "target\release\libhakodb.dylib"
28
+ $found = @($dll, $so, $dylib) | Where-Object { Test-Path $_ } | Select-Object -First 1
29
+ if (-not $found) { throw "no release library under $CoreDir\target\release (cargo build --release first)" }
30
+ Copy-Item $found $Native -Force
31
+ Write-Output "synced from checkout: $CoreDir"
32
+ } elseif ($Tag -ne "") {
33
+ if ($Platform -eq "") {
34
+ if ($IsWindows -or $env:OS -eq "Windows_NT") { $Platform = "win32" }
35
+ elseif ($IsLinux) { $Platform = "linux" }
36
+ elseif ($IsMacOS) { $Platform = "darwin" }
37
+ else { $Platform = "win32" }
38
+ }
39
+ $base = "https://github.com/hakodb/hakodb/releases/download/$Tag"
40
+ if ($Platform -eq "win32") {
41
+ Invoke-WebRequest -Uri "$base/hakodb-x86_64-pc-windows-msvc.dll" -OutFile (Join-Path $Native "hakodb.dll")
42
+ } elseif ($Platform -eq "linux") {
43
+ # el8 build runs on glibc >= 2.28 everywhere; override -LibTag for an exact distro.
44
+ Invoke-WebRequest -Uri "$base/libhakodb-x86_64-unknown-$LibTag.so" -OutFile (Join-Path $Native "libhakodb.so")
45
+ } elseif ($Platform -eq "android") {
46
+ Invoke-WebRequest -Uri "$base/libhakodb-aarch64-linux-android.so" -OutFile (Join-Path $Native "libhakodb.so")
47
+ } elseif ($Platform -eq "darwin") {
48
+ throw "no macOS prebuilt (no CI job yet) - build from source and use -CoreDir on a Mac"
49
+ } else {
50
+ throw "unknown -Platform '$Platform' (win32|linux|android|darwin)"
51
+ }
52
+ Write-Output "synced from release asset: $Tag ($Platform)"
53
+ } else {
54
+ throw "pass -CoreDir or -Tag"
55
+ }