tapirus 1.0.0 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CORE_LICENSE +36 -0
- package/LICENSE +21 -0
- package/NOTICE +8 -0
- package/README.md +69 -32
- package/index.d.ts +165 -29
- package/index.js +143 -55
- package/package.json +30 -12
- package/tapirus.darwin-arm64.node +0 -0
- package/tapirus.darwin-x64.node +0 -0
- package/tapirus.linux-arm64-gnu.node +0 -0
- package/tapirus.linux-x64-gnu.node +0 -0
- package/tapirus.win32-x64-msvc.node +0 -0
package/CORE_LICENSE
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Business Source License 1.1
|
|
2
|
+
|
|
3
|
+
Parameters:
|
|
4
|
+
|
|
5
|
+
Licensor:
|
|
6
|
+
Ahmad Faiz (TapirusLab / TapirusDB)
|
|
7
|
+
|
|
8
|
+
Licensed Work:
|
|
9
|
+
TapirusDB ("tapirus") database engine source code and documentation.
|
|
10
|
+
|
|
11
|
+
Additional Use Grant:
|
|
12
|
+
You may make use of the Licensed Work (including copying, modifying, and
|
|
13
|
+
compiling it) for any application or purpose, provided that you do not offer
|
|
14
|
+
the Licensed Work as a hosted commercial Managed Database-as-a-Service (DBaaS)
|
|
15
|
+
or cloud-hosted database platform in competition with the Licensor without
|
|
16
|
+
an explicit commercial license agreement.
|
|
17
|
+
|
|
18
|
+
Individual developer usage, research, embedded application embedding,
|
|
19
|
+
self-hosted single-node deployments, and edge silicon use cases are 100%
|
|
20
|
+
permitted and royalty-free under this grant.
|
|
21
|
+
|
|
22
|
+
Change Date:
|
|
23
|
+
September 16, 2030
|
|
24
|
+
|
|
25
|
+
Change License:
|
|
26
|
+
Apache License, Version 2.0
|
|
27
|
+
|
|
28
|
+
-------------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
Notice:
|
|
31
|
+
|
|
32
|
+
The Business Source License 1.1 (the "License") is a license that allows you
|
|
33
|
+
to use the Licensed Work for free, subject to the conditions above. On the
|
|
34
|
+
Change Date, the Licensed Work will become subject to the Change License.
|
|
35
|
+
|
|
36
|
+
For full license terms and conditions, see https://mariadb.com/bsl11/
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TapirusDB Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
The packaged native addon includes the TapirusDB engine under its existing
|
|
2
|
+
Business Source License 1.1. The core license parameters and Additional Use
|
|
3
|
+
Grant are reproduced in CORE_LICENSE.
|
|
4
|
+
|
|
5
|
+
The Node wrapper source is declared MIT. That declaration does not change
|
|
6
|
+
the license of the embedded database engine. The package's license expression
|
|
7
|
+
records both components. Dependency license declarations are inventoried in
|
|
8
|
+
the release CycloneDX file; it is not an ownership or license-compliance audit.
|
package/README.md
CHANGED
|
@@ -1,48 +1,85 @@
|
|
|
1
|
-
# TapirusDB Node.js
|
|
1
|
+
# TapirusDB Node.js SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The supported runtime floor is Node.js 22; CI also covers the 24 and 26 LTS
|
|
4
|
+
lines. Release builds target Linux x64/ARM64 (glibc), macOS Intel/Apple Silicon,
|
|
5
|
+
and Windows x64. Linux musl and Windows ARM64 addons are not produced by the
|
|
6
|
+
SDK release workflow. The Rust core's broader target matrix is separate.
|
|
4
7
|
|
|
5
|
-
|
|
8
|
+
New source APIs include upsert, atomic batches, TTL, model identity, revision
|
|
9
|
+
checks and indexed retrieval diagnostics. `TapirusSessionDatabase` provides
|
|
10
|
+
independently owned transactions over serialized storage. See
|
|
11
|
+
[AI and embedded workflows](../../docs/AI_EMBEDDED_WORKFLOWS.md).
|
|
6
12
|
|
|
7
|
-
|
|
13
|
+
This package is a synchronous Node.js binding to the TapirusDB Rust engine. It requires a matching native `.node` addon. It does not switch to an in-memory JavaScript implementation if that addon is missing; opening a database fails with a diagnostic error instead.
|
|
8
14
|
|
|
9
|
-
Install
|
|
10
|
-
```bash
|
|
11
|
-
npm install ./sdks/nodejs
|
|
12
|
-
```
|
|
15
|
+
## Install and open a database
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
```bash
|
|
17
|
+
```sh
|
|
16
18
|
npm install tapirus
|
|
17
19
|
```
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
```js
|
|
22
|
+
const { open } = require('tapirus');
|
|
20
23
|
|
|
21
|
-
|
|
24
|
+
const db = open('app.tapir');
|
|
25
|
+
db.execute('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL);');
|
|
26
|
+
db.execute('INSERT INTO notes VALUES (?, ?);', [1, 'Stored on disk']);
|
|
27
|
+
console.log(db.query('SELECT id, body FROM notes WHERE id = ?;', [1]));
|
|
28
|
+
db.close();
|
|
29
|
+
```
|
|
22
30
|
|
|
23
|
-
|
|
24
|
-
import { open } from 'tapirus';
|
|
31
|
+
Use `open(':memory:')` when a transient database is intended. `close()` checkpoints the connection and propagates checkpoint errors. For deployments where native artifacts are built locally, set `TAPIRUS_NATIVE_PATH` to the addon file.
|
|
25
32
|
|
|
26
|
-
|
|
27
|
-
const db = open(':memory:');
|
|
33
|
+
## Bound parameters
|
|
28
34
|
|
|
29
|
-
|
|
30
|
-
db.execute(`
|
|
31
|
-
CREATE TABLE memories (
|
|
32
|
-
id INTEGER PRIMARY KEY,
|
|
33
|
-
content TEXT,
|
|
34
|
-
importance REAL
|
|
35
|
-
);
|
|
36
|
-
`);
|
|
35
|
+
Use `?` placeholders for values. The SDK sends parameters through the engine's prepared-statement API, so question marks inside quoted SQL strings remain literal text.
|
|
37
36
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
```js
|
|
38
|
+
db.execute('INSERT INTO notes VALUES (?, ?);', [2, "O'Reilly"]);
|
|
39
|
+
const rows = db.query("SELECT '?' AS literal, ? AS bound;", ['value']);
|
|
40
|
+
```
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
const rows = db.query('SELECT * FROM memories;');
|
|
44
|
-
console.log(rows);
|
|
42
|
+
Supported JavaScript parameter values are strings, booleans, finite numbers, `bigint`, `null`, numeric arrays for vectors, and `Uint8Array` for blobs. Integers outside JavaScript's safe number range must use `bigint`.
|
|
45
43
|
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
## Vector search and memory
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
const nearest = db.vectorSearch('notes_with_vectors', 'embedding', [0.1, 0.2, 0.3], 5);
|
|
48
|
+
const memoryId = db.remember('The user prefers concise answers', 0.7, ['preference']);
|
|
49
|
+
const memories = db.recall('answer style', 5);
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The vector column must exist on the named table and the query dimension must match its schema. TAP classification, verification, routing and scoring are heuristic engine operations; their scores are not calibrated probabilities.
|
|
53
|
+
|
|
54
|
+
## Committed change notifications
|
|
55
|
+
|
|
56
|
+
For model-supplied embeddings, namespace/session filters, transactional source storage and source citations, use `storeMemory`, `searchMemories` and `forgetMemory`. See the [AI memory guide](../../docs/AI_MEMORY.md).
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
const subscription = db.subscribe('notes', change => {
|
|
60
|
+
console.log(change.op, change.table, change.row_id);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
db.execute('BEGIN;');
|
|
64
|
+
db.execute('INSERT INTO notes VALUES (?, ?);', [3, 'Committed later']);
|
|
65
|
+
db.execute('COMMIT;');
|
|
66
|
+
subscription.unsubscribe();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Notifications are delivered after commit and after the database locks are released. Changes removed by rollback are not delivered. `row_id` is the inserted row ID for a single-row insert; it is `0` when an operation has no single known row ID.
|
|
70
|
+
|
|
71
|
+
## Native package maintenance
|
|
72
|
+
|
|
73
|
+
The supported npm package is `tapirus` in `sdks/nodejs`. Its release workflow builds platform addons and runs the persistence smoke test before publishing. The older `packages/npm` wrapper is synchronized for local compatibility and marked private; it is not a second published SDK.
|
|
74
|
+
|
|
75
|
+
Build and validate locally from the repository root:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
node scripts/build-node-sdk.js --debug
|
|
79
|
+
node sdks/nodejs/test.js
|
|
80
|
+
node scripts/test-node-package.js
|
|
48
81
|
```
|
|
82
|
+
|
|
83
|
+
The package test installs the generated npm tarball into a fresh consumer directory and checks persistence in a second Node process. SQL integers beyond the safe JavaScript number range are returned as `bigint`.
|
|
84
|
+
|
|
85
|
+
The wrapper source is declared MIT; the packaged native addon embeds the BUSL-1.1 core. `CORE_LICENSE` and `NOTICE` accompany the binary, and the npm license expression includes both existing component licenses.
|
package/index.d.ts
CHANGED
|
@@ -1,43 +1,179 @@
|
|
|
1
|
-
|
|
2
|
-
* TapirusDB Official Node.js & TypeScript SDK
|
|
3
|
-
*/
|
|
1
|
+
export type Value = string | number | bigint | boolean | null | number[] | Uint8Array;
|
|
4
2
|
|
|
5
|
-
export interface
|
|
6
|
-
path?: string;
|
|
3
|
+
export interface DatabaseOptions {
|
|
7
4
|
passphrase?: string;
|
|
5
|
+
memory?: MemoryConfig;
|
|
8
6
|
}
|
|
9
7
|
|
|
10
|
-
export interface
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
export interface ChangeEvent {
|
|
9
|
+
op: 'Insert' | 'Update' | 'Delete';
|
|
10
|
+
table: string;
|
|
11
|
+
row_id: number;
|
|
12
|
+
timestamp: number;
|
|
13
|
+
data: unknown;
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
export
|
|
16
|
-
|
|
16
|
+
export interface Subscription {
|
|
17
|
+
unsubscribe(): boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface MemoryDocument {
|
|
21
|
+
content: string;
|
|
22
|
+
embedding?: number[];
|
|
23
|
+
importance?: number;
|
|
24
|
+
tags?: string[];
|
|
25
|
+
namespace?: string;
|
|
26
|
+
sessionId?: string;
|
|
27
|
+
externalId?: string;
|
|
28
|
+
sourceVersion?: string;
|
|
29
|
+
embeddingModel?: string;
|
|
30
|
+
expiresAt?: number;
|
|
31
|
+
ttlSeconds?: number;
|
|
32
|
+
expectedRevision?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface MemorySearch {
|
|
36
|
+
query?: string;
|
|
37
|
+
embedding?: number[];
|
|
38
|
+
limit?: number;
|
|
39
|
+
namespace?: string;
|
|
40
|
+
sessionId?: string;
|
|
41
|
+
tags?: string[];
|
|
42
|
+
embeddingModel?: string;
|
|
43
|
+
candidateLimit?: number;
|
|
44
|
+
fusion?: 'rrf' | 'weighted';
|
|
45
|
+
rrfK?: number;
|
|
46
|
+
vectorWeight?: number;
|
|
47
|
+
lexicalWeight?: number;
|
|
48
|
+
recencyWeight?: number;
|
|
49
|
+
importanceWeight?: number;
|
|
50
|
+
halfLifeSeconds?: number;
|
|
51
|
+
minScore?: number;
|
|
52
|
+
exact?: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface MemoryConfig {
|
|
56
|
+
maxDocuments?: number;
|
|
57
|
+
maxEstimatedBytes?: number;
|
|
58
|
+
maxDocumentBytes?: number;
|
|
59
|
+
maxVectorDimensions?: number;
|
|
60
|
+
maxVectorSpaces?: number;
|
|
61
|
+
maxBatchDocuments?: number;
|
|
62
|
+
maxCandidates?: number;
|
|
63
|
+
hnswM?: number;
|
|
64
|
+
efConstruction?: number;
|
|
65
|
+
efSearch?: number;
|
|
66
|
+
}
|
|
67
|
+
export interface MemoryStats {
|
|
68
|
+
documents: number;
|
|
69
|
+
estimated_resident_bytes: number;
|
|
70
|
+
max_estimated_bytes: number;
|
|
71
|
+
vector_spaces: number;
|
|
72
|
+
indexed_vectors: number;
|
|
73
|
+
pending_index_updates: number;
|
|
74
|
+
}
|
|
75
|
+
export interface MemoryDeleteScope {
|
|
76
|
+
namespace?: string;
|
|
77
|
+
sessionId?: string;
|
|
78
|
+
externalId?: string;
|
|
79
|
+
sourceVersion?: string;
|
|
80
|
+
exceptSourceVersion?: string;
|
|
81
|
+
tags?: string[];
|
|
82
|
+
all?: boolean;
|
|
83
|
+
}
|
|
84
|
+
export interface MemorySearchResponse {
|
|
85
|
+
results: MemoryResult[];
|
|
86
|
+
diagnostics: {
|
|
87
|
+
total_documents: number; candidate_limit: number; lexical_candidates: number;
|
|
88
|
+
vector_candidates: number; scored_candidates: number; exact_vector_search: boolean;
|
|
89
|
+
vector_indexes_used: number; fusion: 'rrf' | 'weighted';
|
|
90
|
+
};
|
|
91
|
+
}
|
|
17
92
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
93
|
+
export interface StorageHealth {
|
|
94
|
+
reopen_required: boolean;
|
|
95
|
+
checkpoint_error: string | null;
|
|
96
|
+
wal_frames: number;
|
|
97
|
+
}
|
|
23
98
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
99
|
+
export interface MemoryResult {
|
|
100
|
+
entry: { id: number; content: string; vector: number[] | null; tags: string[]; namespace: string | null; session_id: string | null;
|
|
101
|
+
external_id: string | null; source_version: string | null; embedding_model: string | null;
|
|
102
|
+
expires_at: number | null; revision: number; updated_at: number; content_hash: string };
|
|
103
|
+
combined_score: number;
|
|
104
|
+
semantic_score: number;
|
|
105
|
+
lexical_score: number;
|
|
106
|
+
recency_score: number;
|
|
107
|
+
is_associative: boolean;
|
|
108
|
+
}
|
|
28
109
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
110
|
+
export class TapirusDatabase {
|
|
111
|
+
constructor(filePath?: string, options?: DatabaseOptions);
|
|
112
|
+
static open(path?: string, options?: DatabaseOptions): TapirusDatabase;
|
|
113
|
+
static openInMemory(options?: DatabaseOptions): TapirusDatabase;
|
|
114
|
+
static version(): string;
|
|
115
|
+
readonly isNative: true;
|
|
116
|
+
readonly isOpen: boolean;
|
|
117
|
+
readonly path: string;
|
|
118
|
+
execute(sql: string, params?: Value[]): number;
|
|
119
|
+
query<T = Record<string, unknown>>(sql: string, params?: Value[]): T[];
|
|
120
|
+
vectorSearch<T = Record<string, unknown>>(table: string, vectorColumn: string, vector: number[], limit?: number): T[];
|
|
121
|
+
graphAlgorithm(algorithm: string): Record<string, unknown>[];
|
|
122
|
+
tapClassifyDetailed(text: string, candidates: string[]): Record<string, unknown>;
|
|
123
|
+
tapClassify(text: string, candidates: string[]): string;
|
|
124
|
+
tapVerify(premise: string, hypothesis: string, threshold?: number): boolean;
|
|
125
|
+
tapScore(text: string, criteria: string): number;
|
|
126
|
+
tapRoute(state: string, routes: string[]): string;
|
|
127
|
+
remember(text: string, importance?: number, tags?: string[]): number;
|
|
128
|
+
storeMemory(document: MemoryDocument): number;
|
|
129
|
+
upsertMemory(document: MemoryDocument): number;
|
|
130
|
+
storeMemoryBatch(documents: MemoryDocument[]): number[];
|
|
131
|
+
upsertMemoryBatch(documents: MemoryDocument[]): number[];
|
|
132
|
+
searchMemories(search: MemorySearch): MemoryResult[];
|
|
133
|
+
searchMemoriesDetailed(search: MemorySearch): MemorySearchResponse;
|
|
134
|
+
configureMemory(config: MemoryConfig): MemoryStats;
|
|
135
|
+
memoryStats(): MemoryStats;
|
|
136
|
+
storageHealth(): StorageHealth;
|
|
137
|
+
prepareMemoryIndexes(): MemoryStats;
|
|
138
|
+
purgeExpiredMemories(): number;
|
|
139
|
+
deleteMemories(scope: MemoryDeleteScope): number;
|
|
140
|
+
forgetMemory(id: number): boolean;
|
|
141
|
+
recall(query: string, limit?: number): Record<string, unknown>[];
|
|
142
|
+
recallPrompt(query: string, limit?: number): string;
|
|
143
|
+
graphRagQuery(options: { query: string; limit?: number }): Record<string, unknown>;
|
|
144
|
+
subscribe(table: string, listener: (change: ChangeEvent) => void): Subscription;
|
|
145
|
+
checkpoint(): number;
|
|
146
|
+
vacuumInto(targetPath: string): number;
|
|
32
147
|
close(): void;
|
|
33
148
|
}
|
|
34
149
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
150
|
+
export function open(filePath?: string, options?: DatabaseOptions): TapirusDatabase;
|
|
151
|
+
export function version(): string;
|
|
152
|
+
export const Tapirus: typeof TapirusDatabase;
|
|
153
|
+
|
|
154
|
+
/** Sessions serialize access; a transaction belongs to one session. */
|
|
155
|
+
export class TapirusSessionDatabase {
|
|
156
|
+
constructor(filePath?: string, options?: DatabaseOptions);
|
|
157
|
+
session(options?: { busyTimeoutMs?: number }): TapirusSession;
|
|
158
|
+
close(): void;
|
|
159
|
+
}
|
|
160
|
+
export interface TapirusSession extends Pick<TapirusDatabase,
|
|
161
|
+
'execute' | 'query' | 'storeMemory' | 'upsertMemory' | 'storeMemoryBatch' |
|
|
162
|
+
'upsertMemoryBatch' | 'searchMemories' | 'searchMemoriesDetailed' |
|
|
163
|
+
'configureMemory' | 'memoryStats' | 'storageHealth' | 'prepareMemoryIndexes' |
|
|
164
|
+
'purgeExpiredMemories' | 'deleteMemories' | 'forgetMemory' | 'checkpoint' | 'close'> {
|
|
165
|
+
begin(): void;
|
|
166
|
+
commit(): void;
|
|
167
|
+
rollback(): void;
|
|
168
|
+
/** The callback must be synchronous. */
|
|
169
|
+
transaction<T>(callback: (session: TapirusSession) => T extends PromiseLike<unknown> ? never : T): T;
|
|
170
|
+
}
|
|
39
171
|
|
|
40
|
-
|
|
41
|
-
open
|
|
42
|
-
|
|
172
|
+
declare const _default: {
|
|
173
|
+
open: typeof open;
|
|
174
|
+
version: typeof version;
|
|
175
|
+
Tapirus: typeof TapirusDatabase;
|
|
176
|
+
TapirusDatabase: typeof TapirusDatabase;
|
|
177
|
+
TapirusSessionDatabase: typeof TapirusSessionDatabase;
|
|
43
178
|
};
|
|
179
|
+
export default _default;
|
package/index.js
CHANGED
|
@@ -1,65 +1,153 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
// Shared native loader source. scripts/sync-node-sdk.js copies this API to both npm packages.
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
let binding;
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
7
|
+
function loadBinding() {
|
|
8
|
+
if (binding) return binding;
|
|
9
|
+
const candidates = process.env.TAPIRUS_NATIVE_PATH
|
|
10
|
+
? [path.resolve(process.env.TAPIRUS_NATIVE_PATH)]
|
|
11
|
+
: [path.join(__dirname, 'tapirus.node'), path.join(__dirname, 'build', 'Release', 'tapirus.node'),
|
|
12
|
+
...fs.readdirSync(__dirname).filter(file => /^tapirus\..+\.node$/.test(file)).map(file => path.join(__dirname, file))];
|
|
13
|
+
const failures = [];
|
|
14
|
+
for (const file of candidates) {
|
|
15
|
+
if (!fs.existsSync(file)) continue;
|
|
16
|
+
try {
|
|
17
|
+
const native = { exports: {} };
|
|
18
|
+
process.dlopen(native, file);
|
|
19
|
+
if (typeof native.exports.TapirusClient !== 'function') throw new Error('Missing TapirusClient export');
|
|
20
|
+
binding = native.exports;
|
|
21
|
+
return binding;
|
|
22
|
+
} catch (error) { failures.push(`${path.basename(file)}: ${error.message}`); }
|
|
17
23
|
}
|
|
24
|
+
throw new Error(`TapirusDB native engine is unavailable for ${process.platform}/${process.arch}. Install a package containing the matching .node binary or set TAPIRUS_NATIVE_PATH for a local build.${failures.length ? '\n' + failures.join('\n') : ''}`);
|
|
25
|
+
}
|
|
18
26
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
27
|
+
function paramsJson(params) {
|
|
28
|
+
if (!Array.isArray(params)) throw new TypeError('Parameters must be an array');
|
|
29
|
+
return JSON.stringify(params, (_key, value) => {
|
|
30
|
+
if (typeof value === 'bigint') return { $integer: value.toString() };
|
|
31
|
+
if (value instanceof Uint8Array || (value && value.type === 'Buffer' && Array.isArray(value.data))) return { $blob: Array.from(value.data || value) };
|
|
32
|
+
if (typeof value === 'number' && (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value)))) throw new TypeError('Use finite numbers and bigint for integers outside the safe JS range');
|
|
33
|
+
if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new TypeError('Unsupported SQL parameter');
|
|
34
|
+
return value;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function identifier(value) {
|
|
38
|
+
if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) throw new TypeError('Invalid SQL identifier');
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function limitValue(value) {
|
|
42
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('Limit must be a nonnegative safe integer');
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
23
45
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
46
|
+
function memoryPayload(value) {
|
|
47
|
+
const names = { sessionId: 'session_id', externalId: 'external_id', sourceVersion: 'source_version', exceptSourceVersion: 'except_source_version', embeddingModel: 'embedding_model', expiresAt: 'expires_at', ttlSeconds: 'ttl_seconds', expectedRevision: 'expected_revision', candidateLimit: 'candidate_limit', rrfK: 'rrf_k', vectorWeight: 'vector_weight', lexicalWeight: 'lexical_weight', recencyWeight: 'recency_weight', importanceWeight: 'importance_weight', halfLifeSeconds: 'half_life_seconds', minScore: 'min_score', maxDocuments: 'max_documents', maxEstimatedBytes: 'max_estimated_bytes', maxDocumentBytes: 'max_document_bytes', maxVectorDimensions: 'max_vector_dimensions', maxVectorSpaces: 'max_vector_spaces', maxBatchDocuments: 'max_batch_documents', maxCandidates: 'max_candidates', hnswM: 'hnsw_m', efConstruction: 'ef_construction', efSearch: 'ef_search' };
|
|
48
|
+
const normalize = item => {
|
|
49
|
+
if (typeof item === 'number' && (!Number.isFinite(item) || (Number.isInteger(item) && !Number.isSafeInteger(item)))) throw new TypeError('Memory values require finite numbers and exact integer parameters');
|
|
50
|
+
if (Array.isArray(item)) return item.map(normalize);
|
|
51
|
+
if (item && typeof item === 'object') {
|
|
52
|
+
const output = Object.create(null);
|
|
53
|
+
for (const [key, entry] of Object.entries(item)) {
|
|
54
|
+
const name = names[key] || key;
|
|
55
|
+
if (Object.hasOwn(output, name)) throw new TypeError(`Duplicate memory field: ${name}`);
|
|
56
|
+
output[name] = normalize(entry);
|
|
57
|
+
}
|
|
58
|
+
return output;
|
|
35
59
|
}
|
|
36
|
-
return
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
if (this.isClosed) throw new Error('TapirusConnection is closed');
|
|
41
|
-
const clean = sql.trim().replace(/;$/, '');
|
|
42
|
-
const parts = clean.split(/\s+/);
|
|
43
|
-
const upperParts = parts.map(p => p.toUpperCase());
|
|
44
|
-
const fromIdx = upperParts.indexOf('FROM');
|
|
60
|
+
return item;
|
|
61
|
+
};
|
|
62
|
+
return JSON.stringify(normalize(value));
|
|
63
|
+
}
|
|
45
64
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
65
|
+
class TapirusDatabase {
|
|
66
|
+
constructor(filePath = ':memory:', options = {}) {
|
|
67
|
+
const nativeOptions = { dbPath: filePath };
|
|
68
|
+
if (options.passphrase !== undefined) nativeOptions.passphrase = options.passphrase;
|
|
69
|
+
if (options.memory !== undefined) nativeOptions.memoryConfigJson = memoryPayload(options.memory);
|
|
70
|
+
this._db = new (loadBinding().TapirusClient)(nativeOptions);
|
|
71
|
+
this.isNative = true;
|
|
72
|
+
this.isOpen = true;
|
|
73
|
+
this.path = filePath;
|
|
51
74
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
75
|
+
static open(filePath = ':memory:', options = {}) { return new TapirusDatabase(filePath, options); }
|
|
76
|
+
static openInMemory(options = {}) { return new TapirusDatabase(':memory:', options); }
|
|
77
|
+
static version() { return loadBinding().version(); }
|
|
78
|
+
execute(sql, params = []) { return this._db.execute(sql, paramsJson(params)); }
|
|
79
|
+
query(sql, params = []) { return this._db.query(sql, paramsJson(params)); }
|
|
80
|
+
vectorSearch(table, column, vector, limit = 5) {
|
|
81
|
+
return this.query(`SELECT * FROM ${identifier(table)} VECTOR NEAR ${identifier(column)} = ? TOP ${limitValue(limit)};`, [vector]);
|
|
82
|
+
}
|
|
83
|
+
graphAlgorithm(algorithm) { return this.query(`GRAPH ALGORITHM ${identifier(algorithm)};`); }
|
|
84
|
+
tapClassifyDetailed(text, candidates) { return JSON.parse(this._db.tapClassifyJson(text, candidates)); }
|
|
85
|
+
tapClassify(text, candidates) { return this.tapClassifyDetailed(text, candidates).top_choice; }
|
|
86
|
+
tapVerify(premise, hypothesis, threshold = 0.5) { return this._db.tapVerify(premise, hypothesis, threshold); }
|
|
87
|
+
tapScore(text, criteria) { return this._db.tapScore(text, criteria); }
|
|
88
|
+
tapRoute(state, routes) { return this._db.tapRoute(state, routes); }
|
|
89
|
+
remember(text, importance = 0.5, tags = []) { return this._db.remember(text, importance, tags); }
|
|
90
|
+
storeMemory(document) { return this._db.storeMemoryJson(memoryPayload(document)); }
|
|
91
|
+
searchMemories(search) { return JSON.parse(this._db.searchMemoriesJson(memoryPayload(search))); }
|
|
92
|
+
_memoryRequest(operation, payload = {}) { return JSON.parse(this._db.memoryRequestJson(operation, memoryPayload(payload))); }
|
|
93
|
+
upsertMemory(document) { return this._memoryRequest('upsert', document); }
|
|
94
|
+
storeMemoryBatch(documents) { return this._memoryRequest('store_batch', documents); }
|
|
95
|
+
upsertMemoryBatch(documents) { return this._memoryRequest('upsert_batch', documents); }
|
|
96
|
+
searchMemoriesDetailed(search) { return this._memoryRequest('search_detailed', search); }
|
|
97
|
+
configureMemory(config) { return this._memoryRequest('configure', config); }
|
|
98
|
+
memoryStats() { return this._memoryRequest('stats'); }
|
|
99
|
+
storageHealth() { return this._memoryRequest('storage_health'); }
|
|
100
|
+
prepareMemoryIndexes() { return this._memoryRequest('prepare'); }
|
|
101
|
+
purgeExpiredMemories() { return this._memoryRequest('purge_expired'); }
|
|
102
|
+
deleteMemories(scope) { return this._memoryRequest('delete', scope); }
|
|
103
|
+
forgetMemory(id) {
|
|
104
|
+
if (!Number.isSafeInteger(id) || id < 1) throw new TypeError('Memory ID must be a positive safe integer');
|
|
105
|
+
return this._db.forgetMemory(String(id));
|
|
106
|
+
}
|
|
107
|
+
recall(query, limit = 5) { return JSON.parse(this._db.recallJson(query, limitValue(limit))); }
|
|
108
|
+
recallPrompt(query, limit = 5) { return this._db.recallPrompt(query, limitValue(limit)); }
|
|
109
|
+
graphRagQuery({ query, limit = 5 }) { return JSON.parse(this._db.graphRagJson(query, limitValue(limit))); }
|
|
110
|
+
subscribe(table, listener) {
|
|
111
|
+
const key = identifier(table).toLowerCase();
|
|
112
|
+
const id = this._db.subscribe(key, (error, json) => {
|
|
113
|
+
if (error) throw error;
|
|
114
|
+
listener(JSON.parse(json));
|
|
115
|
+
});
|
|
116
|
+
return { unsubscribe: () => this._db.unsubscribe(id) };
|
|
55
117
|
}
|
|
118
|
+
checkpoint() { return this._db.checkpoint(); }
|
|
119
|
+
vacuumInto(targetPath) { return this.execute('VACUUM INTO ?;', [targetPath]); }
|
|
120
|
+
close() { this._db.close(); this.isOpen = false; }
|
|
56
121
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
122
|
+
class TapirusSessionDatabase {
|
|
123
|
+
constructor(filePath = ':memory:', options = {}) {
|
|
124
|
+
this._db = new (loadBinding().SessionDatabaseClient)({ dbPath: filePath, passphrase: options.passphrase, memoryConfigJson: options.memory === undefined ? undefined : memoryPayload(options.memory) });
|
|
125
|
+
}
|
|
126
|
+
session({ busyTimeoutMs = 0 } = {}) {
|
|
127
|
+
if (!Number.isInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 0xffffffff) throw new TypeError('Invalid session busyTimeoutMs');
|
|
128
|
+
return new TapirusSession(this._db.session(busyTimeoutMs));
|
|
129
|
+
}
|
|
130
|
+
close() { this._db.close(); }
|
|
60
131
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
132
|
+
class TapirusSession {
|
|
133
|
+
constructor(native) { this._db = native; }
|
|
134
|
+
execute(sql, params = []) { return this._db.execute(sql, paramsJson(params)); }
|
|
135
|
+
query(sql, params = []) { return this._db.query(sql, paramsJson(params)); }
|
|
136
|
+
begin() { this.execute('BEGIN'); }
|
|
137
|
+
commit() { this.execute('COMMIT'); }
|
|
138
|
+
rollback() { this.execute('ROLLBACK'); }
|
|
139
|
+
transaction(callback) {
|
|
140
|
+
this.begin();
|
|
141
|
+
try {
|
|
142
|
+
const result = callback(this);
|
|
143
|
+
if (result && typeof result.then === 'function') throw new TypeError('Session transaction callbacks must be synchronous');
|
|
144
|
+
this.commit(); return result;
|
|
145
|
+
} catch (error) { try { this.rollback(); } catch (rollback) { error.rollbackError = rollback; } throw error; }
|
|
146
|
+
}
|
|
147
|
+
checkpoint() { return this._db.checkpoint(); }
|
|
148
|
+
close() { this._db.close(); }
|
|
149
|
+
}
|
|
150
|
+
for (const name of ['_memoryRequest', 'storeMemory', 'searchMemories', 'upsertMemory', 'storeMemoryBatch', 'upsertMemoryBatch', 'searchMemoriesDetailed', 'configureMemory', 'memoryStats', 'storageHealth', 'prepareMemoryIndexes', 'purgeExpiredMemories', 'deleteMemories', 'forgetMemory']) {
|
|
151
|
+
Object.defineProperty(TapirusSession.prototype, name, { value: TapirusDatabase.prototype[name] });
|
|
152
|
+
}
|
|
153
|
+
module.exports = { open: TapirusDatabase.open, Tapirus: TapirusDatabase, TapirusDatabase, TapirusSessionDatabase, version: TapirusDatabase.version };
|
package/package.json
CHANGED
|
@@ -1,17 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tapirus",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "Official Node.js
|
|
3
|
+
"version": "1.0.4",
|
|
4
|
+
"description": "Official Node.js and TypeScript SDK for TapirusDB's embedded database APIs",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
|
-
"
|
|
8
|
-
"
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
11
|
"index.js",
|
|
12
12
|
"index.d.ts",
|
|
13
|
-
"
|
|
13
|
+
"CORE_LICENSE",
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"NOTICE",
|
|
16
|
+
"*.node"
|
|
14
17
|
],
|
|
18
|
+
"napi": {
|
|
19
|
+
"name": "tapirus",
|
|
20
|
+
"triples": {
|
|
21
|
+
"additional": [
|
|
22
|
+
"x86_64-apple-darwin",
|
|
23
|
+
"aarch64-apple-darwin",
|
|
24
|
+
"x86_64-pc-windows-msvc",
|
|
25
|
+
"x86_64-unknown-linux-gnu",
|
|
26
|
+
"aarch64-unknown-linux-gnu"
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "node ../../scripts/build-node-sdk.js",
|
|
32
|
+
"build:debug": "node ../../scripts/build-node-sdk.js --debug",
|
|
33
|
+
"test": "node test.js",
|
|
34
|
+
"test:package": "node ../../scripts/test-node-package.js",
|
|
35
|
+
"prepack": "node verify-native.js"
|
|
36
|
+
},
|
|
15
37
|
"keywords": [
|
|
16
38
|
"tapirus",
|
|
17
39
|
"tapirusdb",
|
|
@@ -23,14 +45,10 @@
|
|
|
23
45
|
"rag",
|
|
24
46
|
"graph"
|
|
25
47
|
],
|
|
26
|
-
"author": "
|
|
27
|
-
"license": "BUSL-1.1",
|
|
48
|
+
"author": "TapirusDB Contributors <contact@tapirusdb.com>",
|
|
49
|
+
"license": "MIT AND BUSL-1.1",
|
|
28
50
|
"repository": {
|
|
29
51
|
"type": "git",
|
|
30
52
|
"url": "git+https://github.com/tapiruslab/TapirusDB.git"
|
|
31
|
-
}
|
|
32
|
-
"bugs": {
|
|
33
|
-
"url": "https://github.com/tapiruslab/TapirusDB/issues"
|
|
34
|
-
},
|
|
35
|
-
"homepage": "https://tapirusdb.com"
|
|
53
|
+
}
|
|
36
54
|
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|