sutradb-core 0.0.0-stage → 5.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # `sutradb-core` — Node.js & TypeScript Bindings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Native `napi-rs` bindings for **SutraDB** (embedded Rust SIMD vector + BM25 + WAND sparse + ColBERT hybrid search) with zero-copy `Float32Array` vector ingest/query, instant `.sutra.idx` cold restarts, and a zero-dependency `SutraClient` for remote `sutradb-server` / Edge runtimes.
4
+
5
+ ---
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install sutradb-core@5.6.1
11
+ ```
12
+
13
+ ---
14
+
15
+ ## Embedded Zero-Copy `Float32Array` Quickstart
16
+
17
+ ```ts
18
+ import { SutraDB, detectSimd } from "sutradb-core";
19
+
20
+ console.log("Host SIMD:", detectSimd());
21
+
22
+ const db = new SutraDB("./sutra_data");
23
+ const col = db.getOrCreateCollection("kb", 4, { metric: "cosine", enableWal: true });
24
+
25
+ // Zero-copy TypedArray batch insert (flat row-major: docs * dimension)
26
+ const vectors = new Float32Array([
27
+ 1, 0, 0, 0,
28
+ 0, 1, 0, 0,
29
+ ]);
30
+
31
+ col.insertBatch(
32
+ vectors,
33
+ ["doc_1", "doc_2"],
34
+ ["Rust HNSW with Roaring metadata filtering", "Zero-copy mmap cold start"],
35
+ [{ tier: "prod", latency_ms: 0.18 }, { tier: "prod", latency_ms: 96.6 }]
36
+ );
37
+
38
+ col.buildHnsw({ m: 16, efConstruction: 100, efSearch: 64 });
39
+ col.save();
40
+
41
+ const hits = col.query({
42
+ vector: new Float32Array([1, 0, 0, 0]),
43
+ text: "Roaring filtering",
44
+ filter: { tier: "prod", latency_ms: { $lt: 1.0 } },
45
+ topK: 5,
46
+ useAnn: true,
47
+ });
48
+
49
+ console.log(hits);
50
+ ```
51
+
52
+ ---
53
+
54
+ ## Remote `SutraClient` (Edge / Serverless Compatible)
55
+
56
+ Uses standard Web `fetch` (Node 18+, Cloudflare Workers, Vercel Edge, Deno) with zero native addon dependencies when imported from `sutradb-core/client`:
57
+
58
+ ```ts
59
+ import { SutraClient } from "sutradb-core/client";
60
+
61
+ const client = new SutraClient({
62
+ baseUrl: "http://127.0.0.1:8765",
63
+ apiKey: process.env.SUTRA_API_KEY,
64
+ });
65
+
66
+ await client.createCollection("edge_kb", 384, { metric: "cosine", enableWal: true });
67
+ await client.insert("edge_kb", [
68
+ {
69
+ id: "d1",
70
+ vector: new Float32Array(384).fill(0.05),
71
+ text: "Standalone Rust sutradb-server serves gRPC, HTTP, and /ui",
72
+ metadata: { env: "prod" },
73
+ },
74
+ ]);
75
+
76
+ const results = await client.query("edge_kb", {
77
+ vector: new Float32Array(384).fill(0.05),
78
+ filter: { env: "prod" },
79
+ topK: 3,
80
+ });
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Quantization & Maintenance
86
+
87
+ - `col.enableBq()` — 1-Bit Binary Quantization (32× vector RAM compression + hardware `POPCNT`)
88
+ - `col.enableSq8()` — 8-Bit Scalar Quantization (4× compression)
89
+ - `col.trainPq({ m, maxSamples })` + `col.enablePq()` — Product Quantization (up to 64× compression)
90
+ - `col.compact()` — Tombstone reclamation & slab compaction
91
+ - `col.save()` / `col.load()` — Atomic `.sutra` + `.sutra.idx` (`SUTRAIDX v2`) sidecar persistence
package/client.d.ts ADDED
@@ -0,0 +1,100 @@
1
+ import type {
2
+ CreateCollectionOptions,
3
+ DocumentRecord,
4
+ HnswOptions,
5
+ QueryOptions,
6
+ SearchResult,
7
+ TrainPqOptions,
8
+ } from "./native.js";
9
+
10
+ export type RemoteVector = Float32Array | Array<number>;
11
+
12
+ export interface RemoteDocumentInput {
13
+ id?: string;
14
+ vector: RemoteVector;
15
+ text?: string;
16
+ metadata?: Record<string, any>;
17
+ namespace?: string;
18
+ sparseVector?: Record<string, number>;
19
+ colbertTokens?: Array<Array<number>>;
20
+ }
21
+
22
+ export interface SutraClientOptions {
23
+ baseUrl?: string;
24
+ apiKey?: string;
25
+ timeoutMs?: number;
26
+ headers?: Record<string, string>;
27
+ fetch?: typeof globalThis.fetch;
28
+ }
29
+
30
+ export interface RemoteQueryOptions extends QueryOptions {
31
+ vector?: RemoteVector;
32
+ }
33
+
34
+ export declare class SutraClientError extends Error {
35
+ status?: number;
36
+ body?: unknown;
37
+ constructor(message: string, status?: number, body?: unknown);
38
+ }
39
+
40
+ export declare class SutraClient {
41
+ baseUrl: string;
42
+ apiKey?: string;
43
+ timeoutMs: number;
44
+ constructor(optionsOrUrl?: string | SutraClientOptions);
45
+ health(): Promise<{
46
+ status: string;
47
+ version: string;
48
+ collections: Array<string>;
49
+ uptime_seconds: number;
50
+ }>;
51
+ listCollections(): Promise<Array<Record<string, any>>>;
52
+ createCollection(
53
+ name: string,
54
+ dimension?: number,
55
+ options?: Pick<CreateCollectionOptions, "metric" | "enableWal">
56
+ ): Promise<Record<string, any>>;
57
+ dropCollection(name: string): Promise<{ message: string }>;
58
+ stats(collection: string): Promise<Record<string, any>>;
59
+ insert(
60
+ collection: string,
61
+ documents: Array<RemoteDocumentInput>
62
+ ): Promise<{ inserted: number; total_count: number }>;
63
+ upsert(
64
+ collection: string,
65
+ documents: Array<RemoteDocumentInput>
66
+ ): Promise<{ upserted: number; total_count: number }>;
67
+ get(collection: string, docId: string): Promise<DocumentRecord | null>;
68
+ listDocuments(
69
+ collection: string,
70
+ options?: { limit?: number; offset?: number }
71
+ ): Promise<{
72
+ total: number;
73
+ limit: number;
74
+ offset: number;
75
+ documents: Array<Record<string, any>>;
76
+ }>;
77
+ updateMetadata(
78
+ collection: string,
79
+ docId: string,
80
+ metadata: Record<string, any>
81
+ ): Promise<{ updated: boolean; message: string }>;
82
+ delete(
83
+ collection: string,
84
+ ids: string | Array<string>
85
+ ): Promise<{ deleted: number; message: string }>;
86
+ query(collection: string, options: RemoteQueryOptions): Promise<Array<SearchResult>>;
87
+ buildHnsw(
88
+ collection: string,
89
+ options?: HnswOptions
90
+ ): Promise<Record<string, any>>;
91
+ enableBq(collection: string): Promise<Record<string, any>>;
92
+ enableSq8(collection: string): Promise<Record<string, any>>;
93
+ trainPq(
94
+ collection: string,
95
+ options?: TrainPqOptions
96
+ ): Promise<Record<string, any>>;
97
+ enablePq(collection: string): Promise<Record<string, any>>;
98
+ compact(collection: string): Promise<Record<string, any>>;
99
+ save(collection: string): Promise<Record<string, any>>;
100
+ }
package/client.js ADDED
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+
3
+ class SutraClientError extends Error {
4
+ constructor(message, status, body) {
5
+ super(message);
6
+ this.name = "SutraClientError";
7
+ this.status = status;
8
+ this.body = body;
9
+ }
10
+ }
11
+
12
+ function normalizeVector(vec) {
13
+ if (vec == null) return undefined;
14
+ return Array.isArray(vec) ? vec : Array.from(vec);
15
+ }
16
+
17
+ function normalizeDocument(doc) {
18
+ const out = {
19
+ vector: normalizeVector(doc.vector),
20
+ text: doc.text ?? "",
21
+ metadata: doc.metadata ?? {},
22
+ };
23
+ if (doc.id !== undefined) out.id = doc.id;
24
+ if (doc.namespace !== undefined) out.namespace = doc.namespace;
25
+ if (doc.sparseVector !== undefined || doc.sparse_vector !== undefined) {
26
+ out.sparse_vector = doc.sparseVector ?? doc.sparse_vector;
27
+ }
28
+ if (doc.colbertTokens !== undefined || doc.colbert_tokens !== undefined) {
29
+ out.colbert_tokens = doc.colbertTokens ?? doc.colbert_tokens;
30
+ }
31
+ return out;
32
+ }
33
+
34
+ function requirePathSegment(value, label) {
35
+ if (typeof value !== "string" || value.trim().length === 0) {
36
+ throw new SutraClientError(`${label} must be a non-empty string`);
37
+ }
38
+ return encodeURIComponent(value);
39
+ }
40
+
41
+ class SutraClient {
42
+ constructor(optionsOrUrl = "http://localhost:8765") {
43
+ const opts =
44
+ typeof optionsOrUrl === "string"
45
+ ? { baseUrl: optionsOrUrl }
46
+ : optionsOrUrl || {};
47
+ const rawBaseUrl = (opts.baseUrl || "http://localhost:8765").replace(/\/+$/, "");
48
+ let parsedUrl;
49
+ try {
50
+ parsedUrl = new URL(rawBaseUrl);
51
+ } catch {
52
+ throw new SutraClientError(`Invalid SutraDB baseUrl: ${rawBaseUrl}`);
53
+ }
54
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
55
+ throw new SutraClientError(
56
+ `Unsupported baseUrl protocol '${parsedUrl.protocol}'; expected http: or https:`
57
+ );
58
+ }
59
+ this.baseUrl = rawBaseUrl;
60
+ this.apiKey = opts.apiKey;
61
+ this.timeoutMs = typeof opts.timeoutMs === "number" ? opts.timeoutMs : 30000;
62
+ this.defaultHeaders = Object.assign({}, opts.headers || {});
63
+ this.fetchImpl = opts.fetch || globalThis.fetch;
64
+ if (typeof this.fetchImpl !== "function") {
65
+ throw new SutraClientError(
66
+ "globalThis.fetch is unavailable; provide Node >=18 or pass options.fetch"
67
+ );
68
+ }
69
+ }
70
+
71
+ async _request(method, path, body) {
72
+ const headers = Object.assign({}, this.defaultHeaders);
73
+ if (this.apiKey) {
74
+ headers.Authorization = `Bearer ${this.apiKey}`;
75
+ }
76
+ if (body !== undefined) {
77
+ headers["Content-Type"] = "application/json";
78
+ }
79
+
80
+ const controller = new AbortController();
81
+ const timer =
82
+ this.timeoutMs > 0
83
+ ? setTimeout(() => controller.abort(), this.timeoutMs)
84
+ : null;
85
+
86
+ try {
87
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
88
+ method,
89
+ headers,
90
+ body: body !== undefined ? JSON.stringify(body) : undefined,
91
+ signal: controller.signal,
92
+ });
93
+
94
+ const contentType = response.headers.get("content-type") || "";
95
+ const text = await response.text();
96
+ let parsed = null;
97
+ if (text) {
98
+ if (contentType.includes("application/json")) {
99
+ try {
100
+ parsed = JSON.parse(text);
101
+ } catch {
102
+ parsed = text;
103
+ }
104
+ } else {
105
+ try {
106
+ parsed = JSON.parse(text);
107
+ } catch {
108
+ parsed = text;
109
+ }
110
+ }
111
+ }
112
+
113
+ if (!response.ok) {
114
+ const detail =
115
+ (parsed &&
116
+ typeof parsed === "object" &&
117
+ (parsed.detail || parsed.error || parsed.message)) ||
118
+ (typeof parsed === "string" ? parsed : response.statusText);
119
+ throw new SutraClientError(
120
+ `HTTP ${response.status}: ${detail}`,
121
+ response.status,
122
+ parsed
123
+ );
124
+ }
125
+
126
+ return parsed;
127
+ } finally {
128
+ if (timer !== null) clearTimeout(timer);
129
+ }
130
+ }
131
+
132
+ async health() {
133
+ return this._request("GET", "/health");
134
+ }
135
+
136
+ async listCollections() {
137
+ const data = await this._request("GET", "/collections");
138
+ return (data && data.collections) || [];
139
+ }
140
+
141
+ async createCollection(name, dimension = 384, options = {}) {
142
+ return this._request("POST", "/collections", {
143
+ name,
144
+ dimension,
145
+ metric: options.metric ?? "cosine",
146
+ enable_wal: Boolean(options.enableWal),
147
+ });
148
+ }
149
+
150
+ async dropCollection(name) {
151
+ return this._request("DELETE", `/collections/${requirePathSegment(name, "collection")}`);
152
+ }
153
+
154
+ async stats(collection) {
155
+ return this._request(
156
+ "GET",
157
+ `/collections/${requirePathSegment(collection, "collection")}/stats`
158
+ );
159
+ }
160
+
161
+ async insert(collection, documents) {
162
+ return this._request(
163
+ "POST",
164
+ `/collections/${requirePathSegment(collection, "collection")}/insert`,
165
+ { documents: documents.map(normalizeDocument) }
166
+ );
167
+ }
168
+
169
+ async upsert(collection, documents) {
170
+ return this._request(
171
+ "POST",
172
+ `/collections/${requirePathSegment(collection, "collection")}/upsert`,
173
+ { documents: documents.map(normalizeDocument) }
174
+ );
175
+ }
176
+
177
+ async get(collection, docId) {
178
+ try {
179
+ return await this._request(
180
+ "GET",
181
+ `/collections/${requirePathSegment(collection, "collection")}/documents/${requirePathSegment(
182
+ docId,
183
+ "docId"
184
+ )}`
185
+ );
186
+ } catch (err) {
187
+ if (err instanceof SutraClientError && err.status === 404) {
188
+ return null;
189
+ }
190
+ throw err;
191
+ }
192
+ }
193
+
194
+ async listDocuments(collection, options = {}) {
195
+ const params = new URLSearchParams();
196
+ if (options.limit !== undefined) params.set("limit", String(options.limit));
197
+ if (options.offset !== undefined) {
198
+ params.set("offset", String(options.offset));
199
+ }
200
+ const qs = params.toString();
201
+ const suffix = qs ? `?${qs}` : "";
202
+ return this._request(
203
+ "GET",
204
+ `/collections/${requirePathSegment(collection, "collection")}/documents${suffix}`
205
+ );
206
+ }
207
+
208
+ async updateMetadata(collection, docId, metadata) {
209
+ return this._request(
210
+ "PATCH",
211
+ `/collections/${requirePathSegment(collection, "collection")}/documents/${requirePathSegment(
212
+ docId,
213
+ "docId"
214
+ )}/metadata`,
215
+ { metadata }
216
+ );
217
+ }
218
+
219
+ async delete(collection, ids) {
220
+ const idList = Array.isArray(ids) ? ids : [ids];
221
+ return this._request(
222
+ "DELETE",
223
+ `/collections/${requirePathSegment(collection, "collection")}/documents`,
224
+ { ids: idList }
225
+ );
226
+ }
227
+
228
+ async query(collection, options = {}) {
229
+ const payload = {
230
+ top_k: options.topK ?? 10,
231
+ hybrid: options.hybrid ?? true,
232
+ use_ann: options.useAnn ?? false,
233
+ };
234
+ if (options.vector !== undefined) {
235
+ payload.vector = normalizeVector(options.vector);
236
+ }
237
+ if (options.text !== undefined) payload.text = options.text;
238
+ if (options.filter !== undefined) payload.filter = options.filter;
239
+ if (options.namespace !== undefined) payload.namespace = options.namespace;
240
+ if (options.sparseVector !== undefined) {
241
+ payload.sparse_vector = options.sparseVector;
242
+ }
243
+ if (options.colbertTokens !== undefined) {
244
+ payload.colbert_tokens = options.colbertTokens;
245
+ }
246
+ if (options.rrfConstant !== undefined) {
247
+ payload.rrf_constant = options.rrfConstant;
248
+ }
249
+ if (options.denseWeight !== undefined) {
250
+ payload.dense_weight = options.denseWeight;
251
+ }
252
+ if (options.bm25Weight !== undefined) {
253
+ payload.bm25_weight = options.bm25Weight;
254
+ }
255
+ if (options.sparseWeight !== undefined) {
256
+ payload.sparse_weight = options.sparseWeight;
257
+ }
258
+ if (options.colbertWeight !== undefined) {
259
+ payload.colbert_weight = options.colbertWeight;
260
+ }
261
+ if (options.alpha !== undefined) payload.alpha = options.alpha;
262
+
263
+ const data = await this._request(
264
+ "POST",
265
+ `/collections/${requirePathSegment(collection, "collection")}/query`,
266
+ payload
267
+ );
268
+ const raw = (data && data.results) || [];
269
+ return raw.map((r) => ({
270
+ id: r.id,
271
+ score: r.score,
272
+ text: r.text,
273
+ denseScore: r.dense_score,
274
+ bm25Score: r.bm25_score,
275
+ sparseScore: r.sparse_score,
276
+ colbertScore: r.colbert_score,
277
+ namespace: r.namespace ?? null,
278
+ metadata: r.metadata ?? {},
279
+ }));
280
+ }
281
+
282
+ async buildHnsw(collection, options = {}) {
283
+ return this._request(
284
+ "POST",
285
+ `/collections/${requirePathSegment(collection, "collection")}/hnsw`,
286
+ {
287
+ m: options.m ?? 16,
288
+ ef_construction: options.efConstruction ?? 200,
289
+ ef_search: options.efSearch ?? 64,
290
+ }
291
+ );
292
+ }
293
+
294
+ async enableBq(collection) {
295
+ return this._request(
296
+ "POST",
297
+ `/collections/${requirePathSegment(collection, "collection")}/bq`,
298
+ {}
299
+ );
300
+ }
301
+
302
+ async enableSq8(collection) {
303
+ return this._request(
304
+ "POST",
305
+ `/collections/${requirePathSegment(collection, "collection")}/sq8`,
306
+ {}
307
+ );
308
+ }
309
+
310
+ async trainPq(collection, options = {}) {
311
+ return this._request(
312
+ "POST",
313
+ `/collections/${requirePathSegment(collection, "collection")}/pq/train`,
314
+ {
315
+ m: options.m ?? null,
316
+ max_samples: options.maxSamples ?? null,
317
+ }
318
+ );
319
+ }
320
+
321
+ async enablePq(collection) {
322
+ return this._request(
323
+ "POST",
324
+ `/collections/${requirePathSegment(collection, "collection")}/pq`,
325
+ {}
326
+ );
327
+ }
328
+
329
+ async compact(collection) {
330
+ return this._request(
331
+ "POST",
332
+ `/collections/${requirePathSegment(collection, "collection")}/compact`,
333
+ {}
334
+ );
335
+ }
336
+
337
+ async save(collection) {
338
+ return this._request(
339
+ "POST",
340
+ `/collections/${requirePathSegment(collection, "collection")}/save`,
341
+ {}
342
+ );
343
+ }
344
+ }
345
+
346
+ module.exports = { SutraClient, SutraClientError };
package/client.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import clientMod from "./client.js";
2
+
3
+ export const { SutraClient, SutraClientError } = clientMod;
4
+ export default SutraClient;
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./native.js";
2
+ export * from "./client.js";
package/index.js ADDED
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+
3
+ const { SutraClient, SutraClientError } = require("./client.js");
4
+
5
+ let nativeModule = null;
6
+ let nativeLoadError = null;
7
+
8
+ try {
9
+ nativeModule = require("./native.js");
10
+ } catch (err) {
11
+ nativeLoadError = err;
12
+ }
13
+
14
+ function makeMissingNativeClass(name) {
15
+ return class {
16
+ constructor() {
17
+ const reason = nativeLoadError ? nativeLoadError.message : "unknown error";
18
+ throw new Error(
19
+ `Native SutraDB addon is unavailable for '${name}': ${reason}. ` +
20
+ `Use SutraClient from "sutradb-core/client" in Edge/Serverless runtimes, ` +
21
+ `or build the native binding with "npm run build".`
22
+ );
23
+ }
24
+ };
25
+ }
26
+
27
+ const SutraDB = nativeModule ? nativeModule.SutraDB : makeMissingNativeClass("SutraDB");
28
+ const Collection = nativeModule
29
+ ? nativeModule.Collection
30
+ : makeMissingNativeClass("Collection");
31
+ const detectSimd = nativeModule
32
+ ? nativeModule.detectSimd
33
+ : () => {
34
+ throw nativeLoadError || new Error("Native SutraDB addon is unavailable");
35
+ };
36
+
37
+ module.exports = {
38
+ SutraDB,
39
+ Collection,
40
+ detectSimd,
41
+ SutraClient,
42
+ SutraClientError,
43
+ };
package/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import pkg from "./index.js";
2
+
3
+ export const { SutraDB, Collection, detectSimd, SutraClient, SutraClientError } = pkg;
4
+ export default SutraDB;
package/native.d.ts ADDED
@@ -0,0 +1,120 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /* auto-generated by NAPI-RS */
5
+
6
+ export interface AnalyzerOptions {
7
+ lowercase?: boolean
8
+ stemmer?: boolean
9
+ stopwords?: boolean
10
+ language?: string
11
+ splitIdentifiers?: boolean
12
+ cjkBigrams?: boolean
13
+ }
14
+ export interface CreateCollectionOptions {
15
+ metric?: string
16
+ enableWal?: boolean
17
+ storagePath?: string
18
+ analyzer?: AnalyzerOptions
19
+ }
20
+ export interface DocumentInput {
21
+ id?: string
22
+ vector: Float32Array | Array<number>
23
+ text?: string
24
+ metadata?: any
25
+ namespace?: string
26
+ sparseVector?: Record<string, number>
27
+ colbertTokens?: Array<Array<number>>
28
+ }
29
+ export interface QueryOptions {
30
+ vector?: Float32Array | Array<number>
31
+ text?: string
32
+ sparseVector?: Record<string, number>
33
+ colbertTokens?: Array<Array<number>>
34
+ filter?: any
35
+ namespace?: string
36
+ topK?: number
37
+ hybrid?: boolean
38
+ rrfConstant?: number
39
+ denseWeight?: number
40
+ bm25Weight?: number
41
+ sparseWeight?: number
42
+ colbertWeight?: number
43
+ alpha?: number
44
+ useAnn?: boolean
45
+ }
46
+ export interface SearchResult {
47
+ id: string
48
+ score: number
49
+ text: string
50
+ denseScore?: number
51
+ bm25Score?: number
52
+ sparseScore?: number
53
+ colbertScore?: number
54
+ namespace?: string
55
+ metadata: any
56
+ }
57
+ export interface DocumentRecord {
58
+ id: string
59
+ text: string
60
+ namespace?: string
61
+ metadata: any
62
+ vector?: Float32Array
63
+ sparseVector?: Record<string, number>
64
+ colbertTokens?: Array<Array<number>>
65
+ }
66
+ export interface HnswOptions {
67
+ m?: number
68
+ efConstruction?: number
69
+ efSearch?: number
70
+ }
71
+ export interface IvfOptions {
72
+ nLists?: number
73
+ nprobe?: number
74
+ }
75
+ export interface TrainPqOptions {
76
+ m?: number
77
+ maxSamples?: number
78
+ }
79
+ export interface ColbertQueryOptions {
80
+ namespace?: string
81
+ filter?: any
82
+ topK?: number
83
+ }
84
+ /** Returns the active SIMD instruction level detected on the host CPU. */
85
+ export declare function detectSimd(): string
86
+ /** In-process Rust SIMD hybrid vector + lexical collection. */
87
+ export declare class Collection {
88
+ constructor(name: string, dimension: number, options?: CreateCollectionOptions | undefined | null)
89
+ /** Zero-copy batch ingest from a flat row-major `Float32Array` (`ids.length * dimension`). */
90
+ insertBatch(vectors: Float32Array, ids: Array<string>, texts: Array<string>, metadatas?: Array<any | undefined | null> | undefined | null, namespaces?: Array<string | undefined | null> | undefined | null, sparseVectors?: Array<Record<string, number> | undefined | null> | undefined | null, colbertTokens?: Array<Array<Array<number>> | undefined | null> | undefined | null): number
91
+ insert(documents: Array<DocumentInput>): number
92
+ upsert(documents: Array<DocumentInput>): number
93
+ get(docId: string): DocumentRecord | null
94
+ getAll(includeVectors?: boolean | undefined | null): Array<DocumentRecord>
95
+ delete(ids: string | Array<string>): number
96
+ updateMetadata(docId: string, metadata: any): boolean
97
+ query(options: QueryOptions): Array<SearchResult>
98
+ queryColbert(queryTokens: Array<Array<number>>, options?: ColbertQueryOptions | undefined | null): Array<SearchResult>
99
+ buildHnsw(options?: HnswOptions | undefined | null): void
100
+ buildIvf(options?: IvfOptions | undefined | null): void
101
+ enableBq(): void
102
+ enableSq8(): void
103
+ trainPq(options?: TrainPqOptions | undefined | null): void
104
+ enablePq(): void
105
+ compact(): number
106
+ save(path?: string | undefined | null): number
107
+ load(path?: string | undefined | null): number
108
+ verifyChecksum(path?: string | undefined | null): void
109
+ stats(): any
110
+ count(): number
111
+ }
112
+ /** Top-level embedded database manager for disk-backed or in-memory collections. */
113
+ export declare class SutraDB {
114
+ constructor(dataDir?: string | undefined | null)
115
+ createCollection(name: string, dimension?: number | undefined | null, options?: CreateCollectionOptions | undefined | null): Collection
116
+ getCollection(name: string): Collection
117
+ getOrCreateCollection(name: string, dimension?: number | undefined | null, options?: CreateCollectionOptions | undefined | null): Collection
118
+ listCollections(): Array<string>
119
+ dropCollection(name: string): boolean
120
+ }
package/native.js ADDED
@@ -0,0 +1,317 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /* prettier-ignore */
4
+
5
+ /* auto-generated by NAPI-RS */
6
+
7
+ const { existsSync, readFileSync } = require('fs')
8
+ const { join } = require('path')
9
+
10
+ const { platform, arch } = process
11
+
12
+ let nativeBinding = null
13
+ let localFileExisted = false
14
+ let loadError = null
15
+
16
+ function isMusl() {
17
+ // For Node 10
18
+ if (!process.report || typeof process.report.getReport !== 'function') {
19
+ try {
20
+ const lddPath = require('child_process').execSync('which ldd').toString().trim()
21
+ return readFileSync(lddPath, 'utf8').includes('musl')
22
+ } catch (e) {
23
+ return true
24
+ }
25
+ } else {
26
+ const { glibcVersionRuntime } = process.report.getReport().header
27
+ return !glibcVersionRuntime
28
+ }
29
+ }
30
+
31
+ switch (platform) {
32
+ case 'android':
33
+ switch (arch) {
34
+ case 'arm64':
35
+ localFileExisted = existsSync(join(__dirname, 'sutradb-node.android-arm64.node'))
36
+ try {
37
+ if (localFileExisted) {
38
+ nativeBinding = require('./sutradb-node.android-arm64.node')
39
+ } else {
40
+ nativeBinding = require('sutradb-core-android-arm64')
41
+ }
42
+ } catch (e) {
43
+ loadError = e
44
+ }
45
+ break
46
+ case 'arm':
47
+ localFileExisted = existsSync(join(__dirname, 'sutradb-node.android-arm-eabi.node'))
48
+ try {
49
+ if (localFileExisted) {
50
+ nativeBinding = require('./sutradb-node.android-arm-eabi.node')
51
+ } else {
52
+ nativeBinding = require('sutradb-core-android-arm-eabi')
53
+ }
54
+ } catch (e) {
55
+ loadError = e
56
+ }
57
+ break
58
+ default:
59
+ throw new Error(`Unsupported architecture on Android ${arch}`)
60
+ }
61
+ break
62
+ case 'win32':
63
+ switch (arch) {
64
+ case 'x64':
65
+ localFileExisted = existsSync(
66
+ join(__dirname, 'sutradb-node.win32-x64-msvc.node')
67
+ )
68
+ try {
69
+ if (localFileExisted) {
70
+ nativeBinding = require('./sutradb-node.win32-x64-msvc.node')
71
+ } else {
72
+ nativeBinding = require('sutradb-core-win32-x64-msvc')
73
+ }
74
+ } catch (e) {
75
+ loadError = e
76
+ }
77
+ break
78
+ case 'ia32':
79
+ localFileExisted = existsSync(
80
+ join(__dirname, 'sutradb-node.win32-ia32-msvc.node')
81
+ )
82
+ try {
83
+ if (localFileExisted) {
84
+ nativeBinding = require('./sutradb-node.win32-ia32-msvc.node')
85
+ } else {
86
+ nativeBinding = require('sutradb-core-win32-ia32-msvc')
87
+ }
88
+ } catch (e) {
89
+ loadError = e
90
+ }
91
+ break
92
+ case 'arm64':
93
+ localFileExisted = existsSync(
94
+ join(__dirname, 'sutradb-node.win32-arm64-msvc.node')
95
+ )
96
+ try {
97
+ if (localFileExisted) {
98
+ nativeBinding = require('./sutradb-node.win32-arm64-msvc.node')
99
+ } else {
100
+ nativeBinding = require('sutradb-core-win32-arm64-msvc')
101
+ }
102
+ } catch (e) {
103
+ loadError = e
104
+ }
105
+ break
106
+ default:
107
+ throw new Error(`Unsupported architecture on Windows: ${arch}`)
108
+ }
109
+ break
110
+ case 'darwin':
111
+ localFileExisted = existsSync(join(__dirname, 'sutradb-node.darwin-universal.node'))
112
+ try {
113
+ if (localFileExisted) {
114
+ nativeBinding = require('./sutradb-node.darwin-universal.node')
115
+ } else {
116
+ nativeBinding = require('sutradb-core-darwin-universal')
117
+ }
118
+ break
119
+ } catch {}
120
+ switch (arch) {
121
+ case 'x64':
122
+ localFileExisted = existsSync(join(__dirname, 'sutradb-node.darwin-x64.node'))
123
+ try {
124
+ if (localFileExisted) {
125
+ nativeBinding = require('./sutradb-node.darwin-x64.node')
126
+ } else {
127
+ nativeBinding = require('sutradb-core-darwin-x64')
128
+ }
129
+ } catch (e) {
130
+ loadError = e
131
+ }
132
+ break
133
+ case 'arm64':
134
+ localFileExisted = existsSync(
135
+ join(__dirname, 'sutradb-node.darwin-arm64.node')
136
+ )
137
+ try {
138
+ if (localFileExisted) {
139
+ nativeBinding = require('./sutradb-node.darwin-arm64.node')
140
+ } else {
141
+ nativeBinding = require('sutradb-core-darwin-arm64')
142
+ }
143
+ } catch (e) {
144
+ loadError = e
145
+ }
146
+ break
147
+ default:
148
+ throw new Error(`Unsupported architecture on macOS: ${arch}`)
149
+ }
150
+ break
151
+ case 'freebsd':
152
+ if (arch !== 'x64') {
153
+ throw new Error(`Unsupported architecture on FreeBSD: ${arch}`)
154
+ }
155
+ localFileExisted = existsSync(join(__dirname, 'sutradb-node.freebsd-x64.node'))
156
+ try {
157
+ if (localFileExisted) {
158
+ nativeBinding = require('./sutradb-node.freebsd-x64.node')
159
+ } else {
160
+ nativeBinding = require('sutradb-core-freebsd-x64')
161
+ }
162
+ } catch (e) {
163
+ loadError = e
164
+ }
165
+ break
166
+ case 'linux':
167
+ switch (arch) {
168
+ case 'x64':
169
+ if (isMusl()) {
170
+ localFileExisted = existsSync(
171
+ join(__dirname, 'sutradb-node.linux-x64-musl.node')
172
+ )
173
+ try {
174
+ if (localFileExisted) {
175
+ nativeBinding = require('./sutradb-node.linux-x64-musl.node')
176
+ } else {
177
+ nativeBinding = require('sutradb-core-linux-x64-musl')
178
+ }
179
+ } catch (e) {
180
+ loadError = e
181
+ }
182
+ } else {
183
+ localFileExisted = existsSync(
184
+ join(__dirname, 'sutradb-node.linux-x64-gnu.node')
185
+ )
186
+ try {
187
+ if (localFileExisted) {
188
+ nativeBinding = require('./sutradb-node.linux-x64-gnu.node')
189
+ } else {
190
+ nativeBinding = require('sutradb-core-linux-x64-gnu')
191
+ }
192
+ } catch (e) {
193
+ loadError = e
194
+ }
195
+ }
196
+ break
197
+ case 'arm64':
198
+ if (isMusl()) {
199
+ localFileExisted = existsSync(
200
+ join(__dirname, 'sutradb-node.linux-arm64-musl.node')
201
+ )
202
+ try {
203
+ if (localFileExisted) {
204
+ nativeBinding = require('./sutradb-node.linux-arm64-musl.node')
205
+ } else {
206
+ nativeBinding = require('sutradb-core-linux-arm64-musl')
207
+ }
208
+ } catch (e) {
209
+ loadError = e
210
+ }
211
+ } else {
212
+ localFileExisted = existsSync(
213
+ join(__dirname, 'sutradb-node.linux-arm64-gnu.node')
214
+ )
215
+ try {
216
+ if (localFileExisted) {
217
+ nativeBinding = require('./sutradb-node.linux-arm64-gnu.node')
218
+ } else {
219
+ nativeBinding = require('sutradb-core-linux-arm64-gnu')
220
+ }
221
+ } catch (e) {
222
+ loadError = e
223
+ }
224
+ }
225
+ break
226
+ case 'arm':
227
+ if (isMusl()) {
228
+ localFileExisted = existsSync(
229
+ join(__dirname, 'sutradb-node.linux-arm-musleabihf.node')
230
+ )
231
+ try {
232
+ if (localFileExisted) {
233
+ nativeBinding = require('./sutradb-node.linux-arm-musleabihf.node')
234
+ } else {
235
+ nativeBinding = require('sutradb-core-linux-arm-musleabihf')
236
+ }
237
+ } catch (e) {
238
+ loadError = e
239
+ }
240
+ } else {
241
+ localFileExisted = existsSync(
242
+ join(__dirname, 'sutradb-node.linux-arm-gnueabihf.node')
243
+ )
244
+ try {
245
+ if (localFileExisted) {
246
+ nativeBinding = require('./sutradb-node.linux-arm-gnueabihf.node')
247
+ } else {
248
+ nativeBinding = require('sutradb-core-linux-arm-gnueabihf')
249
+ }
250
+ } catch (e) {
251
+ loadError = e
252
+ }
253
+ }
254
+ break
255
+ case 'riscv64':
256
+ if (isMusl()) {
257
+ localFileExisted = existsSync(
258
+ join(__dirname, 'sutradb-node.linux-riscv64-musl.node')
259
+ )
260
+ try {
261
+ if (localFileExisted) {
262
+ nativeBinding = require('./sutradb-node.linux-riscv64-musl.node')
263
+ } else {
264
+ nativeBinding = require('sutradb-core-linux-riscv64-musl')
265
+ }
266
+ } catch (e) {
267
+ loadError = e
268
+ }
269
+ } else {
270
+ localFileExisted = existsSync(
271
+ join(__dirname, 'sutradb-node.linux-riscv64-gnu.node')
272
+ )
273
+ try {
274
+ if (localFileExisted) {
275
+ nativeBinding = require('./sutradb-node.linux-riscv64-gnu.node')
276
+ } else {
277
+ nativeBinding = require('sutradb-core-linux-riscv64-gnu')
278
+ }
279
+ } catch (e) {
280
+ loadError = e
281
+ }
282
+ }
283
+ break
284
+ case 's390x':
285
+ localFileExisted = existsSync(
286
+ join(__dirname, 'sutradb-node.linux-s390x-gnu.node')
287
+ )
288
+ try {
289
+ if (localFileExisted) {
290
+ nativeBinding = require('./sutradb-node.linux-s390x-gnu.node')
291
+ } else {
292
+ nativeBinding = require('sutradb-core-linux-s390x-gnu')
293
+ }
294
+ } catch (e) {
295
+ loadError = e
296
+ }
297
+ break
298
+ default:
299
+ throw new Error(`Unsupported architecture on Linux: ${arch}`)
300
+ }
301
+ break
302
+ default:
303
+ throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
304
+ }
305
+
306
+ if (!nativeBinding) {
307
+ if (loadError) {
308
+ throw loadError
309
+ }
310
+ throw new Error(`Failed to load native binding`)
311
+ }
312
+
313
+ const { detectSimd, Collection, SutraDB } = nativeBinding
314
+
315
+ module.exports.detectSimd = detectSimd
316
+ module.exports.Collection = Collection
317
+ module.exports.SutraDB = SutraDB
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "sutradb-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.6.1",
4
+ "description": "Embedded Rust + Node.js hybrid vector database (HNSW, BM25, WAND sparse, ColBERT) with zero-copy Float32Array SIMD, 32x BQ, and sub-ms Roaring filtering, plus zero-dependency SutraClient.",
5
+ "main": "index.js",
6
+ "module": "index.mjs",
7
+ "types": "index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "import": "./index.mjs",
12
+ "require": "./index.js"
13
+ },
14
+ "./client": {
15
+ "types": "./client.d.ts",
16
+ "import": "./client.mjs",
17
+ "require": "./client.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "index.js",
22
+ "index.mjs",
23
+ "index.d.ts",
24
+ "native.js",
25
+ "native.d.ts",
26
+ "client.js",
27
+ "client.mjs",
28
+ "client.d.ts",
29
+ "README.md"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "napi": {
35
+ "name": "sutradb-node",
36
+ "triples": {
37
+ "defaults": false,
38
+ "additional": [
39
+ "x86_64-unknown-linux-gnu",
40
+ "aarch64-unknown-linux-gnu",
41
+ "aarch64-apple-darwin",
42
+ "x86_64-apple-darwin",
43
+ "x86_64-pc-windows-msvc"
44
+ ]
45
+ }
46
+ },
47
+ "scripts": {
48
+ "build": "napi build --platform --release --js native.js --dts native.d.ts",
49
+ "build:debug": "napi build --platform --js native.js --dts native.d.ts",
50
+ "artifacts": "napi artifacts",
51
+ "test": "node --test test/sutradb.test.mjs"
52
+ },
53
+ "engines": {
54
+ "node": ">=18.0.0"
55
+ },
56
+ "keywords": [
57
+ "vector-database",
58
+ "hybrid-search",
59
+ "hnsw",
60
+ "bm25",
61
+ "rag",
62
+ "colbert",
63
+ "embeddings",
64
+ "rust",
65
+ "napi-rs",
66
+ "simd",
67
+ "embedded-database"
68
+ ],
69
+ "author": "Samarth Nimangre <samarthknimangre@gmail.com>",
70
+ "license": "MIT",
71
+ "repository": {
72
+ "type": "git",
73
+ "url": "git+https://github.com/Sam-CodesAI/SutraDB.git",
74
+ "directory": "bindings/node"
75
+ },
76
+ "homepage": "https://github.com/Sam-CodesAI/SutraDB/tree/main/bindings/node#readme",
77
+ "bugs": {
78
+ "url": "https://github.com/Sam-CodesAI/SutraDB/issues"
79
+ },
80
+ "devDependencies": {
81
+ "@napi-rs/cli": "^2.18.4"
82
+ },
83
+ "optionalDependencies": {
84
+ "sutradb-core-darwin-arm64": "5.6.1",
85
+ "sutradb-core-darwin-x64": "5.6.1",
86
+ "sutradb-core-linux-arm64-gnu": "5.6.1",
87
+ "sutradb-core-linux-x64-gnu": "5.6.1",
88
+ "sutradb-core-win32-x64-msvc": "5.6.1"
89
+ }
90
+ }