@midsummer-ai/sdk 0.1.0-staging.3121 → 0.1.0-staging.3127
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/ai/contract.mjs +39 -0
- package/ai/index.d.mts +70 -12
- package/ai/index.mjs +74 -5
- package/ai/stand-in.mjs +26 -4
- package/client.d.mts +1 -1
- package/client.mjs +1 -105
- package/{connection-Cu2GSOaR.mjs → connection-C_JSWUrt.mjs} +7 -6
- package/contract.d.mts +1 -1
- package/contract.mjs +1 -1
- package/database/client.d.mts +20 -1
- package/database/client.mjs +31 -8
- package/database/stand-in.d.mts +2 -2
- package/database/stand-in.mjs +1 -1
- package/email/client.mjs +1 -130
- package/email/contract.mjs +1 -1
- package/email/index.d.mts +9 -7
- package/email/index.mjs +1 -58
- package/email/smtp.mjs +1 -2
- package/email/stand-in.mjs +1 -1
- package/email-DXtpr7pT.mjs +214 -0
- package/here-CeqGJW21.mjs +28 -0
- package/{index-DNNXNny7.d.mts → index-B9zs0wIp.d.mts} +6 -1
- package/{index-sgdyoA2P.d.mts → index-Ci6mGXqz.d.mts} +7 -1
- package/index.d.mts +2 -2
- package/index.mjs +3 -137
- package/package.json +1 -1
- package/queues/index.d.mts +17 -5
- package/queues/index.mjs +71 -1
- package/s3.d.mts +1 -1
- package/s3.mjs +1 -1
- package/socket.d.mts +1 -1
- package/socket.mjs +1 -262
- package/src-BKrQAqJN.mjs +519 -0
- package/stand-in.d.mts +1 -1
- package/{store-lIZ5GxVv.mjs → store-CsBhnabU.mjs} +1 -1
- package/{tabs-zCh8kceo.mjs → tabs-gHJHkhm2.mjs} +1 -1
- package/vector/contract.d.mts +1 -1
- package/vector/contract.mjs +1 -1
- package/vector/index.d.mts +2 -2
- package/vector/index.mjs +18 -7
- package/vector/stand-in.d.mts +1 -1
- package/vector/stand-in.mjs +1 -1
- package/vector/wire.d.mts +1 -1
- package/vector/wire.mjs +1 -339
- package/wire-BdNDzlIN.mjs +554 -0
- package/wire.d.mts +1 -1
- package/schema-CTHQMRsW.mjs +0 -217
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/vector/errors.ts
|
|
3
|
+
const vectorErrorCodes = [
|
|
4
|
+
"invalid",
|
|
5
|
+
"not_found",
|
|
6
|
+
"conflict",
|
|
7
|
+
"forbidden",
|
|
8
|
+
"unavailable"
|
|
9
|
+
];
|
|
10
|
+
var VectorError = class extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, why) {
|
|
13
|
+
super(why);
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.name = "VectorError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/vector/schema.ts
|
|
20
|
+
/**
|
|
21
|
+
* What Vector DB accepts, as zod schemas: the client checks a call with them before it leaves the
|
|
22
|
+
* caller, and `serve` checks every frame with them again, because a frame comes from the network.
|
|
23
|
+
* A limit lives here once, so both edges hold the same one.
|
|
24
|
+
*/
|
|
25
|
+
/** Most numbers a Vector holds. */
|
|
26
|
+
const MAX_DIMENSION = 4096;
|
|
27
|
+
/** Most Vectors one upsert takes, and most ids one fetch or delete names. */
|
|
28
|
+
const MAX_BATCH = 1e3;
|
|
29
|
+
/** The most matches one query returns. */
|
|
30
|
+
const MAX_TOP_K = 100;
|
|
31
|
+
/** Most characters a text to embed has. */
|
|
32
|
+
const MAX_TEXT = 3e4;
|
|
33
|
+
/** Most bytes a Vector's metadata takes, as JSON. */
|
|
34
|
+
const MAX_METADATA_BYTES = 10240;
|
|
35
|
+
/** Most searches one `multiQuery` asks. */
|
|
36
|
+
const MAX_QUERIES = 16;
|
|
37
|
+
/** Most metadata fields a namespace keeps full text. */
|
|
38
|
+
const MAX_FULL_TEXT = 16;
|
|
39
|
+
/** 1 to 63 lowercase letters, digits and hyphens, starting with a letter or digit. */
|
|
40
|
+
const NamespaceName = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "a Vector namespace's name is 1 to 63 lowercase letters, digits and hyphens, starting with a letter or digit");
|
|
41
|
+
/** How closeness is measured, fixed when a Vector namespace is made. */
|
|
42
|
+
const Metric = z.enum([
|
|
43
|
+
"cosine",
|
|
44
|
+
"euclidean",
|
|
45
|
+
"dot"
|
|
46
|
+
]);
|
|
47
|
+
const Dimension = z.number().int().min(1).max(MAX_DIMENSION);
|
|
48
|
+
const VectorId = z.string().min(1).max(512);
|
|
49
|
+
const Finite = z.number().refine(Number.isFinite, "a number in metadata is finite");
|
|
50
|
+
const Scalar = z.union([
|
|
51
|
+
z.string().max(2048),
|
|
52
|
+
Finite,
|
|
53
|
+
z.boolean()
|
|
54
|
+
]);
|
|
55
|
+
const FieldName = z.string().min(1).max(64).refine((name) => !name.startsWith("$") && !name.includes("."), "a metadata field's name does not start with $ or hold a dot");
|
|
56
|
+
/** An array value: up to 100 strings and numbers. */
|
|
57
|
+
const List_ = z.array(z.union([z.string().max(2048), Finite])).max(100);
|
|
58
|
+
const Metadata = z.record(FieldName, z.union([Scalar, List_])).refine((metadata) => new TextEncoder().encode(JSON.stringify(metadata)).length <= MAX_METADATA_BYTES, `metadata is at most ${MAX_METADATA_BYTES} bytes as JSON`);
|
|
59
|
+
/**
|
|
60
|
+
* The largest value a Vector holds. Engines keep values and scores as 32-bit floats, and within it
|
|
61
|
+
* every score of 4,096 values is one, finite: a squared distance is at most 4,096 · (2e17)², about
|
|
62
|
+
* 1.6e38, under a 32-bit float's 3.4e38. Scores are exact to a 32-bit float's precision for values
|
|
63
|
+
* from 1e-17 up.
|
|
64
|
+
*/
|
|
65
|
+
const MAX_VALUE = 0x16345785d8a0000;
|
|
66
|
+
const Values = z.array(z.number().refine((value) => Number.isFinite(value) && Math.abs(value) <= 0x16345785d8a0000, `a Vector's values are finite numbers of at most ${MAX_VALUE} in size`)).min(1).max(MAX_DIMENSION);
|
|
67
|
+
const Vector = z.object({
|
|
68
|
+
id: VectorId,
|
|
69
|
+
values: Values,
|
|
70
|
+
metadata: Metadata.optional()
|
|
71
|
+
}).strict();
|
|
72
|
+
const Text = z.string().max(MAX_TEXT).refine((text) => text.trim().length > 0, "a text to embed is not empty or all spaces");
|
|
73
|
+
const TextVector = z.object({
|
|
74
|
+
id: VectorId,
|
|
75
|
+
text: Text,
|
|
76
|
+
metadata: Metadata.optional()
|
|
77
|
+
}).strict();
|
|
78
|
+
const Vectors = z.array(z.union([Vector, TextVector])).min(1).max(MAX_BATCH).refine((vectors) => new Set(vectors.map((v) => v.id)).size === vectors.length, "each id is upserted once a call");
|
|
79
|
+
const Ids = z.array(VectorId).min(1).max(MAX_BATCH);
|
|
80
|
+
const Bound = z.union([z.string().max(2048), z.number().refine(Number.isFinite)]);
|
|
81
|
+
const Item = z.union([z.string().max(2048), z.number().refine(Number.isFinite)]);
|
|
82
|
+
const Pattern = z.string().max(2048);
|
|
83
|
+
const Nullable = z.union([Scalar, z.null()]);
|
|
84
|
+
const Condition = z.union([Scalar, z.object({
|
|
85
|
+
$eq: Nullable.optional(),
|
|
86
|
+
$ne: Nullable.optional(),
|
|
87
|
+
$in: z.array(Nullable).min(1).max(100).optional(),
|
|
88
|
+
$nin: z.array(Nullable).min(1).max(100).optional(),
|
|
89
|
+
$gt: Bound.optional(),
|
|
90
|
+
$gte: Bound.optional(),
|
|
91
|
+
$lt: Bound.optional(),
|
|
92
|
+
$lte: Bound.optional(),
|
|
93
|
+
$contains: Item.optional(),
|
|
94
|
+
$notContains: Item.optional(),
|
|
95
|
+
$containsAny: z.array(Item).min(1).max(100).optional(),
|
|
96
|
+
$notContainsAny: z.array(Item).min(1).max(100).optional(),
|
|
97
|
+
$anyGt: Bound.optional(),
|
|
98
|
+
$anyGte: Bound.optional(),
|
|
99
|
+
$anyLt: Bound.optional(),
|
|
100
|
+
$anyLte: Bound.optional(),
|
|
101
|
+
$glob: Pattern.optional(),
|
|
102
|
+
$notGlob: Pattern.optional(),
|
|
103
|
+
$iglob: Pattern.optional(),
|
|
104
|
+
$notIGlob: Pattern.optional(),
|
|
105
|
+
$containsAllTokens: Pattern.optional(),
|
|
106
|
+
$containsAnyToken: z.union([Pattern, z.object({
|
|
107
|
+
tokens: Pattern,
|
|
108
|
+
lastAsPrefix: z.boolean().optional()
|
|
109
|
+
}).strict()]).optional(),
|
|
110
|
+
$containsTokenSequence: Pattern.optional()
|
|
111
|
+
}).strict().refine((condition) => Object.keys(condition).length > 0, "a condition names an operator")]);
|
|
112
|
+
/** A filter's field: a metadata field, or `id`. */
|
|
113
|
+
const FilterField = z.union([z.literal("id"), FieldName]);
|
|
114
|
+
const Fields = z.record(FilterField, Condition).refine((filter) => Object.keys(filter).length <= 20, "a filter names at most 20 fields");
|
|
115
|
+
/** How deep `$and`, `$or` and `$not` nest. */
|
|
116
|
+
const DEPTH = 4;
|
|
117
|
+
function filterOf(depth) {
|
|
118
|
+
if (depth === 0) return Fields;
|
|
119
|
+
const inner = z.lazy(() => filterOf(depth - 1));
|
|
120
|
+
return z.union([
|
|
121
|
+
z.object({ $and: z.array(inner).min(1).max(20) }).strict(),
|
|
122
|
+
z.object({ $or: z.array(inner).min(1).max(20) }).strict(),
|
|
123
|
+
z.object({ $not: inner }).strict(),
|
|
124
|
+
Fields
|
|
125
|
+
]);
|
|
126
|
+
}
|
|
127
|
+
/** Each field's condition, all of which must hold (a bare value is `$eq`); or `$and`, `$or` or `$not` of filters, 4 deep at most. */
|
|
128
|
+
const Filter = filterOf(DEPTH);
|
|
129
|
+
const QueryOptions = {
|
|
130
|
+
topK: z.number().int().min(1).max(100),
|
|
131
|
+
filter: Filter.optional(),
|
|
132
|
+
includeValues: z.boolean(),
|
|
133
|
+
includeMetadata: z.boolean(),
|
|
134
|
+
consistency: z.enum(["strong", "eventual"]).optional()
|
|
135
|
+
};
|
|
136
|
+
const Query = z.union([z.object({
|
|
137
|
+
vector: Values,
|
|
138
|
+
...QueryOptions
|
|
139
|
+
}).strict(), z.object({
|
|
140
|
+
text: Text,
|
|
141
|
+
...QueryOptions
|
|
142
|
+
}).strict()]);
|
|
143
|
+
const Include = {
|
|
144
|
+
includeValues: z.boolean(),
|
|
145
|
+
includeMetadata: z.boolean()
|
|
146
|
+
};
|
|
147
|
+
const TopK = z.number().int().min(1).max(100);
|
|
148
|
+
const OrderField = z.union([z.literal("id"), FieldName]);
|
|
149
|
+
const List = z.object({
|
|
150
|
+
orderBy: z.array(z.tuple([OrderField, z.enum(["asc", "desc"])])).min(1).max(8),
|
|
151
|
+
filter: Filter.optional(),
|
|
152
|
+
topK: TopK,
|
|
153
|
+
...Include
|
|
154
|
+
}).strict();
|
|
155
|
+
const Words = z.string().max(MAX_TEXT).refine((words) => /[\p{L}\p{N}]/u.test(words), "a text search has a word");
|
|
156
|
+
const TextSearch = z.object({
|
|
157
|
+
words: Words,
|
|
158
|
+
field: FieldName,
|
|
159
|
+
filter: Filter.optional(),
|
|
160
|
+
topK: TopK,
|
|
161
|
+
...Include
|
|
162
|
+
}).strict();
|
|
163
|
+
const PartOptions = {
|
|
164
|
+
filter: Filter.optional(),
|
|
165
|
+
topK: TopK
|
|
166
|
+
};
|
|
167
|
+
const Part = z.union([
|
|
168
|
+
z.object({
|
|
169
|
+
vector: Values,
|
|
170
|
+
...PartOptions
|
|
171
|
+
}).strict(),
|
|
172
|
+
z.object({
|
|
173
|
+
text: Text,
|
|
174
|
+
...PartOptions
|
|
175
|
+
}).strict(),
|
|
176
|
+
z.object({
|
|
177
|
+
textSearch: Words,
|
|
178
|
+
field: FieldName,
|
|
179
|
+
...PartOptions
|
|
180
|
+
}).strict()
|
|
181
|
+
]);
|
|
182
|
+
const MultiQuery = z.object({
|
|
183
|
+
queries: z.array(Part).min(1).max(16),
|
|
184
|
+
fuse: z.object({
|
|
185
|
+
k: z.number().min(0).max(1e6),
|
|
186
|
+
weights: z.array(z.number().min(0).max(1e6))
|
|
187
|
+
}).strict().optional(),
|
|
188
|
+
topK: TopK,
|
|
189
|
+
includeMetadata: z.boolean()
|
|
190
|
+
}).strict().refine((multi) => !multi.fuse || multi.fuse.weights.length === multi.queries.length, "fuse has one weight a search");
|
|
191
|
+
const AggregateOf = z.union([z.tuple([z.literal("count")]), z.tuple([z.literal("sum"), FieldName])]);
|
|
192
|
+
const Aggregation = z.object({
|
|
193
|
+
aggregates: z.record(z.string().min(1).max(64), AggregateOf).refine((a) => Object.keys(a).length >= 1 && Object.keys(a).length <= 16, "1 to 16 aggregates"),
|
|
194
|
+
groupBy: z.array(FieldName).max(8),
|
|
195
|
+
filter: Filter.optional(),
|
|
196
|
+
limit: z.number().int().min(1).max(1e4)
|
|
197
|
+
}).strict();
|
|
198
|
+
/** An embedding model's name, as the platform offers it. */
|
|
199
|
+
const EmbeddingModel = z.string().min(1).max(100);
|
|
200
|
+
const FullText = z.array(FieldName).max(16).refine((fields) => new Set(fields).size === fields.length, "each full-text field once");
|
|
201
|
+
const Settings = z.object({
|
|
202
|
+
dimension: Dimension,
|
|
203
|
+
metric: Metric,
|
|
204
|
+
embed: EmbeddingModel.optional(),
|
|
205
|
+
fullText: FullText.optional(),
|
|
206
|
+
vectorType: z.enum(["f32", "f16"]).optional()
|
|
207
|
+
}).strict();
|
|
208
|
+
const Update = z.object({ addFullText: FullText.min(1) }).strict();
|
|
209
|
+
/** `value` as `schema` reads it, or `invalid` with why not. */
|
|
210
|
+
function checked(schema, value) {
|
|
211
|
+
const parsed = schema.safeParse(value);
|
|
212
|
+
if (parsed.success) return parsed.data;
|
|
213
|
+
const issue = parsed.error.issues[0];
|
|
214
|
+
throw new VectorError("invalid", `${issue && issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue?.message ?? "not valid"}`);
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/vector/wire.ts
|
|
218
|
+
/**
|
|
219
|
+
* Vector DB's wire: one call is one frame, `{ op, namespace, … }`, and its answer is one frame, `{ ok }`
|
|
220
|
+
* or `{ error, why }` with a `VectorErrorCode`. A frame is a u32 (little-endian) length, that much
|
|
221
|
+
* UTF-8 JSON, then its vectors: each array at a place its call names for one (`places`: an upsert's
|
|
222
|
+
* Vectors' `values`, a query's `vector`, an answer's matches' `values`; never a filter, metadata or
|
|
223
|
+
* an aggregate's key, whatever its fields are named) is `{"$v": n}` in the JSON and section n after
|
|
224
|
+
* it, a u32 count and that many little-endian 32-bit floats, so a value crosses the wire bit for bit
|
|
225
|
+
* (-0 included), never as a JSON number. A transport
|
|
226
|
+
* only carries frames; a Site's own handle is one (`{ send }`), handed to it by the platform for its
|
|
227
|
+
* Environment.
|
|
228
|
+
*
|
|
229
|
+
* const docs = vectorDb(remote(context.vector)).namespace("docs") // a Site
|
|
230
|
+
* const answer = await serve(scoped(engine, (name) => vector.siteNamespace(repositoryId, environment, name)))(frame) // the platform
|
|
231
|
+
*
|
|
232
|
+
* `scoped` is how the platform serves a Site: names mapped to the ids the engine knows them by, and
|
|
233
|
+
* making, changing or dropping a namespace refused.
|
|
234
|
+
*/
|
|
235
|
+
const call = z.discriminatedUnion("op", [
|
|
236
|
+
z.object({
|
|
237
|
+
op: z.literal("describe"),
|
|
238
|
+
namespace: z.string()
|
|
239
|
+
}),
|
|
240
|
+
z.object({
|
|
241
|
+
op: z.literal("upsert"),
|
|
242
|
+
namespace: z.string(),
|
|
243
|
+
vectors: z.unknown()
|
|
244
|
+
}),
|
|
245
|
+
z.object({
|
|
246
|
+
op: z.literal("query"),
|
|
247
|
+
namespace: z.string(),
|
|
248
|
+
query: z.unknown()
|
|
249
|
+
}),
|
|
250
|
+
z.object({
|
|
251
|
+
op: z.literal("fetch"),
|
|
252
|
+
namespace: z.string(),
|
|
253
|
+
ids: z.unknown()
|
|
254
|
+
}),
|
|
255
|
+
z.object({
|
|
256
|
+
op: z.literal("delete"),
|
|
257
|
+
namespace: z.string(),
|
|
258
|
+
ids: z.unknown()
|
|
259
|
+
}),
|
|
260
|
+
z.object({
|
|
261
|
+
op: z.literal("list"),
|
|
262
|
+
namespace: z.string(),
|
|
263
|
+
list: z.unknown()
|
|
264
|
+
}),
|
|
265
|
+
z.object({
|
|
266
|
+
op: z.literal("textSearch"),
|
|
267
|
+
namespace: z.string(),
|
|
268
|
+
search: z.unknown()
|
|
269
|
+
}),
|
|
270
|
+
z.object({
|
|
271
|
+
op: z.literal("multiQuery"),
|
|
272
|
+
namespace: z.string(),
|
|
273
|
+
multi: z.unknown()
|
|
274
|
+
}),
|
|
275
|
+
z.object({
|
|
276
|
+
op: z.literal("aggregate"),
|
|
277
|
+
namespace: z.string(),
|
|
278
|
+
aggregate: z.unknown()
|
|
279
|
+
}),
|
|
280
|
+
z.object({
|
|
281
|
+
op: z.literal("create"),
|
|
282
|
+
namespace: z.string(),
|
|
283
|
+
settings: z.unknown()
|
|
284
|
+
}),
|
|
285
|
+
z.object({
|
|
286
|
+
op: z.literal("update"),
|
|
287
|
+
namespace: z.string(),
|
|
288
|
+
change: z.unknown()
|
|
289
|
+
}),
|
|
290
|
+
z.object({
|
|
291
|
+
op: z.literal("drop"),
|
|
292
|
+
namespace: z.string()
|
|
293
|
+
})
|
|
294
|
+
]);
|
|
295
|
+
const answer = z.union([z.object({
|
|
296
|
+
error: z.enum(vectorErrorCodes),
|
|
297
|
+
why: z.string()
|
|
298
|
+
}), z.object({ ok: z.unknown() })]);
|
|
299
|
+
/** The places of a call's vectors (`side` "call") or of its answer's (`side` "answer"), by its op. */
|
|
300
|
+
function places(op, side) {
|
|
301
|
+
if (side === "call") {
|
|
302
|
+
if (op === "upsert") return [[
|
|
303
|
+
"vectors",
|
|
304
|
+
"*",
|
|
305
|
+
"values"
|
|
306
|
+
]];
|
|
307
|
+
if (op === "query") return [["query", "vector"]];
|
|
308
|
+
if (op === "multiQuery") return [[
|
|
309
|
+
"multi",
|
|
310
|
+
"queries",
|
|
311
|
+
"*",
|
|
312
|
+
"vector"
|
|
313
|
+
]];
|
|
314
|
+
return [];
|
|
315
|
+
}
|
|
316
|
+
if (op === "query" || op === "fetch" || op === "list" || op === "textSearch") return [[
|
|
317
|
+
"ok",
|
|
318
|
+
"*",
|
|
319
|
+
"values"
|
|
320
|
+
]];
|
|
321
|
+
if (op === "multiQuery") return [[
|
|
322
|
+
"ok",
|
|
323
|
+
"results",
|
|
324
|
+
"*",
|
|
325
|
+
"*",
|
|
326
|
+
"values"
|
|
327
|
+
], [
|
|
328
|
+
"ok",
|
|
329
|
+
"fused",
|
|
330
|
+
"*",
|
|
331
|
+
"values"
|
|
332
|
+
]];
|
|
333
|
+
return [];
|
|
334
|
+
}
|
|
335
|
+
/** `value` with each thing at one of `at` (`Places`) given to `f`, the rest as it is. */
|
|
336
|
+
function atPlaces(value, at, f) {
|
|
337
|
+
const walk = (v, paths) => {
|
|
338
|
+
if (paths.some((p) => p.length === 0)) return f(v);
|
|
339
|
+
if (paths.length === 0 || v === null || typeof v !== "object") return v;
|
|
340
|
+
if (Array.isArray(v)) {
|
|
341
|
+
const next = paths.filter((p) => p[0] === "*").map((p) => p.slice(1));
|
|
342
|
+
return next.length === 0 ? v : v.map((item) => walk(item, next));
|
|
343
|
+
}
|
|
344
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => {
|
|
345
|
+
const next = paths.filter((p) => p[0] === k).map((p) => p.slice(1));
|
|
346
|
+
return [k, next.length === 0 ? x : walk(x, next)];
|
|
347
|
+
}));
|
|
348
|
+
};
|
|
349
|
+
return walk(value, at);
|
|
350
|
+
}
|
|
351
|
+
/** `value` as a frame: the arrays of numbers at `where` (`places`) moved into sections (`{"$v": n}`), the JSON first. */
|
|
352
|
+
function encode(value, where = []) {
|
|
353
|
+
const sections = [];
|
|
354
|
+
const lifted = atPlaces(value, where, (v) => Array.isArray(v) && v.every((x) => typeof x === "number") ? { $v: sections.push(v) - 1 } : v);
|
|
355
|
+
const json = new TextEncoder().encode(JSON.stringify(lifted));
|
|
356
|
+
const out = new Uint8Array(4 + json.length + sections.reduce((n, v) => n + 4 + 4 * v.length, 0));
|
|
357
|
+
const view = new DataView(out.buffer);
|
|
358
|
+
view.setUint32(0, json.length, true);
|
|
359
|
+
out.set(json, 4);
|
|
360
|
+
let at = 4 + json.length;
|
|
361
|
+
for (const v of sections) {
|
|
362
|
+
view.setUint32(at, v.length, true);
|
|
363
|
+
at += 4;
|
|
364
|
+
for (const x of v) {
|
|
365
|
+
view.setFloat32(at, x, true);
|
|
366
|
+
at += 4;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return out;
|
|
370
|
+
}
|
|
371
|
+
/** A frame's value (`encode`): its sections back in place of their `{"$v": n}` at `where` (`places`; or, for a call
|
|
372
|
+
* read before its op is known, the places of the op its JSON names). Throws where it does not read. */
|
|
373
|
+
function decode(frame, where = []) {
|
|
374
|
+
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
|
|
375
|
+
const length = view.getUint32(0, true);
|
|
376
|
+
if (4 + length > frame.length) throw new Error("a frame shorter than its JSON");
|
|
377
|
+
const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame.subarray(4, 4 + length)));
|
|
378
|
+
const sections = [];
|
|
379
|
+
for (let at = 4 + length; at < frame.length;) {
|
|
380
|
+
const count = view.getUint32(at, true);
|
|
381
|
+
at += 4;
|
|
382
|
+
if (at + 4 * count > frame.length) throw new Error("a frame shorter than its vectors");
|
|
383
|
+
sections.push(Array.from({ length: count }, (_, k) => view.getFloat32(at + 4 * k, true)));
|
|
384
|
+
at += 4 * count;
|
|
385
|
+
}
|
|
386
|
+
const place = (v) => {
|
|
387
|
+
if (v === null || typeof v !== "object" || Array.isArray(v) || !("$v" in v)) return v;
|
|
388
|
+
const n = v.$v;
|
|
389
|
+
if (typeof n !== "number" || !sections[n]) throw new Error("a vector section that is not there");
|
|
390
|
+
return sections[n];
|
|
391
|
+
};
|
|
392
|
+
return atPlaces(json, typeof where === "function" ? where(json) : where, place);
|
|
393
|
+
}
|
|
394
|
+
/** The places of the call `json` names the op of (`places`). */
|
|
395
|
+
function callPlaces(json) {
|
|
396
|
+
const op = json !== null && typeof json === "object" ? json.op : void 0;
|
|
397
|
+
return typeof op === "string" ? places(op, "call") : [];
|
|
398
|
+
}
|
|
399
|
+
/** An engine that sends each call over `transport`. A transport that fails is `unavailable`. */
|
|
400
|
+
function remote(transport) {
|
|
401
|
+
async function ask(request) {
|
|
402
|
+
let frame;
|
|
403
|
+
try {
|
|
404
|
+
frame = await transport.send(encode(request, places(request.op, "call")));
|
|
405
|
+
} catch {
|
|
406
|
+
throw new VectorError("unavailable", "Vector DB could not be reached. Try again.");
|
|
407
|
+
}
|
|
408
|
+
let parsed;
|
|
409
|
+
try {
|
|
410
|
+
parsed = answer.parse(decode(frame, places(request.op, "answer")));
|
|
411
|
+
} catch {
|
|
412
|
+
throw new VectorError("unavailable", "Vector DB answered something that is not a Vector DB frame");
|
|
413
|
+
}
|
|
414
|
+
if ("error" in parsed) throw new VectorError(parsed.error, parsed.why);
|
|
415
|
+
return parsed.ok;
|
|
416
|
+
}
|
|
417
|
+
return {
|
|
418
|
+
describe: (namespace) => ask({
|
|
419
|
+
op: "describe",
|
|
420
|
+
namespace
|
|
421
|
+
}),
|
|
422
|
+
upsert: (namespace, vectors) => ask({
|
|
423
|
+
op: "upsert",
|
|
424
|
+
namespace,
|
|
425
|
+
vectors
|
|
426
|
+
}),
|
|
427
|
+
query: (namespace, query) => ask({
|
|
428
|
+
op: "query",
|
|
429
|
+
namespace,
|
|
430
|
+
query
|
|
431
|
+
}),
|
|
432
|
+
fetch: (namespace, ids) => ask({
|
|
433
|
+
op: "fetch",
|
|
434
|
+
namespace,
|
|
435
|
+
ids
|
|
436
|
+
}),
|
|
437
|
+
delete: async (namespace, ids) => void await ask({
|
|
438
|
+
op: "delete",
|
|
439
|
+
namespace,
|
|
440
|
+
ids
|
|
441
|
+
}),
|
|
442
|
+
list: (namespace, list) => ask({
|
|
443
|
+
op: "list",
|
|
444
|
+
namespace,
|
|
445
|
+
list
|
|
446
|
+
}),
|
|
447
|
+
textSearch: (namespace, search) => ask({
|
|
448
|
+
op: "textSearch",
|
|
449
|
+
namespace,
|
|
450
|
+
search
|
|
451
|
+
}),
|
|
452
|
+
multiQuery: (namespace, multi) => ask({
|
|
453
|
+
op: "multiQuery",
|
|
454
|
+
namespace,
|
|
455
|
+
multi
|
|
456
|
+
}),
|
|
457
|
+
aggregate: (namespace, aggregate) => ask({
|
|
458
|
+
op: "aggregate",
|
|
459
|
+
namespace,
|
|
460
|
+
aggregate
|
|
461
|
+
}),
|
|
462
|
+
create: async (namespace, settings) => void await ask({
|
|
463
|
+
op: "create",
|
|
464
|
+
namespace,
|
|
465
|
+
settings
|
|
466
|
+
}),
|
|
467
|
+
update: async (namespace, change) => void await ask({
|
|
468
|
+
op: "update",
|
|
469
|
+
namespace,
|
|
470
|
+
change
|
|
471
|
+
}),
|
|
472
|
+
drop: async (namespace) => void await ask({
|
|
473
|
+
op: "drop",
|
|
474
|
+
namespace
|
|
475
|
+
})
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Serves request frames from `engine`. A frame comes from the network, so it is checked here as the
|
|
480
|
+
* client would check it; a refusal is returned as `invalid`. Making and dropping namespaces is
|
|
481
|
+
* served only by an engine that has them, else `forbidden`. A failure that is not a `VectorError`
|
|
482
|
+
* is the engine's own fault and is thrown to the transport, never returned.
|
|
483
|
+
*/
|
|
484
|
+
function serve(engine) {
|
|
485
|
+
return async (frame) => {
|
|
486
|
+
try {
|
|
487
|
+
let json;
|
|
488
|
+
try {
|
|
489
|
+
json = decode(frame, callPlaces);
|
|
490
|
+
} catch {
|
|
491
|
+
throw new VectorError("invalid", "the request frame is not a Vector DB frame");
|
|
492
|
+
}
|
|
493
|
+
const parsed = call.safeParse(json);
|
|
494
|
+
if (!parsed.success) throw new VectorError("invalid", "the request frame is not a Vector DB call");
|
|
495
|
+
const request = parsed.data;
|
|
496
|
+
return encode({ ok: await answerTo(engine, checked(NamespaceName, request.namespace), request) ?? null }, places(request.op, "answer"));
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (error instanceof VectorError) return encode({
|
|
499
|
+
error: error.code,
|
|
500
|
+
why: error.message
|
|
501
|
+
});
|
|
502
|
+
throw error;
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
async function answerTo(engine, namespace, request) {
|
|
507
|
+
switch (request.op) {
|
|
508
|
+
case "describe": return engine.describe(namespace);
|
|
509
|
+
case "upsert": return engine.upsert(namespace, checked(Vectors, request.vectors));
|
|
510
|
+
case "query": return engine.query(namespace, checked(Query, request.query));
|
|
511
|
+
case "fetch": return engine.fetch(namespace, checked(Ids, request.ids));
|
|
512
|
+
case "delete": return engine.delete(namespace, checked(Ids, request.ids));
|
|
513
|
+
case "list": return engine.list(namespace, checked(List, request.list));
|
|
514
|
+
case "textSearch": return engine.textSearch(namespace, checked(TextSearch, request.search));
|
|
515
|
+
case "multiQuery": return engine.multiQuery(namespace, checked(MultiQuery, request.multi));
|
|
516
|
+
case "aggregate": return engine.aggregate(namespace, checked(Aggregation, request.aggregate));
|
|
517
|
+
case "create":
|
|
518
|
+
if (!engine.create) throw new VectorError("forbidden", "Vector namespaces are made through the platform");
|
|
519
|
+
return engine.create(namespace, checked(Settings, request.settings));
|
|
520
|
+
case "update":
|
|
521
|
+
if (!engine.update) throw new VectorError("forbidden", "Vector namespaces are changed through the platform");
|
|
522
|
+
return engine.update(namespace, checked(Update, request.change));
|
|
523
|
+
case "drop":
|
|
524
|
+
if (!engine.drop) throw new VectorError("forbidden", "Vector namespaces are dropped through the platform");
|
|
525
|
+
return engine.drop(namespace);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* `engine` as a Site of one Environment reaches it: `namespaceId` returns, for the one name a call
|
|
530
|
+
* names, the id the engine knows that Environment's Vector namespace by, so a call costs the lookup
|
|
531
|
+
* of its own namespace and never a listing of the others. A name with no id is `not_found`, as a
|
|
532
|
+
* namespace that does not exist is, so a Site learns nothing of other Environments. It cannot make
|
|
533
|
+
* or drop one.
|
|
534
|
+
*/
|
|
535
|
+
function scoped(engine, namespaceId) {
|
|
536
|
+
const id = async (name) => {
|
|
537
|
+
const found = await namespaceId(name);
|
|
538
|
+
if (found === void 0) throw new VectorError("not_found", `There is no Vector namespace named ${name}.`);
|
|
539
|
+
return found;
|
|
540
|
+
};
|
|
541
|
+
return {
|
|
542
|
+
describe: async (namespace) => engine.describe(await id(namespace)),
|
|
543
|
+
upsert: async (namespace, vectors) => engine.upsert(await id(namespace), vectors),
|
|
544
|
+
query: async (namespace, query) => engine.query(await id(namespace), query),
|
|
545
|
+
fetch: async (namespace, ids) => engine.fetch(await id(namespace), ids),
|
|
546
|
+
delete: async (namespace, ids) => engine.delete(await id(namespace), ids),
|
|
547
|
+
list: async (namespace, list) => engine.list(await id(namespace), list),
|
|
548
|
+
textSearch: async (namespace, search) => engine.textSearch(await id(namespace), search),
|
|
549
|
+
multiQuery: async (namespace, multi) => engine.multiQuery(await id(namespace), multi),
|
|
550
|
+
aggregate: async (namespace, aggregate) => engine.aggregate(await id(namespace), aggregate)
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
//#endregion
|
|
554
|
+
export { checked as C, Vectors as S, vectorErrorCodes as T, MAX_VALUE as _, scoped as a, Query as b, Ids as c, MAX_DIMENSION as d, MAX_FULL_TEXT as f, MAX_TOP_K as g, MAX_TEXT as h, remote as i, List as l, MAX_QUERIES as m, encode as n, serve as o, MAX_METADATA_BYTES as p, places as r, Aggregation as s, decode as t, MAX_BATCH as u, MultiQuery as v, VectorError as w, TextSearch as x, NamespaceName as y };
|
package/wire.d.mts
CHANGED