@mirk/store 0.4.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/LICENSE +202 -0
- package/README.md +108 -0
- package/dist/adapters/sqlite.d.ts +27 -0
- package/dist/adapters/sqlite.js +382 -0
- package/dist/chunk-GC4MYP45.js +43 -0
- package/dist/chunk-ZFSKQHBT.js +62 -0
- package/dist/chunk-ZI4JA6IU.js +148 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +22 -0
- package/dist/kv.d.ts +28 -0
- package/dist/kv.js +8 -0
- package/dist/types-BqSZEMAB.d.ts +57 -0
- package/dist/types-DyQLNtxa.d.ts +83 -0
- package/dist/vector.d.ts +35 -0
- package/dist/vector.js +16 -0
- package/package.json +80 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 David Robinson
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# @mirk/store
|
|
2
|
+
|
|
3
|
+
Code-split storage **ports** + source **adapters** under one namespace. Import the whole
|
|
4
|
+
namespace, or just the specific subpath you need — the interface ports and their in-memory
|
|
5
|
+
reference implementations are zero-native, and only the SQLite adapter references native
|
|
6
|
+
bindings (as optional peers).
|
|
7
|
+
|
|
8
|
+
ESM-only (the package exposes `import` entry points; there is no CommonJS build).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @mirk/store
|
|
14
|
+
# Using the SQLite adapter (@mirk/store/sqlite)? Add its peer:
|
|
15
|
+
npm install better-sqlite3
|
|
16
|
+
# Optional: vec0 KNN acceleration (graceful exact-JS fallback without it)
|
|
17
|
+
npm install sqlite-vec
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Subpaths
|
|
21
|
+
|
|
22
|
+
| Import | What it gives you | Native deps |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `@mirk/store` | the ports + their in-memory references + `toAsync` + cosine helpers | none |
|
|
25
|
+
| `@mirk/store/kv` | `SyncStore` port (key-value + collections), `InMemoryKv`, `toAsync` | none |
|
|
26
|
+
| `@mirk/store/vector` | `VectorStore` port, `InMemoryVectorStore`, cosine helpers | none |
|
|
27
|
+
| `@mirk/store/sqlite` | the SQLite **source adapter** — one connection, `.kv` + `.vector` facets | `better-sqlite3` (peer), `sqlite-vec` (optional peer) |
|
|
28
|
+
|
|
29
|
+
Source adapters are reached **only** through their own subpath (e.g. `/sqlite`) — the root and the
|
|
30
|
+
port subpaths never re-export them, so importing `@mirk/store`, `/kv`, or `/vector` never drags a
|
|
31
|
+
native binding into a consumer bundle.
|
|
32
|
+
|
|
33
|
+
## Quickstart — zero native deps
|
|
34
|
+
|
|
35
|
+
The in-memory references implement the same ports as the backends, so you can build against them
|
|
36
|
+
with nothing installed:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { InMemoryKv, toAsync } from "@mirk/store/kv";
|
|
40
|
+
|
|
41
|
+
const kv = new InMemoryKv();
|
|
42
|
+
kv.set("user:1", { name: "Ada" });
|
|
43
|
+
kv.get<{ name: string }>("user:1"); // { name: "Ada" }
|
|
44
|
+
kv.keys("user:"); // ["user:1"]
|
|
45
|
+
|
|
46
|
+
// Lift any SyncStore to a Promise-returning API (one-way: sync ⊂ async):
|
|
47
|
+
const asyncKv = toAsync(kv);
|
|
48
|
+
await asyncKv.get("user:1");
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Collections
|
|
52
|
+
|
|
53
|
+
A `SyncStore` is also a small document store, keyed by `id`:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
kv.put("posts", { id: "p1", title: "Hello", pinned: true });
|
|
57
|
+
kv.getById("posts", "p1"); // { id: "p1", title: "Hello", pinned: true }
|
|
58
|
+
kv.list("posts", { where: { pinned: true }, sortBy: "title", limit: 10 });
|
|
59
|
+
kv.count("posts"); // 1
|
|
60
|
+
kv.remove("posts", "p1");
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## SQLite adapter — one connection, many capabilities
|
|
64
|
+
|
|
65
|
+
`SqliteAdapter` opens a single `better-sqlite3` database and exposes a `.kv` facet (a `SyncStore`)
|
|
66
|
+
and a `.vector` facet (a `VectorStore`) over it:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { SqliteAdapter } from "@mirk/store/sqlite";
|
|
70
|
+
|
|
71
|
+
// `dimensions` is required to use the .vector facet; .kv works without it.
|
|
72
|
+
const db = new SqliteAdapter({ path: "data.db", dimensions: 768 });
|
|
73
|
+
|
|
74
|
+
db.kv.set("user:1", { name: "Ada" });
|
|
75
|
+
|
|
76
|
+
const embedding = new Float32Array(768); // your real embedding here
|
|
77
|
+
const query = new Float32Array(768);
|
|
78
|
+
db.vector.upsert("docs", { id: "a", vector: embedding });
|
|
79
|
+
const results = db.vector.search("docs", query, { topK: 10 }); // ranked by cosine
|
|
80
|
+
|
|
81
|
+
db.close();
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### `SqliteAdapter` options
|
|
85
|
+
|
|
86
|
+
| Option | Type | Notes |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `path` | `string` | DB file path, or `":memory:"`. |
|
|
89
|
+
| `db` | `Database` | Reuse an existing `better-sqlite3` connection instead of opening one. |
|
|
90
|
+
| `dimensions` | `number` | Embedding dimensionality. Required before using `.vector`; persisted and enforced on reopen. |
|
|
91
|
+
| `forceJsCosine` | `boolean` | Pin the exact JS-cosine path even when `sqlite-vec` is installed (mainly for tests). |
|
|
92
|
+
|
|
93
|
+
Vectors (`Vector` is a `Float32Array`) are stored as little-endian float32 BLOBs and ranked by
|
|
94
|
+
**exact cosine**. When the optional `sqlite-vec` peer is installed, search is transparently
|
|
95
|
+
accelerated by vec0 using the `cosine` distance metric, so rankings are identical to the JS path;
|
|
96
|
+
without it, the exact JS-cosine fallback runs. `db.vector.meta.accelerated` reports which path is
|
|
97
|
+
live.
|
|
98
|
+
|
|
99
|
+
## Sync by design
|
|
100
|
+
|
|
101
|
+
Embedded backends are **synchronous** — `better-sqlite3` is synchronous, and an async-everywhere
|
|
102
|
+
interface would tax every local call with a Promise it doesn't need. A `SyncStore` lifts to an
|
|
103
|
+
async API via `toAsync(store)`; the reverse is impossible. Pick sync for embedded/local, and reach
|
|
104
|
+
for async only where a remote backend genuinely requires it.
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
Apache-2.0 © David Robinson
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import Database from 'better-sqlite3';
|
|
2
|
+
import { b as SyncStore } from '../types-DyQLNtxa.js';
|
|
3
|
+
import { d as VectorStore } from '../types-BqSZEMAB.js';
|
|
4
|
+
|
|
5
|
+
interface SqliteAdapterOptions {
|
|
6
|
+
/** Path to the SQLite database file. Use ":memory:" for in-memory. */
|
|
7
|
+
path: string;
|
|
8
|
+
/** Existing better-sqlite3 instance to reuse (shares one connection). */
|
|
9
|
+
db?: Database.Database;
|
|
10
|
+
/** Embedding dimensions. Required to use the `.vector` facet; KV works without it. */
|
|
11
|
+
dimensions?: number;
|
|
12
|
+
/** Force the exact JS-cosine search path even when sqlite-vec is installed.
|
|
13
|
+
* Mainly for parity testing; production should leave this off. */
|
|
14
|
+
forceJsCosine?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Multi-capability sqlite source adapter. Open once; use `.kv` and/or `.vector`
|
|
17
|
+
* — both ride the same connection. */
|
|
18
|
+
declare class SqliteAdapter {
|
|
19
|
+
private readonly db;
|
|
20
|
+
readonly kv: SyncStore;
|
|
21
|
+
readonly vector: VectorStore;
|
|
22
|
+
constructor(opts: SqliteAdapterOptions);
|
|
23
|
+
/** Close the underlying connection (shared by both facets). */
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export { SqliteAdapter, type SqliteAdapterOptions };
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertDimensions,
|
|
3
|
+
bufferToVector,
|
|
4
|
+
cosineSimilarity,
|
|
5
|
+
vectorToBuffer
|
|
6
|
+
} from "../chunk-GC4MYP45.js";
|
|
7
|
+
|
|
8
|
+
// src/adapters/sqlite.ts
|
|
9
|
+
import Database from "better-sqlite3";
|
|
10
|
+
import { createRequire } from "module";
|
|
11
|
+
var nodeRequire = createRequire(import.meta.url);
|
|
12
|
+
function tryLoadSqliteVec(db) {
|
|
13
|
+
try {
|
|
14
|
+
const vec = nodeRequire("sqlite-vec");
|
|
15
|
+
if (typeof vec.load === "function") {
|
|
16
|
+
vec.load(db);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
if (typeof vec.getLoadablePath === "function") {
|
|
20
|
+
db.loadExtension(vec.getLoadablePath());
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function isUsableVector(v) {
|
|
29
|
+
let nonZero = false;
|
|
30
|
+
for (let i = 0; i < v.length; i++) {
|
|
31
|
+
const x = v[i] ?? 0;
|
|
32
|
+
if (!Number.isFinite(x)) return false;
|
|
33
|
+
if (x !== 0) nonZero = true;
|
|
34
|
+
}
|
|
35
|
+
return nonZero;
|
|
36
|
+
}
|
|
37
|
+
var SqliteAdapter = class {
|
|
38
|
+
db;
|
|
39
|
+
kv;
|
|
40
|
+
vector;
|
|
41
|
+
constructor(opts) {
|
|
42
|
+
const ownsDb = opts.db === void 0;
|
|
43
|
+
this.db = opts.db ?? new Database(opts.path);
|
|
44
|
+
try {
|
|
45
|
+
this.db.pragma("journal_mode = WAL");
|
|
46
|
+
this.kv = new SqliteKvFacet(this.db);
|
|
47
|
+
this.vector = new SqliteVectorFacet(this.db, opts.path, opts.dimensions, opts.forceJsCosine);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (ownsDb) {
|
|
50
|
+
try {
|
|
51
|
+
this.db.close();
|
|
52
|
+
} catch {
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Close the underlying connection (shared by both facets). */
|
|
59
|
+
close() {
|
|
60
|
+
this.db.close();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
var SqliteKvFacet = class {
|
|
64
|
+
constructor(db) {
|
|
65
|
+
this.db = db;
|
|
66
|
+
this.db.pragma("foreign_keys = ON");
|
|
67
|
+
this.db.exec(`
|
|
68
|
+
CREATE TABLE IF NOT EXISTS _kv (
|
|
69
|
+
key TEXT PRIMARY KEY,
|
|
70
|
+
value TEXT NOT NULL,
|
|
71
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
72
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
73
|
+
)
|
|
74
|
+
`);
|
|
75
|
+
}
|
|
76
|
+
db;
|
|
77
|
+
meta = { backend: "sqlite" };
|
|
78
|
+
initializedTables = /* @__PURE__ */ new Set();
|
|
79
|
+
tableName(collection) {
|
|
80
|
+
if (collection.length === 0) throw new Error("Invalid collection name");
|
|
81
|
+
const sanitized = collection.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
82
|
+
return `c_${sanitized}_${hashName(collection)}`;
|
|
83
|
+
}
|
|
84
|
+
ensureTable(collection) {
|
|
85
|
+
const table = this.tableName(collection);
|
|
86
|
+
if (this.initializedTables.has(table)) return table;
|
|
87
|
+
this.db.exec(
|
|
88
|
+
`CREATE TABLE IF NOT EXISTS ${table} (
|
|
89
|
+
id TEXT PRIMARY KEY,
|
|
90
|
+
data JSON NOT NULL,
|
|
91
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
92
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
93
|
+
)`
|
|
94
|
+
);
|
|
95
|
+
this.initializedTables.add(table);
|
|
96
|
+
return table;
|
|
97
|
+
}
|
|
98
|
+
get(key) {
|
|
99
|
+
const row = this.db.prepare("SELECT value FROM _kv WHERE key = ?").get(key);
|
|
100
|
+
if (!row) return null;
|
|
101
|
+
return JSON.parse(row.value);
|
|
102
|
+
}
|
|
103
|
+
set(key, value) {
|
|
104
|
+
this.db.prepare(
|
|
105
|
+
`INSERT INTO _kv (key, value, updated_at) VALUES (?, ?, datetime('now'))
|
|
106
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')`
|
|
107
|
+
).run(key, JSON.stringify(value));
|
|
108
|
+
}
|
|
109
|
+
has(key) {
|
|
110
|
+
return this.db.prepare("SELECT 1 FROM _kv WHERE key = ?").get(key) !== void 0;
|
|
111
|
+
}
|
|
112
|
+
delete(key) {
|
|
113
|
+
return this.db.prepare("DELETE FROM _kv WHERE key = ?").run(key).changes > 0;
|
|
114
|
+
}
|
|
115
|
+
keys(prefix) {
|
|
116
|
+
if (prefix) {
|
|
117
|
+
const escaped = prefix.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
118
|
+
const rows2 = this.db.prepare(`SELECT key FROM _kv WHERE key LIKE ? ESCAPE '\\' ORDER BY key`).all(`${escaped}%`);
|
|
119
|
+
return rows2.map((r) => r.key);
|
|
120
|
+
}
|
|
121
|
+
const rows = this.db.prepare("SELECT key FROM _kv ORDER BY key").all();
|
|
122
|
+
return rows.map((r) => r.key);
|
|
123
|
+
}
|
|
124
|
+
list(collection, filter) {
|
|
125
|
+
const table = this.ensureTable(collection);
|
|
126
|
+
const where = buildWhereClause(filter);
|
|
127
|
+
const orderBy = buildOrderBy(filter);
|
|
128
|
+
const limitOffset = buildLimitOffset(filter);
|
|
129
|
+
const sql = `SELECT data FROM ${table}${where.clause}${orderBy.clause}${limitOffset}`;
|
|
130
|
+
const rows = this.db.prepare(sql).all(...where.params, ...orderBy.params);
|
|
131
|
+
return rows.map((r) => JSON.parse(r.data));
|
|
132
|
+
}
|
|
133
|
+
getById(collection, id) {
|
|
134
|
+
const table = this.ensureTable(collection);
|
|
135
|
+
const row = this.db.prepare(`SELECT data FROM ${table} WHERE id = ?`).get(id);
|
|
136
|
+
if (!row) return null;
|
|
137
|
+
return JSON.parse(row.data);
|
|
138
|
+
}
|
|
139
|
+
put(collection, item) {
|
|
140
|
+
const table = this.ensureTable(collection);
|
|
141
|
+
this.db.prepare(
|
|
142
|
+
`INSERT INTO ${table} (id, data, updated_at) VALUES (?, ?, datetime('now'))
|
|
143
|
+
ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')`
|
|
144
|
+
).run(item.id, JSON.stringify(item));
|
|
145
|
+
return item;
|
|
146
|
+
}
|
|
147
|
+
remove(collection, id) {
|
|
148
|
+
const table = this.ensureTable(collection);
|
|
149
|
+
return this.db.prepare(`DELETE FROM ${table} WHERE id = ?`).run(id).changes > 0;
|
|
150
|
+
}
|
|
151
|
+
count(collection, filter) {
|
|
152
|
+
const table = this.ensureTable(collection);
|
|
153
|
+
const where = buildWhereClause(filter);
|
|
154
|
+
const row = this.db.prepare(`SELECT COUNT(*) as cnt FROM ${table}${where.clause}`).get(...where.params);
|
|
155
|
+
return row.cnt;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
var SqliteVectorFacet = class {
|
|
159
|
+
constructor(db, path, dimensions, forceJsCosine) {
|
|
160
|
+
this.db = db;
|
|
161
|
+
this.db.exec(
|
|
162
|
+
`CREATE TABLE IF NOT EXISTS vectors (
|
|
163
|
+
collection TEXT NOT NULL,
|
|
164
|
+
id TEXT NOT NULL,
|
|
165
|
+
vec BLOB NOT NULL,
|
|
166
|
+
metadata TEXT,
|
|
167
|
+
PRIMARY KEY (collection, id)
|
|
168
|
+
);
|
|
169
|
+
CREATE INDEX IF NOT EXISTS vectors_collection ON vectors(collection);
|
|
170
|
+
CREATE TABLE IF NOT EXISTS _vec_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);`
|
|
171
|
+
);
|
|
172
|
+
const stored = this.db.prepare(`SELECT value FROM _vec_meta WHERE key = 'dimensions'`).get();
|
|
173
|
+
if (stored) {
|
|
174
|
+
this.dimensions = Number(stored.value);
|
|
175
|
+
if (dimensions !== void 0 && dimensions !== this.dimensions) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`Vector store at ${path} was created with ${this.dimensions} dimensions, opened with ${dimensions}.`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
} else if (dimensions !== void 0) {
|
|
181
|
+
this.dimensions = dimensions;
|
|
182
|
+
this.db.prepare(`INSERT INTO _vec_meta (key, value) VALUES ('dimensions', ?)`).run(String(dimensions));
|
|
183
|
+
} else {
|
|
184
|
+
this.dimensions = -1;
|
|
185
|
+
}
|
|
186
|
+
this.accelerated = !forceJsCosine && this.dimensions >= 0 && tryLoadSqliteVec(this.db);
|
|
187
|
+
this.meta = {
|
|
188
|
+
backend: "sqlite",
|
|
189
|
+
dimensions: Math.max(this.dimensions, 0),
|
|
190
|
+
accelerated: this.accelerated
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
db;
|
|
194
|
+
meta;
|
|
195
|
+
dimensions;
|
|
196
|
+
/** True when sqlite-vec loaded and the vec0 acceleration path is live. */
|
|
197
|
+
accelerated;
|
|
198
|
+
vecTablesEnsured = /* @__PURE__ */ new Set();
|
|
199
|
+
requireDims(v) {
|
|
200
|
+
if (this.dimensions < 0) {
|
|
201
|
+
throw new Error("SqliteAdapter.vector requires `dimensions` \u2014 pass { dimensions } when opening.");
|
|
202
|
+
}
|
|
203
|
+
assertDimensions(v, this.dimensions);
|
|
204
|
+
}
|
|
205
|
+
// ── vec0 acceleration helpers ───────────────────────────────────────────
|
|
206
|
+
vecTableName(collection) {
|
|
207
|
+
return `vectors_vec_${collection.replace(/[^a-zA-Z0-9_]/g, "_")}_${hashName(collection)}`;
|
|
208
|
+
}
|
|
209
|
+
ensureVecTable(collection) {
|
|
210
|
+
const table = this.vecTableName(collection);
|
|
211
|
+
if (this.vecTablesEnsured.has(table)) return table;
|
|
212
|
+
this.db.exec(
|
|
213
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS ${table} USING vec0(embedding float[${this.dimensions}] distance_metric=cosine)`
|
|
214
|
+
);
|
|
215
|
+
this.vecTablesEnsured.add(table);
|
|
216
|
+
const existing = this.db.prepare(`SELECT rowid, vec FROM vectors WHERE collection = ?`).all(collection);
|
|
217
|
+
if (existing.length > 0) {
|
|
218
|
+
const del = this.db.prepare(`DELETE FROM ${table} WHERE rowid = ?`);
|
|
219
|
+
const ins = this.db.prepare(`INSERT INTO ${table}(rowid, embedding) VALUES (?, ?)`);
|
|
220
|
+
const backfill = this.db.transaction(() => {
|
|
221
|
+
for (const r of existing) {
|
|
222
|
+
const rid = BigInt(r.rowid);
|
|
223
|
+
del.run(rid);
|
|
224
|
+
if (isUsableVector(bufferToVector(r.vec))) ins.run(rid, r.vec);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
backfill();
|
|
228
|
+
}
|
|
229
|
+
return table;
|
|
230
|
+
}
|
|
231
|
+
/** Keep a (collection,id)'s vec0 row in sync. vec0 is keyed by the vectors row's
|
|
232
|
+
* rowid (stable under ON CONFLICT DO UPDATE); the rowid binds as BigInt. */
|
|
233
|
+
syncVec(collection, id, vector) {
|
|
234
|
+
const table = this.ensureVecTable(collection);
|
|
235
|
+
const row = this.db.prepare(`SELECT rowid FROM vectors WHERE collection = ? AND id = ?`).get(collection, id);
|
|
236
|
+
if (!row) return;
|
|
237
|
+
const rid = BigInt(row.rowid);
|
|
238
|
+
this.db.prepare(`DELETE FROM ${table} WHERE rowid = ?`).run(rid);
|
|
239
|
+
if (isUsableVector(vector)) {
|
|
240
|
+
this.db.prepare(`INSERT INTO ${table}(rowid, embedding) VALUES (?, ?)`).run(rid, vectorToBuffer(vector));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
upsert(collection, doc) {
|
|
244
|
+
this.requireDims(doc.vector);
|
|
245
|
+
const write = this.db.transaction(() => {
|
|
246
|
+
this.db.prepare(
|
|
247
|
+
`INSERT INTO vectors(collection, id, vec, metadata) VALUES (?, ?, ?, ?)
|
|
248
|
+
ON CONFLICT(collection, id) DO UPDATE SET vec = excluded.vec, metadata = excluded.metadata`
|
|
249
|
+
).run(
|
|
250
|
+
collection,
|
|
251
|
+
doc.id,
|
|
252
|
+
vectorToBuffer(doc.vector),
|
|
253
|
+
doc.metadata === void 0 ? null : JSON.stringify(doc.metadata)
|
|
254
|
+
);
|
|
255
|
+
if (this.accelerated) this.syncVec(collection, doc.id, doc.vector);
|
|
256
|
+
});
|
|
257
|
+
write();
|
|
258
|
+
}
|
|
259
|
+
upsertMany(collection, docs) {
|
|
260
|
+
const tx = this.db.transaction((items) => {
|
|
261
|
+
for (const doc of items) this.upsert(collection, doc);
|
|
262
|
+
});
|
|
263
|
+
tx(docs);
|
|
264
|
+
}
|
|
265
|
+
get(collection, id) {
|
|
266
|
+
const row = this.db.prepare(`SELECT id, vec, metadata FROM vectors WHERE collection = ? AND id = ?`).get(collection, id);
|
|
267
|
+
if (!row) return null;
|
|
268
|
+
return {
|
|
269
|
+
id: row.id,
|
|
270
|
+
vector: bufferToVector(row.vec),
|
|
271
|
+
metadata: row.metadata === null ? void 0 : JSON.parse(row.metadata)
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
remove(collection, id) {
|
|
275
|
+
if (this.accelerated) {
|
|
276
|
+
const row = this.db.prepare(`SELECT rowid FROM vectors WHERE collection = ? AND id = ?`).get(collection, id);
|
|
277
|
+
if (row) {
|
|
278
|
+
this.db.prepare(`DELETE FROM ${this.ensureVecTable(collection)} WHERE rowid = ?`).run(BigInt(row.rowid));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return this.db.prepare(`DELETE FROM vectors WHERE collection = ? AND id = ?`).run(collection, id).changes > 0;
|
|
282
|
+
}
|
|
283
|
+
count(collection) {
|
|
284
|
+
const row = this.db.prepare(`SELECT COUNT(*) AS n FROM vectors WHERE collection = ?`).get(collection);
|
|
285
|
+
return row.n;
|
|
286
|
+
}
|
|
287
|
+
search(collection, query, opts) {
|
|
288
|
+
this.requireDims(query);
|
|
289
|
+
const topK = opts?.topK ?? 10;
|
|
290
|
+
const minScore = opts?.minScore;
|
|
291
|
+
if (this.accelerated && isUsableVector(query)) {
|
|
292
|
+
try {
|
|
293
|
+
return this.searchVec(collection, query, topK, minScore);
|
|
294
|
+
} catch {
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return this.searchJs(collection, query, topK, minScore);
|
|
298
|
+
}
|
|
299
|
+
searchVec(collection, query, topK, minScore) {
|
|
300
|
+
const table = this.ensureVecTable(collection);
|
|
301
|
+
const rows = this.db.prepare(
|
|
302
|
+
`SELECT v.id AS id, v.metadata AS metadata, vv.distance AS distance
|
|
303
|
+
FROM ${table} vv JOIN vectors v ON v.rowid = vv.rowid
|
|
304
|
+
WHERE vv.embedding MATCH ? ORDER BY vv.distance LIMIT ?`
|
|
305
|
+
).all(vectorToBuffer(query), topK);
|
|
306
|
+
const out = [];
|
|
307
|
+
for (const r of rows) {
|
|
308
|
+
if (r.distance === null) continue;
|
|
309
|
+
const score = 1 - r.distance;
|
|
310
|
+
if (!Number.isFinite(score)) continue;
|
|
311
|
+
if (minScore !== void 0 && score < minScore) continue;
|
|
312
|
+
out.push({
|
|
313
|
+
id: r.id,
|
|
314
|
+
score,
|
|
315
|
+
metadata: r.metadata === null ? void 0 : JSON.parse(r.metadata)
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
out.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
searchJs(collection, query, topK, minScore) {
|
|
322
|
+
const rows = this.db.prepare(`SELECT id, vec, metadata FROM vectors WHERE collection = ?`).all(collection);
|
|
323
|
+
const scored = [];
|
|
324
|
+
for (const row of rows) {
|
|
325
|
+
const vec = bufferToVector(row.vec);
|
|
326
|
+
if (!isUsableVector(vec)) continue;
|
|
327
|
+
const score = cosineSimilarity(query, vec);
|
|
328
|
+
if (!Number.isFinite(score)) continue;
|
|
329
|
+
if (minScore !== void 0 && score < minScore) continue;
|
|
330
|
+
scored.push({
|
|
331
|
+
id: row.id,
|
|
332
|
+
score,
|
|
333
|
+
metadata: row.metadata === null ? void 0 : JSON.parse(row.metadata)
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
scored.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
337
|
+
return scored.slice(0, topK);
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
function buildWhereClause(filter) {
|
|
341
|
+
if (!filter?.where || Object.keys(filter.where).length === 0) {
|
|
342
|
+
return { clause: "", params: [] };
|
|
343
|
+
}
|
|
344
|
+
const conditions = [];
|
|
345
|
+
const params = [];
|
|
346
|
+
for (const [key, value] of Object.entries(filter.where)) {
|
|
347
|
+
conditions.push(`json_extract(data, '$.' || ?) = ?`);
|
|
348
|
+
const bound = typeof value === "boolean" ? value ? 1 : 0 : value;
|
|
349
|
+
params.push(key, bound);
|
|
350
|
+
}
|
|
351
|
+
return { clause: ` WHERE ${conditions.join(" AND ")}`, params };
|
|
352
|
+
}
|
|
353
|
+
function buildOrderBy(filter) {
|
|
354
|
+
if (!filter?.sortBy) return { clause: "", params: [] };
|
|
355
|
+
const dir = filter.sortDir === "desc" ? "DESC" : "ASC";
|
|
356
|
+
return {
|
|
357
|
+
clause: ` ORDER BY json_extract(data, '$.' || ?) IS NULL, json_extract(data, '$.' || ?) ${dir}`,
|
|
358
|
+
params: [filter.sortBy, filter.sortBy]
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
function hashName(s) {
|
|
362
|
+
let h = 2166136261;
|
|
363
|
+
for (let i = 0; i < s.length; i++) {
|
|
364
|
+
h ^= s.charCodeAt(i);
|
|
365
|
+
h = Math.imul(h, 16777619);
|
|
366
|
+
}
|
|
367
|
+
return (h >>> 0).toString(36);
|
|
368
|
+
}
|
|
369
|
+
function buildLimitOffset(filter) {
|
|
370
|
+
let sql = "";
|
|
371
|
+
if (filter?.limit !== void 0) {
|
|
372
|
+
sql += ` LIMIT ${Math.max(0, Math.floor(filter.limit))}`;
|
|
373
|
+
}
|
|
374
|
+
if (filter?.offset !== void 0 && filter.offset > 0) {
|
|
375
|
+
if (!sql.includes("LIMIT")) sql += " LIMIT -1";
|
|
376
|
+
sql += ` OFFSET ${Math.max(0, Math.floor(filter.offset))}`;
|
|
377
|
+
}
|
|
378
|
+
return sql;
|
|
379
|
+
}
|
|
380
|
+
export {
|
|
381
|
+
SqliteAdapter
|
|
382
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// src/vector/cosine.ts
|
|
2
|
+
function cosineSimilarity(a, b) {
|
|
3
|
+
if (a.length !== b.length) return 0;
|
|
4
|
+
let dot = 0;
|
|
5
|
+
let an = 0;
|
|
6
|
+
let bn = 0;
|
|
7
|
+
for (let i = 0; i < a.length; i++) {
|
|
8
|
+
const av = a[i] ?? 0;
|
|
9
|
+
const bv = b[i] ?? 0;
|
|
10
|
+
dot += av * bv;
|
|
11
|
+
an += av * av;
|
|
12
|
+
bn += bv * bv;
|
|
13
|
+
}
|
|
14
|
+
if (an === 0 || bn === 0) return 0;
|
|
15
|
+
return dot / (Math.sqrt(an) * Math.sqrt(bn));
|
|
16
|
+
}
|
|
17
|
+
function vectorToBuffer(vec) {
|
|
18
|
+
const buf = Buffer.allocUnsafe(vec.length * 4);
|
|
19
|
+
for (let i = 0; i < vec.length; i++) {
|
|
20
|
+
buf.writeFloatLE(vec[i] ?? 0, i * 4);
|
|
21
|
+
}
|
|
22
|
+
return buf;
|
|
23
|
+
}
|
|
24
|
+
function bufferToVector(buf) {
|
|
25
|
+
const b = buf instanceof Buffer ? buf : Buffer.from(buf);
|
|
26
|
+
const out = new Float32Array(Math.floor(b.byteLength / 4));
|
|
27
|
+
for (let i = 0; i < out.length; i++) {
|
|
28
|
+
out[i] = b.readFloatLE(i * 4);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
function assertDimensions(vector, dimensions) {
|
|
33
|
+
if (vector.length !== dimensions) {
|
|
34
|
+
throw new Error(`Vector dimension mismatch: expected ${dimensions}, got ${vector.length}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export {
|
|
39
|
+
cosineSimilarity,
|
|
40
|
+
vectorToBuffer,
|
|
41
|
+
bufferToVector,
|
|
42
|
+
assertDimensions
|
|
43
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertDimensions,
|
|
3
|
+
cosineSimilarity
|
|
4
|
+
} from "./chunk-GC4MYP45.js";
|
|
5
|
+
|
|
6
|
+
// src/vector/memory.ts
|
|
7
|
+
var InMemoryVectorStore = class {
|
|
8
|
+
meta;
|
|
9
|
+
dimensions;
|
|
10
|
+
collections = /* @__PURE__ */ new Map();
|
|
11
|
+
constructor(opts) {
|
|
12
|
+
this.dimensions = opts.dimensions;
|
|
13
|
+
this.meta = { backend: "memory", dimensions: opts.dimensions, accelerated: false };
|
|
14
|
+
}
|
|
15
|
+
upsert(collection, doc) {
|
|
16
|
+
assertDimensions(doc.vector, this.dimensions);
|
|
17
|
+
this.collectionFor(collection).set(doc.id, doc);
|
|
18
|
+
}
|
|
19
|
+
upsertMany(collection, docs) {
|
|
20
|
+
for (const doc of docs) assertDimensions(doc.vector, this.dimensions);
|
|
21
|
+
const coll = this.collectionFor(collection);
|
|
22
|
+
for (const doc of docs) coll.set(doc.id, doc);
|
|
23
|
+
}
|
|
24
|
+
get(collection, id) {
|
|
25
|
+
const doc = this.collections.get(collection)?.get(id);
|
|
26
|
+
return doc ?? null;
|
|
27
|
+
}
|
|
28
|
+
remove(collection, id) {
|
|
29
|
+
return this.collections.get(collection)?.delete(id) ?? false;
|
|
30
|
+
}
|
|
31
|
+
count(collection) {
|
|
32
|
+
return this.collections.get(collection)?.size ?? 0;
|
|
33
|
+
}
|
|
34
|
+
search(collection, query, opts) {
|
|
35
|
+
assertDimensions(query, this.dimensions);
|
|
36
|
+
const topK = opts?.topK ?? 10;
|
|
37
|
+
const minScore = opts?.minScore;
|
|
38
|
+
const coll = this.collections.get(collection);
|
|
39
|
+
if (!coll) return [];
|
|
40
|
+
const scored = [];
|
|
41
|
+
for (const doc of coll.values()) {
|
|
42
|
+
const score = cosineSimilarity(query, doc.vector);
|
|
43
|
+
if (!Number.isFinite(score)) continue;
|
|
44
|
+
if (minScore !== void 0 && score < minScore) continue;
|
|
45
|
+
scored.push({ id: doc.id, score, metadata: doc.metadata });
|
|
46
|
+
}
|
|
47
|
+
scored.sort((a, b) => b.score - a.score);
|
|
48
|
+
return scored.slice(0, topK);
|
|
49
|
+
}
|
|
50
|
+
collectionFor(name) {
|
|
51
|
+
let coll = this.collections.get(name);
|
|
52
|
+
if (!coll) {
|
|
53
|
+
coll = /* @__PURE__ */ new Map();
|
|
54
|
+
this.collections.set(name, coll);
|
|
55
|
+
}
|
|
56
|
+
return coll;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export {
|
|
61
|
+
InMemoryVectorStore
|
|
62
|
+
};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// src/to-async.ts
|
|
2
|
+
var AsyncStoreAdapter = class {
|
|
3
|
+
constructor(sync) {
|
|
4
|
+
this.sync = sync;
|
|
5
|
+
}
|
|
6
|
+
sync;
|
|
7
|
+
get meta() {
|
|
8
|
+
return this.sync.meta;
|
|
9
|
+
}
|
|
10
|
+
async get(key) {
|
|
11
|
+
return this.sync.get(key);
|
|
12
|
+
}
|
|
13
|
+
async set(key, value) {
|
|
14
|
+
this.sync.set(key, value);
|
|
15
|
+
}
|
|
16
|
+
async has(key) {
|
|
17
|
+
return this.sync.has(key);
|
|
18
|
+
}
|
|
19
|
+
async delete(key) {
|
|
20
|
+
return this.sync.delete(key);
|
|
21
|
+
}
|
|
22
|
+
async keys(prefix) {
|
|
23
|
+
return this.sync.keys(prefix);
|
|
24
|
+
}
|
|
25
|
+
async list(collection, filter) {
|
|
26
|
+
return this.sync.list(collection, filter);
|
|
27
|
+
}
|
|
28
|
+
async getById(collection, id) {
|
|
29
|
+
return this.sync.getById(collection, id);
|
|
30
|
+
}
|
|
31
|
+
async put(collection, item) {
|
|
32
|
+
return this.sync.put(collection, item);
|
|
33
|
+
}
|
|
34
|
+
async remove(collection, id) {
|
|
35
|
+
return this.sync.remove(collection, id);
|
|
36
|
+
}
|
|
37
|
+
async count(collection, filter) {
|
|
38
|
+
return this.sync.count(collection, filter);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
function toAsync(store) {
|
|
42
|
+
return new AsyncStoreAdapter(store);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/backends/memory.ts
|
|
46
|
+
var InMemoryStore = class {
|
|
47
|
+
meta = {
|
|
48
|
+
backend: "memory"
|
|
49
|
+
};
|
|
50
|
+
/** Key-value storage. */
|
|
51
|
+
kv = /* @__PURE__ */ new Map();
|
|
52
|
+
/** Collection storage: collection name -> Map of id -> item. */
|
|
53
|
+
collections = /* @__PURE__ */ new Map();
|
|
54
|
+
// ── Key-Value ──────────────────────────────────────────────────────
|
|
55
|
+
get(key) {
|
|
56
|
+
const value = this.kv.get(key);
|
|
57
|
+
return value !== void 0 ? value : null;
|
|
58
|
+
}
|
|
59
|
+
set(key, value) {
|
|
60
|
+
this.kv.set(key, value);
|
|
61
|
+
}
|
|
62
|
+
has(key) {
|
|
63
|
+
return this.kv.has(key);
|
|
64
|
+
}
|
|
65
|
+
delete(key) {
|
|
66
|
+
return this.kv.delete(key);
|
|
67
|
+
}
|
|
68
|
+
keys(prefix) {
|
|
69
|
+
const allKeys = [...this.kv.keys()];
|
|
70
|
+
if (!prefix) return allKeys;
|
|
71
|
+
return allKeys.filter((k) => k.startsWith(prefix));
|
|
72
|
+
}
|
|
73
|
+
// ── Collections ────────────────────────────────────────────────────
|
|
74
|
+
ensureCollection(name) {
|
|
75
|
+
let col = this.collections.get(name);
|
|
76
|
+
if (!col) {
|
|
77
|
+
col = /* @__PURE__ */ new Map();
|
|
78
|
+
this.collections.set(name, col);
|
|
79
|
+
}
|
|
80
|
+
return col;
|
|
81
|
+
}
|
|
82
|
+
list(collection, filter) {
|
|
83
|
+
const col = this.ensureCollection(collection);
|
|
84
|
+
let items = [...col.values()];
|
|
85
|
+
items = applyFilter(items, filter);
|
|
86
|
+
return items;
|
|
87
|
+
}
|
|
88
|
+
getById(collection, id) {
|
|
89
|
+
const col = this.ensureCollection(collection);
|
|
90
|
+
const item = col.get(id);
|
|
91
|
+
return item !== void 0 ? item : null;
|
|
92
|
+
}
|
|
93
|
+
put(collection, item) {
|
|
94
|
+
const col = this.ensureCollection(collection);
|
|
95
|
+
col.set(item.id, item);
|
|
96
|
+
return item;
|
|
97
|
+
}
|
|
98
|
+
remove(collection, id) {
|
|
99
|
+
const col = this.ensureCollection(collection);
|
|
100
|
+
return col.delete(id);
|
|
101
|
+
}
|
|
102
|
+
count(collection, filter) {
|
|
103
|
+
const col = this.ensureCollection(collection);
|
|
104
|
+
if (!filter?.where) return col.size;
|
|
105
|
+
const items = [...col.values()];
|
|
106
|
+
return applyFilter(items, filter).length;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
function matchesWhere(item, where) {
|
|
110
|
+
if (typeof item !== "object" || item === null) return false;
|
|
111
|
+
const record = item;
|
|
112
|
+
for (const [key, value] of Object.entries(where)) {
|
|
113
|
+
if (record[key] !== value) return false;
|
|
114
|
+
}
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
function applyFilter(items, filter) {
|
|
118
|
+
if (!filter) return items;
|
|
119
|
+
let result = items;
|
|
120
|
+
if (filter.where) {
|
|
121
|
+
const where = filter.where;
|
|
122
|
+
result = result.filter((item) => matchesWhere(item, where));
|
|
123
|
+
}
|
|
124
|
+
if (filter.sortBy) {
|
|
125
|
+
const field = filter.sortBy;
|
|
126
|
+
const dir = filter.sortDir === "desc" ? -1 : 1;
|
|
127
|
+
result = [...result].sort((a, b) => {
|
|
128
|
+
const aVal = a[field];
|
|
129
|
+
const bVal = b[field];
|
|
130
|
+
if (aVal === bVal) return 0;
|
|
131
|
+
if (aVal === void 0 || aVal === null) return 1;
|
|
132
|
+
if (bVal === void 0 || bVal === null) return -1;
|
|
133
|
+
return aVal < bVal ? -1 * dir : 1 * dir;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (filter.offset !== void 0 && filter.offset > 0) {
|
|
137
|
+
result = result.slice(filter.offset);
|
|
138
|
+
}
|
|
139
|
+
if (filter.limit !== void 0 && filter.limit >= 0) {
|
|
140
|
+
result = result.slice(0, filter.limit);
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export {
|
|
146
|
+
toAsync,
|
|
147
|
+
InMemoryStore
|
|
148
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { A as AsyncStore, S as StoreFilter, a as StoreMeta, b as SyncStore } from './types-DyQLNtxa.js';
|
|
2
|
+
export { InMemoryKv, toAsync } from './kv.js';
|
|
3
|
+
export { V as Vector, a as VectorDocument, b as VectorSearchOptions, c as VectorSearchResult, d as VectorStore, e as VectorStoreMeta } from './types-BqSZEMAB.js';
|
|
4
|
+
export { InMemoryVectorStore, assertDimensions, bufferToVector, cosineSimilarity, vectorToBuffer } from './vector.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InMemoryStore,
|
|
3
|
+
toAsync
|
|
4
|
+
} from "./chunk-ZI4JA6IU.js";
|
|
5
|
+
import {
|
|
6
|
+
InMemoryVectorStore
|
|
7
|
+
} from "./chunk-ZFSKQHBT.js";
|
|
8
|
+
import {
|
|
9
|
+
assertDimensions,
|
|
10
|
+
bufferToVector,
|
|
11
|
+
cosineSimilarity,
|
|
12
|
+
vectorToBuffer
|
|
13
|
+
} from "./chunk-GC4MYP45.js";
|
|
14
|
+
export {
|
|
15
|
+
InMemoryStore as InMemoryKv,
|
|
16
|
+
InMemoryVectorStore,
|
|
17
|
+
assertDimensions,
|
|
18
|
+
bufferToVector,
|
|
19
|
+
cosineSimilarity,
|
|
20
|
+
toAsync,
|
|
21
|
+
vectorToBuffer
|
|
22
|
+
};
|
package/dist/kv.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { b as SyncStore, A as AsyncStore, a as StoreMeta, S as StoreFilter } from './types-DyQLNtxa.js';
|
|
2
|
+
|
|
3
|
+
/** Lift a synchronous store to the {@link AsyncStore} interface. The bridge only
|
|
4
|
+
* goes this direction — sync ⊂ async. */
|
|
5
|
+
declare function toAsync(store: SyncStore): AsyncStore;
|
|
6
|
+
|
|
7
|
+
declare class InMemoryStore implements SyncStore {
|
|
8
|
+
readonly meta: StoreMeta;
|
|
9
|
+
/** Key-value storage. */
|
|
10
|
+
private kv;
|
|
11
|
+
/** Collection storage: collection name -> Map of id -> item. */
|
|
12
|
+
private collections;
|
|
13
|
+
get<T>(key: string): T | null;
|
|
14
|
+
set<T>(key: string, value: T): void;
|
|
15
|
+
has(key: string): boolean;
|
|
16
|
+
delete(key: string): boolean;
|
|
17
|
+
keys(prefix?: string): string[];
|
|
18
|
+
private ensureCollection;
|
|
19
|
+
list<T>(collection: string, filter?: StoreFilter): T[];
|
|
20
|
+
getById<T>(collection: string, id: string): T | null;
|
|
21
|
+
put<T extends {
|
|
22
|
+
id: string;
|
|
23
|
+
}>(collection: string, item: T): T;
|
|
24
|
+
remove(collection: string, id: string): boolean;
|
|
25
|
+
count(collection: string, filter?: StoreFilter): number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export { AsyncStore, InMemoryStore as InMemoryKv, StoreFilter, StoreMeta, SyncStore, toAsync };
|
package/dist/kv.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** An embedding. Float32Array — compact, and the on-disk encoding is little-endian
|
|
2
|
+
* float32 so vectors stay portable across backends. */
|
|
3
|
+
type Vector = Float32Array;
|
|
4
|
+
interface VectorStoreMeta {
|
|
5
|
+
/** Backend identifier (e.g. "memory", "sqlite"). */
|
|
6
|
+
backend: string;
|
|
7
|
+
/** Embedding dimensions this store is configured for. */
|
|
8
|
+
dimensions: number;
|
|
9
|
+
/** True when a native acceleration path (sqlite-vec) is active; false when the
|
|
10
|
+
* store does exact JS-side cosine search. Informational — results are the same
|
|
11
|
+
* ranking either way, only the speed differs. */
|
|
12
|
+
accelerated: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface VectorDocument<M extends Record<string, unknown> = Record<string, unknown>> {
|
|
15
|
+
/** Unique id within the collection. */
|
|
16
|
+
id: string;
|
|
17
|
+
/** The embedding. Length must equal the store's configured dimensions. */
|
|
18
|
+
vector: Vector;
|
|
19
|
+
/** Typed context stored alongside the vector. Persisted as JSON by disk-backed
|
|
20
|
+
* backends, so it must be JSON-serializable; values JSON can't represent
|
|
21
|
+
* (`undefined`, functions) are dropped on persistence — don't rely on them. */
|
|
22
|
+
metadata?: M;
|
|
23
|
+
}
|
|
24
|
+
interface VectorSearchResult<M extends Record<string, unknown> = Record<string, unknown>> {
|
|
25
|
+
id: string;
|
|
26
|
+
/** Cosine similarity in [-1, 1]. Higher is more similar. */
|
|
27
|
+
score: number;
|
|
28
|
+
metadata?: M;
|
|
29
|
+
}
|
|
30
|
+
interface VectorSearchOptions {
|
|
31
|
+
/** Maximum results to return. Default: 10. */
|
|
32
|
+
topK?: number;
|
|
33
|
+
/** Minimum cosine similarity; results below are excluded. Default: no floor. */
|
|
34
|
+
minScore?: number;
|
|
35
|
+
}
|
|
36
|
+
/** A synchronous vector similarity store with per-collection documents.
|
|
37
|
+
*
|
|
38
|
+
* All operations are synchronous. Construction may be async for backends that
|
|
39
|
+
* load native bindings (see each backend's static `open`); once opened, every
|
|
40
|
+
* call is pure sync. */
|
|
41
|
+
interface VectorStore {
|
|
42
|
+
readonly meta: VectorStoreMeta;
|
|
43
|
+
/** Insert or replace a document by (collection, id). Throws on dimension mismatch. */
|
|
44
|
+
upsert<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, doc: VectorDocument<M>): void;
|
|
45
|
+
/** Insert or replace many documents in one collection. */
|
|
46
|
+
upsertMany<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, docs: ReadonlyArray<VectorDocument<M>>): void;
|
|
47
|
+
/** Fetch a document by id, or null. */
|
|
48
|
+
get<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, id: string): VectorDocument<M> | null;
|
|
49
|
+
/** Remove a document by id. Returns true if it existed. */
|
|
50
|
+
remove(collection: string, id: string): boolean;
|
|
51
|
+
/** Number of documents in a collection. */
|
|
52
|
+
count(collection: string): number;
|
|
53
|
+
/** k-nearest-neighbour search by cosine similarity, highest score first. */
|
|
54
|
+
search<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, query: Vector, opts?: VectorSearchOptions): VectorSearchResult<M>[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type { Vector as V, VectorDocument as a, VectorSearchOptions as b, VectorSearchResult as c, VectorStore as d, VectorStoreMeta as e };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metadata about a store instance.
|
|
3
|
+
*/
|
|
4
|
+
interface StoreMeta {
|
|
5
|
+
/** Backend identifier (e.g., "memory", "sqlite", "surrealdb"). */
|
|
6
|
+
backend: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Structured filter for collection queries.
|
|
10
|
+
*/
|
|
11
|
+
interface StoreFilter {
|
|
12
|
+
/** Exact match on fields within the stored item. */
|
|
13
|
+
where?: Record<string, unknown>;
|
|
14
|
+
/** Field to sort by. */
|
|
15
|
+
sortBy?: string;
|
|
16
|
+
/** Sort direction. Default: 'asc'. */
|
|
17
|
+
sortDir?: 'asc' | 'desc';
|
|
18
|
+
/** Maximum number of results. */
|
|
19
|
+
limit?: number;
|
|
20
|
+
/** Number of results to skip. */
|
|
21
|
+
offset?: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A typed key-value + collection store. **Synchronous.**
|
|
25
|
+
*
|
|
26
|
+
* Embedded backends (in-memory, sqlite) implement this directly — better-sqlite3
|
|
27
|
+
* is synchronous, so wrapping it in Promises buys nothing and forecloses sync
|
|
28
|
+
* consumers. A SyncStore can always be lifted to {@link AsyncStore} via
|
|
29
|
+
* {@link toAsync}; the reverse is impossible (you can't block on a network call),
|
|
30
|
+
* which is exactly why sync is the base interface and async is derived from it.
|
|
31
|
+
*/
|
|
32
|
+
interface SyncStore {
|
|
33
|
+
readonly meta: StoreMeta;
|
|
34
|
+
/** Get a value by key. Returns null if not found. */
|
|
35
|
+
get<T>(key: string): T | null;
|
|
36
|
+
/** Set a value by key. Overwrites if exists. */
|
|
37
|
+
set<T>(key: string, value: T): void;
|
|
38
|
+
/** Check if a key exists. */
|
|
39
|
+
has(key: string): boolean;
|
|
40
|
+
/** Delete a key. Returns true if the key existed. */
|
|
41
|
+
delete(key: string): boolean;
|
|
42
|
+
/** List all keys, optionally filtered by prefix. */
|
|
43
|
+
keys(prefix?: string): string[];
|
|
44
|
+
/** Get all items in a collection, with optional filter. */
|
|
45
|
+
list<T>(collection: string, filter?: StoreFilter): T[];
|
|
46
|
+
/** Get a single item by ID within a collection. */
|
|
47
|
+
getById<T>(collection: string, id: string): T | null;
|
|
48
|
+
/** Create or update an item in a collection. */
|
|
49
|
+
put<T extends {
|
|
50
|
+
id: string;
|
|
51
|
+
}>(collection: string, item: T): T;
|
|
52
|
+
/** Remove an item from a collection by ID. Returns true if it existed. */
|
|
53
|
+
remove(collection: string, id: string): boolean;
|
|
54
|
+
/** Count items in a collection, with optional filter. */
|
|
55
|
+
count(collection: string, filter?: StoreFilter): number;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The async face of the same store. **Remote** backends (a future SurrealDB / HTTP
|
|
59
|
+
* store) implement this natively; embedded sync backends reach it via
|
|
60
|
+
* {@link toAsync}.
|
|
61
|
+
*
|
|
62
|
+
* Hand-written rather than derived from SyncStore via a mapped type, because a
|
|
63
|
+
* mapped type cannot preserve the per-method generics (`get<T>`, `list<T>`, …) —
|
|
64
|
+
* `infer` collapses them to `unknown`. The duplication is the price of keeping
|
|
65
|
+
* the async side fully typed.
|
|
66
|
+
*/
|
|
67
|
+
interface AsyncStore {
|
|
68
|
+
readonly meta: StoreMeta;
|
|
69
|
+
get<T>(key: string): Promise<T | null>;
|
|
70
|
+
set<T>(key: string, value: T): Promise<void>;
|
|
71
|
+
has(key: string): Promise<boolean>;
|
|
72
|
+
delete(key: string): Promise<boolean>;
|
|
73
|
+
keys(prefix?: string): Promise<string[]>;
|
|
74
|
+
list<T>(collection: string, filter?: StoreFilter): Promise<T[]>;
|
|
75
|
+
getById<T>(collection: string, id: string): Promise<T | null>;
|
|
76
|
+
put<T extends {
|
|
77
|
+
id: string;
|
|
78
|
+
}>(collection: string, item: T): Promise<T>;
|
|
79
|
+
remove(collection: string, id: string): Promise<boolean>;
|
|
80
|
+
count(collection: string, filter?: StoreFilter): Promise<number>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type { AsyncStore as A, StoreFilter as S, StoreMeta as a, SyncStore as b };
|
package/dist/vector.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { V as Vector, d as VectorStore, e as VectorStoreMeta, a as VectorDocument, b as VectorSearchOptions, c as VectorSearchResult } from './types-BqSZEMAB.js';
|
|
2
|
+
|
|
3
|
+
/** Cosine similarity in [-1, 1]. Exact. Shared by the in-memory backend and the
|
|
4
|
+
* sqlite backend's search path. Returns 0 for length mismatch or a zero vector
|
|
5
|
+
* (undefined direction). */
|
|
6
|
+
declare function cosineSimilarity(a: Vector, b: Vector): number;
|
|
7
|
+
/** Encode a vector as a little-endian float32 BLOB. Writes explicit LE (matching
|
|
8
|
+
* bufferToVector's readFloatLE), so it is portable across host byte order — and
|
|
9
|
+
* into a fresh buffer, so the result never aliases the source's backing memory. */
|
|
10
|
+
declare function vectorToBuffer(vec: Vector): Buffer;
|
|
11
|
+
/** Inverse of vectorToBuffer. */
|
|
12
|
+
declare function bufferToVector(buf: Buffer | Uint8Array): Vector;
|
|
13
|
+
/** Throw if a vector's length doesn't match the store's configured dimensions.
|
|
14
|
+
* Shared by every backend so the check and its message live in one place. */
|
|
15
|
+
declare function assertDimensions(vector: Vector, dimensions: number): void;
|
|
16
|
+
|
|
17
|
+
interface InMemoryVectorStoreOptions {
|
|
18
|
+
/** Embedding dimensions. All vectors must match this length. */
|
|
19
|
+
dimensions: number;
|
|
20
|
+
}
|
|
21
|
+
declare class InMemoryVectorStore implements VectorStore {
|
|
22
|
+
readonly meta: VectorStoreMeta;
|
|
23
|
+
private readonly dimensions;
|
|
24
|
+
private readonly collections;
|
|
25
|
+
constructor(opts: InMemoryVectorStoreOptions);
|
|
26
|
+
upsert<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, doc: VectorDocument<M>): void;
|
|
27
|
+
upsertMany<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, docs: ReadonlyArray<VectorDocument<M>>): void;
|
|
28
|
+
get<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, id: string): VectorDocument<M> | null;
|
|
29
|
+
remove(collection: string, id: string): boolean;
|
|
30
|
+
count(collection: string): number;
|
|
31
|
+
search<M extends Record<string, unknown> = Record<string, unknown>>(collection: string, query: Vector, opts?: VectorSearchOptions): VectorSearchResult<M>[];
|
|
32
|
+
private collectionFor;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { InMemoryVectorStore, Vector, VectorDocument, VectorSearchOptions, VectorSearchResult, VectorStore, VectorStoreMeta, assertDimensions, bufferToVector, cosineSimilarity, vectorToBuffer };
|
package/dist/vector.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InMemoryVectorStore
|
|
3
|
+
} from "./chunk-ZFSKQHBT.js";
|
|
4
|
+
import {
|
|
5
|
+
assertDimensions,
|
|
6
|
+
bufferToVector,
|
|
7
|
+
cosineSimilarity,
|
|
8
|
+
vectorToBuffer
|
|
9
|
+
} from "./chunk-GC4MYP45.js";
|
|
10
|
+
export {
|
|
11
|
+
InMemoryVectorStore,
|
|
12
|
+
assertDimensions,
|
|
13
|
+
bufferToVector,
|
|
14
|
+
cosineSimilarity,
|
|
15
|
+
vectorToBuffer
|
|
16
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mirk/store",
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Code-split storage ports + source adapters under one namespace. KV + collection store and vector similarity store as interface subpaths; the sqlite source-adapter implements both over one connection.",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"author": "David Robinson <dr@monetise.io>",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"storage",
|
|
10
|
+
"key-value",
|
|
11
|
+
"collection-store",
|
|
12
|
+
"vector",
|
|
13
|
+
"vector-search",
|
|
14
|
+
"similarity",
|
|
15
|
+
"cosine",
|
|
16
|
+
"sqlite",
|
|
17
|
+
"sqlite-vec",
|
|
18
|
+
"embeddings"
|
|
19
|
+
],
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/nightwork-dev/mirk.git",
|
|
23
|
+
"directory": "packages/store"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/nightwork-dev/mirk/tree/main/packages/store#readme",
|
|
26
|
+
"bugs": "https://github.com/nightwork-dev/mirk/issues",
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"import": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts"
|
|
32
|
+
},
|
|
33
|
+
"./kv": {
|
|
34
|
+
"import": "./dist/kv.js",
|
|
35
|
+
"types": "./dist/kv.d.ts"
|
|
36
|
+
},
|
|
37
|
+
"./vector": {
|
|
38
|
+
"import": "./dist/vector.js",
|
|
39
|
+
"types": "./dist/vector.d.ts"
|
|
40
|
+
},
|
|
41
|
+
"./sqlite": {
|
|
42
|
+
"import": "./dist/adapters/sqlite.js",
|
|
43
|
+
"types": "./dist/adapters/sqlite.d.ts"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist"
|
|
48
|
+
],
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"better-sqlite3": "^11.0.0 || ^12.0.0",
|
|
51
|
+
"sqlite-vec": "^0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"better-sqlite3": {
|
|
55
|
+
"optional": true
|
|
56
|
+
},
|
|
57
|
+
"sqlite-vec": {
|
|
58
|
+
"optional": true
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@types/better-sqlite3": "^7.6.0",
|
|
63
|
+
"better-sqlite3": "^11.0.0",
|
|
64
|
+
"sqlite-vec": "0.1.9",
|
|
65
|
+
"typescript": "^5.7.0",
|
|
66
|
+
"vitest": "^3.0.0",
|
|
67
|
+
"tsup": "^8.0.0"
|
|
68
|
+
},
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"registry": "https://registry.npmjs.org",
|
|
71
|
+
"access": "public"
|
|
72
|
+
},
|
|
73
|
+
"scripts": {
|
|
74
|
+
"test": "vitest run",
|
|
75
|
+
"test:watch": "vitest",
|
|
76
|
+
"typecheck": "tsc --noEmit",
|
|
77
|
+
"build": "rm -rf dist && tsup src/index.ts src/kv.ts src/vector.ts src/adapters/sqlite.ts --format esm --dts --external better-sqlite3 --external sqlite-vec"
|
|
78
|
+
},
|
|
79
|
+
"types": "./dist/index.d.ts"
|
|
80
|
+
}
|