@wazootech/worlds-cloudflare 0.0.0-stage → 0.15.6
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 +21 -0
- package/README.md +359 -2
- package/dist/d1-connection-driver-DfBsnVwn.d.ts +71 -0
- package/dist/d1-provenance-sql-jn_cwWxX.js +99 -0
- package/dist/d1-quad-insert-sql-B4ZiZZe8.js +313 -0
- package/dist/d1-rdfjs-store-read-2QTEEe_a.js +64 -0
- package/dist/d1-schema-builder-DmrQfhKJ.js +86 -0
- package/dist/d1-schema-builder-sx3v-XjI.d.ts +42 -0
- package/dist/index.d.ts +205 -0
- package/dist/index.js +354 -0
- package/dist/mod-BRtbH8pa.d.ts +52 -0
- package/dist/mod-Do_hSIzo.d.ts +452 -0
- package/dist/mod-L9cQ_Ztm.d.ts +192 -0
- package/dist/project-search-chunks-options-qI9m5FWz.js +166 -0
- package/dist/quad-store-DX7Nqyjw.js +398 -0
- package/dist/quad-store.d.ts +2 -0
- package/dist/quad-store.js +1 -0
- package/dist/rdfjs-store-B3w5noFV.js +668 -0
- package/dist/rdfjs-store.d.ts +2 -0
- package/dist/rdfjs-store.js +1 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +1 -0
- package/dist/search-index-DVbbsc3z.js +609 -0
- package/dist/search-index.d.ts +2 -0
- package/dist/search-index.js +1 -0
- package/package.json +84 -4
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { ReindexRequest, ReindexResponse, SearchIndexInterface, SearchIndexOnImport, SearchRequest, SearchResponse } from "@wazootech/worlds-sdk/search-index";
|
|
2
|
+
import { BuildSearchResultIdOptions, SqlProjectionOptions, SqlStatement, buildChunkFtsValue, buildSearchResultId, sanitizeFtsQuery } from "@wazootech/worlds-sqlite/sql-core";
|
|
3
|
+
import { QuadFilter } from "@wazootech/worlds-sdk/quad-store";
|
|
4
|
+
import { EmbeddingService } from "@wazootech/worlds-sdk/search-index/embedding-service";
|
|
5
|
+
import { EmbeddedChunk, TextSplitterInterface } from "@wazootech/worlds-sdk/search-index/quad-chunker";
|
|
6
|
+
import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
|
|
7
|
+
import * as rdfjs from "@rdfjs/types";
|
|
8
|
+
/**
|
|
9
|
+
* InferenceOptions turns on OWL 2 RL materialization for one world. Off by
|
|
10
|
+
* default: without it the commit path is unchanged and `quads.derived` is not
|
|
11
|
+
* required.
|
|
12
|
+
*/
|
|
13
|
+
interface InferenceOptions {
|
|
14
|
+
/** enabled opts the world in. `{ enabled: false }` is the same as omitting it. */
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* graphs is the reasoner's named-graph mode. `"per-graph"` (default) lists
|
|
18
|
+
* each entailed quad in the graph(s) that entail it alone, else in
|
|
19
|
+
* `https://wazoo.dev/ns/reasoner#derived`; `"union"` merges all graphs and
|
|
20
|
+
* lists everything in the default graph.
|
|
21
|
+
*/
|
|
22
|
+
graphs?: "per-graph" | "union";
|
|
23
|
+
/**
|
|
24
|
+
* maxAssertedQuads is the size guard (default 100000). Each commit rebuilds
|
|
25
|
+
* the reasoner from the world's asserted quads, so a commit that would
|
|
26
|
+
* exceed it fails before writing instead of exhausting the isolate.
|
|
27
|
+
*/
|
|
28
|
+
maxAssertedQuads?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* ProvenanceOptions turns on durable provenance for one world. Off by default:
|
|
32
|
+
* without it no record is written and the `provenance` table is not created.
|
|
33
|
+
*/
|
|
34
|
+
interface ProvenanceOptions {
|
|
35
|
+
/** enabled opts the world in. `{ enabled: false }` is the same as omitting it. */
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* history set to false leaves the correction chains out of provenance queries:
|
|
39
|
+
* `history` comes back empty, and `records` is unchanged. A chain grows with
|
|
40
|
+
* every correction of a value, so set it when you only need the records.
|
|
41
|
+
*/
|
|
42
|
+
history?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* D1ClientBaseOptions lists configuration shared by quad index Cloudflare D1 client factories.
|
|
46
|
+
*/
|
|
47
|
+
interface D1ClientBaseOptions extends QuadFilter {
|
|
48
|
+
/** embeddingService is an optional service projected for transforming text literals into comparison vectors. */
|
|
49
|
+
embeddingService?: EmbeddingService;
|
|
50
|
+
/** textSplitter is an optional custom text splitting facility, defaults to sensible character-based splitting. */
|
|
51
|
+
textSplitter?: TextSplitterInterface;
|
|
52
|
+
/** maxLookupChunkSize specifies the maximum number of host parameters allowed in cache query IN clauses before split-chunking. Defaults to 100 (D1's 100-bound-params/statement cap). */
|
|
53
|
+
maxLookupChunkSize?: number;
|
|
54
|
+
/**
|
|
55
|
+
* vectorDimensions pins F32_BLOB width for chunk vectors and must match every embedding produced when embeddingService is set (default 1536).
|
|
56
|
+
*/
|
|
57
|
+
vectorDimensions?: number;
|
|
58
|
+
/**
|
|
59
|
+
* matchPageSize limits rows per D1RdfjsStore.match SQL round-trip on reads (default 1000).
|
|
60
|
+
*/
|
|
61
|
+
matchPageSize?: number;
|
|
62
|
+
/** maxWriteBatchSize caps how many statements are sent per D1 batch, and so how many a commit may hold and still be atomic. Defaults to 2,000, the largest count measured fine on a real D1 at every vector dimension (Cloudflare documents no per-batch statement cap; the 100 limit is bound parameters per statement, a separate cap). */
|
|
63
|
+
maxWriteBatchSize?: number;
|
|
64
|
+
/** maxBatchWeight caps the estimated serialized bytes per D1 batch (default 16 MiB, 2x under the 32 MiB Worker-to-D1 RPC limit measured on a real D1). A commit is atomic only if it fits this and `maxWriteBatchSize`; heavy rows (1,536-dim vectors) hit this first. */
|
|
65
|
+
maxBatchWeight?: number;
|
|
66
|
+
/**
|
|
67
|
+
* searchIndexOnImport controls when FTS/vector chunk projection runs during import.
|
|
68
|
+
*
|
|
69
|
+
* - `"incremental"` (default): chunks each quad on commit, so an import embeds only the quads it writes.
|
|
70
|
+
* - `"deferred"`: persists quads on each import, then rebuilds FTS/vector chunks for the whole world in one pass.
|
|
71
|
+
* - `"disabled"`: skips chunking entirely; caller calls `client.reindex()` before searching.
|
|
72
|
+
*/
|
|
73
|
+
searchIndexOnImport?: SearchIndexOnImport;
|
|
74
|
+
/**
|
|
75
|
+
* inference opts this world in to OWL 2 RL materialization on write. Needs
|
|
76
|
+
* the `quads.derived` column (see migrations/0001-quads-derived-column.sql).
|
|
77
|
+
*/
|
|
78
|
+
inference?: InferenceOptions;
|
|
79
|
+
/**
|
|
80
|
+
* provenance opts this world in to a record of when each quad was written or
|
|
81
|
+
* removed, by what, and what it replaced. Set it on every SDK that writes the
|
|
82
|
+
* world: a commit made without it leaves a gap.
|
|
83
|
+
*/
|
|
84
|
+
provenance?: ProvenanceOptions;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* RRF_REFERENCE_CONSTANT is the reciprocal-rank constant used by both backends
|
|
88
|
+
* (k = 60), kept as a compatibility alias for sql-core's RRF_FUSION_K.
|
|
89
|
+
* @deprecated Import RRF_FUSION_K from @wazootech/worlds-sqlite/sql-core instead.
|
|
90
|
+
*/
|
|
91
|
+
declare const RRF_REFERENCE_CONSTANT = 60;
|
|
92
|
+
/**
|
|
93
|
+
* D1SearchQueryBuilder builds keyword-only FTS5 chunk queries against the
|
|
94
|
+
* `chunks`/`chunks_fts` tables. The vector signal lives outside D1 (Vectorize,
|
|
95
|
+
* Phase C), so no `vector_top_k` / `vector32` SQL is emitted here; chunk rows
|
|
96
|
+
* store the F32_BLOB width for future Vectorize sync.
|
|
97
|
+
*/
|
|
98
|
+
interface D1SearchQueryBuilderOptions {
|
|
99
|
+
worldId?: string;
|
|
100
|
+
}
|
|
101
|
+
declare class D1SearchQueryBuilder {
|
|
102
|
+
readonly vectorDimensions: number;
|
|
103
|
+
readonly worldId?: string;
|
|
104
|
+
constructor(vectorDimensions: number, options?: D1SearchQueryBuilderOptions);
|
|
105
|
+
buildInsertChunk(insertOptions: {
|
|
106
|
+
quad_id: string;
|
|
107
|
+
subject: string;
|
|
108
|
+
predicate: string;
|
|
109
|
+
graph: string;
|
|
110
|
+
value: string;
|
|
111
|
+
fts_value: string;
|
|
112
|
+
vector?: Float32Array | null;
|
|
113
|
+
world_id?: string;
|
|
114
|
+
}): SqlStatement;
|
|
115
|
+
/** buildClearChunks removes every chunk row of this builder's world (all rows without one). */
|
|
116
|
+
buildClearChunks(): SqlStatement;
|
|
117
|
+
buildDeleteByQuadIds(quadIds: string[]): SqlStatement;
|
|
118
|
+
/**
|
|
119
|
+
* buildChunkVectorLookupByQuadIds selects the fields needed to recompute
|
|
120
|
+
* deterministic vector ids (`buildSearchResultId`) for the chunk rows of
|
|
121
|
+
* the given quads — used by the projector to delete stale vectors from the
|
|
122
|
+
* outside-D1 vector index before refreshing chunk rows.
|
|
123
|
+
*/
|
|
124
|
+
buildChunkVectorLookupByQuadIds(quadIds: string[]): SqlStatement;
|
|
125
|
+
sanitizeFtsQuery(query: string): string;
|
|
126
|
+
buildSearchQuery(request: SearchRequest, searchBuildOptions: {
|
|
127
|
+
limit: number;
|
|
128
|
+
}): SqlStatement;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* VectorSearchIndex abstracts the vector nearest-neighbor index behind the
|
|
132
|
+
* hosted search path (Phase C, worlds-api#1). The Cloudflare implementation
|
|
133
|
+
* wraps a Vectorize binding; the fake is used in tests.
|
|
134
|
+
*
|
|
135
|
+
* Vector ids are the SDK's deterministic `buildSearchResultId` values — the
|
|
136
|
+
* SAME ids the keyword FTS path emits — so hybrid fusion can correlate the
|
|
137
|
+
* two result lists without any id reconciliation.
|
|
138
|
+
*/
|
|
139
|
+
interface VectorSearchEntry {
|
|
140
|
+
/** Contract search-result id (buildSearchResultId of the chunk quad). */
|
|
141
|
+
id: string;
|
|
142
|
+
/** Embedded chunk vector; must match the index dimensions. */
|
|
143
|
+
vector: Float32Array;
|
|
144
|
+
/**
|
|
145
|
+
* Metadata used for filtering and result rendering. `world_id` must be
|
|
146
|
+
* present for per-world scoping (the hosted index registers it as a
|
|
147
|
+
* filterable property at creation time).
|
|
148
|
+
*/
|
|
149
|
+
metadata: Record<string, string>;
|
|
150
|
+
}
|
|
151
|
+
interface VectorSearchHit {
|
|
152
|
+
/** The entry id (`buildSearchResultId` of the chunk quad). */
|
|
153
|
+
id: string;
|
|
154
|
+
/** Cosine similarity in [-1, 1]; consumers clamp to the [0, 1] contract scale. */
|
|
155
|
+
score: number;
|
|
156
|
+
/** The entry metadata (subject/predicate/graph/value + world_id). */
|
|
157
|
+
metadata?: Record<string, string>;
|
|
158
|
+
}
|
|
159
|
+
interface VectorSearchQueryOptions {
|
|
160
|
+
/** Maximum number of nearest neighbors to return. */
|
|
161
|
+
topK: number;
|
|
162
|
+
/**
|
|
163
|
+
* Exact-match metadata filter (e.g. `{ world_id }`). The Cloudflare
|
|
164
|
+
* binding only supports properties registered as filterable on the index.
|
|
165
|
+
*/
|
|
166
|
+
filter?: Record<string, string>;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* VectorizeIndexLike is the minimal Vectorize binding surface the hosted
|
|
170
|
+
* seam uses: query (similarity search), upsert, and deleteByIds. Cloudflare's
|
|
171
|
+
* real `VectorizeIndex` binding satisfies it structurally (like
|
|
172
|
+
* D1DatabaseLike), so tests can also exercise it with call-sites that accept
|
|
173
|
+
* either.
|
|
174
|
+
*/
|
|
175
|
+
interface VectorizeIndexLike {
|
|
176
|
+
query(vector: number[], options?: {
|
|
177
|
+
topK?: number;
|
|
178
|
+
filter?: Record<string, string>;
|
|
179
|
+
returnValues?: boolean;
|
|
180
|
+
returnMetadata?: boolean;
|
|
181
|
+
}): Promise<{
|
|
182
|
+
matches: VectorizeMatchLike[];
|
|
183
|
+
count: number;
|
|
184
|
+
}>;
|
|
185
|
+
upsert(vectors: Array<{
|
|
186
|
+
id: string;
|
|
187
|
+
values: number[];
|
|
188
|
+
metadata?: Record<string, string>;
|
|
189
|
+
}>): Promise<unknown>;
|
|
190
|
+
deleteByIds(ids: string[]): Promise<unknown>;
|
|
191
|
+
/**
|
|
192
|
+
* deleteByMetadataFilter deletes every vector whose metadata matches the
|
|
193
|
+
* filter. Requires a metadata index on the filtered property (provisioning
|
|
194
|
+
* already mandates one on `world_id`). Optional so older bindings and test
|
|
195
|
+
* doubles stay structurally assignable.
|
|
196
|
+
*/
|
|
197
|
+
deleteByMetadataFilter?(filter: {
|
|
198
|
+
filter: Record<string, string>;
|
|
199
|
+
}): Promise<unknown>;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* A single Vectorize query match, loosely typed for structural compatibility
|
|
203
|
+
* with the real binding: workers-types' `VectorizeMatch.metadata` is
|
|
204
|
+
* `VectorizeVectorMetadata` (value or record), so `unknown` keeps the real
|
|
205
|
+
* `VectorizeIndex` assignable without a workers-types dependency. Consumers
|
|
206
|
+
* that need metadata coerce it (see metadataToRecord in
|
|
207
|
+
* vectorize-vector-search-index.ts).
|
|
208
|
+
*/
|
|
209
|
+
interface VectorizeMatchLike {
|
|
210
|
+
id: string;
|
|
211
|
+
score: number;
|
|
212
|
+
metadata?: unknown;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* VectorSearchIndex is the provider boundary for vector nearest-neighbor
|
|
216
|
+
* search used by the hybrid/semantic search path.
|
|
217
|
+
*/
|
|
218
|
+
interface VectorSearchIndex {
|
|
219
|
+
/** query returns the topK nearest neighbors to `vector`, best first. */
|
|
220
|
+
query(vector: number[], options: VectorSearchQueryOptions): Promise<VectorSearchHit[]>;
|
|
221
|
+
/** upsert inserts or replaces the given entries. */
|
|
222
|
+
upsert(entries: VectorSearchEntry[]): Promise<void>;
|
|
223
|
+
/** deleteByIds removes entries by id (best-effort for unknown ids). */
|
|
224
|
+
deleteByIds(ids: string[]): Promise<void>;
|
|
225
|
+
/**
|
|
226
|
+
* deleteAll removes every vector this index instance owns (worlds-cloudflare#71 item 3).
|
|
227
|
+
* The Vectorize implementation is world-scoped, so this purges one world;
|
|
228
|
+
* it backs replace-import wipes and the reindex reconcile pass. Throws when
|
|
229
|
+
* the underlying binding cannot delete by metadata filter — callers count
|
|
230
|
+
* the failure as drift rather than failing the write.
|
|
231
|
+
*/
|
|
232
|
+
deleteAll(): Promise<void>;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* VectorSyncReport records what happened to the outside-D1 vector index
|
|
236
|
+
* during a projection or reindex (worlds-cloudflare#40).
|
|
237
|
+
*
|
|
238
|
+
* Vector sync never fails a write — D1 is the source of truth and keyword
|
|
239
|
+
* search keeps serving — but a failure is no longer discarded: it is counted
|
|
240
|
+
* here, logged as an error, and surfaced by reindex so a caller can tell
|
|
241
|
+
* "completed" from "D1 rebuilt, vectors drifted". Reindex is the repair path:
|
|
242
|
+
* it re-embeds and re-upserts every chunk, and vector ids are deterministic
|
|
243
|
+
* per world, so reruns are idempotent.
|
|
244
|
+
*/
|
|
245
|
+
interface VectorSyncReport {
|
|
246
|
+
/** enabled is false when no vector index or embedding service is wired. */
|
|
247
|
+
enabled: boolean;
|
|
248
|
+
/** attempted is the number of vectors sent to the vector index. */
|
|
249
|
+
attempted: number;
|
|
250
|
+
/** upserted is the number of vectors the vector index accepted. */
|
|
251
|
+
upserted: number;
|
|
252
|
+
/** failedUpserts is the number of vectors whose upsert failed. */
|
|
253
|
+
failedUpserts: number;
|
|
254
|
+
/**
|
|
255
|
+
* embeddingFailures is always 0: an embedding failure now throws before
|
|
256
|
+
* anything is written, on D1 as on every backend. The field stays so
|
|
257
|
+
* consumers that validate the report's shape keep parsing it.
|
|
258
|
+
*/
|
|
259
|
+
embeddingFailures: number;
|
|
260
|
+
/** staleDeleteFailures is the number of stale vectors that could not be removed. */
|
|
261
|
+
staleDeleteFailures: number;
|
|
262
|
+
/** errors holds the first few failure messages, for diagnosis. */
|
|
263
|
+
errors: string[];
|
|
264
|
+
}
|
|
265
|
+
/** emptyVectorSyncReport starts a report for a pass with vector sync on or off. */
|
|
266
|
+
declare function emptyVectorSyncReport(enabled: boolean): VectorSyncReport;
|
|
267
|
+
/** mergeVectorSyncReports sums two reports (e.g. across reindex pages). */
|
|
268
|
+
declare function mergeVectorSyncReports(left: VectorSyncReport, right: VectorSyncReport): VectorSyncReport;
|
|
269
|
+
/** vectorSyncSucceeded is true when nothing was dropped or left stale. */
|
|
270
|
+
declare function vectorSyncSucceeded(report: VectorSyncReport): boolean;
|
|
271
|
+
/** recordVectorSyncError appends a failure message, keeping the list short. */
|
|
272
|
+
declare function recordVectorSyncError(report: VectorSyncReport, stage: string, error: unknown): void;
|
|
273
|
+
/**
|
|
274
|
+
* logVectorSyncDrift emits one structured error when a pass left the vector
|
|
275
|
+
* index out of step with D1, so drift is visible in Worker logs.
|
|
276
|
+
*/
|
|
277
|
+
declare function logVectorSyncDrift(report: VectorSyncReport, context: {
|
|
278
|
+
worldId?: string;
|
|
279
|
+
operation: string;
|
|
280
|
+
}): void;
|
|
281
|
+
/**
|
|
282
|
+
* CloudflareReindexResponse is the SDK ReindexResponse plus the vector sync
|
|
283
|
+
* report, so a reindex whose vector half failed is distinguishable from a
|
|
284
|
+
* complete one (worlds-cloudflare#40).
|
|
285
|
+
*/
|
|
286
|
+
interface CloudflareReindexResponse extends ReindexResponse {
|
|
287
|
+
vectorSync: VectorSyncReport;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* CloudflareSearchIndexOptions defines the structured configuration and dependency parameters needed to construct the Cloudflare D1 search engine.
|
|
291
|
+
*/
|
|
292
|
+
interface CloudflareSearchIndexOptions extends D1ClientBaseOptions {
|
|
293
|
+
/** connection is the D1ConnectionDriver wrapping the D1 binding. */
|
|
294
|
+
connection: D1ConnectionDriver;
|
|
295
|
+
/** worldId scopes the vector query via the world_id metadata filter. */
|
|
296
|
+
worldId?: string;
|
|
297
|
+
/** searchQueryBuilder must match the schema and commit path used when materializing chunk vectors. */
|
|
298
|
+
searchQueryBuilder: D1SearchQueryBuilder;
|
|
299
|
+
/**
|
|
300
|
+
* candidateCount sizes the internal candidate pool at the SQL level — the
|
|
301
|
+
* number of ranked hits fetched before normalization and post-ranking
|
|
302
|
+
* minScore filtering. Provider-internal per the hosted search contract
|
|
303
|
+
* (worlds-api#30 D2); callers pass `max(limit, world.topK)`. Defaults to
|
|
304
|
+
* `limit` (100).
|
|
305
|
+
*/
|
|
306
|
+
candidateCount?: number;
|
|
307
|
+
/**
|
|
308
|
+
* vectorSearch is the outside-D1 vector index (Phase C, worlds-api#1). When
|
|
309
|
+
* both vectorSearch and an embeddingService are wired, searches become
|
|
310
|
+
* hybrid (FTS + vector fused by the contract's deterministic ids) and
|
|
311
|
+
* `mode` reports semantic/hybrid/keyword accordingly.
|
|
312
|
+
*/
|
|
313
|
+
vectorSearch?: VectorSearchIndex;
|
|
314
|
+
/** limit establishes optional page sizing constraints for search result sets, defaulting to 100. */
|
|
315
|
+
limit?: number;
|
|
316
|
+
/** maxWriteBatchSize caps statements per D1 batch during reindex (default 2,000). */
|
|
317
|
+
maxWriteBatchSize?: number;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* CloudflareSearchIndex implements the query pathway over D1's FTS5
|
|
321
|
+
* external-content `chunks_fts` table fused with an outside-D1 vector index
|
|
322
|
+
* (Phase C): keyword matches rank via reciprocal rank fusion against the
|
|
323
|
+
* reference constant; when an embeddingService + Vectorize-bound
|
|
324
|
+
* vectorSearch are wired, the query is embedded and the two lists fuse.
|
|
325
|
+
*
|
|
326
|
+
* Ranked semantics come from the reported `mode` — hybrid (both lists),
|
|
327
|
+
* semantic (vector-only), keyword (FTS-only). No JS cosine fallback exists
|
|
328
|
+
* per the cloudflare architecture decision (worlds-sdk-ts#63); any vector
|
|
329
|
+
* failure degrades gracefully to keyword-only.
|
|
330
|
+
*/
|
|
331
|
+
declare class CloudflareSearchIndex implements SearchIndexInterface {
|
|
332
|
+
private readonly options;
|
|
333
|
+
constructor(options: CloudflareSearchIndexOptions);
|
|
334
|
+
/**
|
|
335
|
+
* search executes a keyword and/or vector query against the index and fuses
|
|
336
|
+
* the ranked lists on the contract's deterministic result ids.
|
|
337
|
+
*/
|
|
338
|
+
search(request: SearchRequest): Promise<SearchResponse>;
|
|
339
|
+
/**
|
|
340
|
+
* reindex rebuilds FTS chunk rows (and, when wired, re-embeds and re-upserts
|
|
341
|
+
* vectors) from durable quads without re-importing graph data. It is the
|
|
342
|
+
* repair path for vector drift; `vectorSync` reports what reached the index.
|
|
343
|
+
*/
|
|
344
|
+
reindex(request?: ReindexRequest): Promise<CloudflareReindexResponse>;
|
|
345
|
+
}
|
|
346
|
+
interface ProjectSearchChunksOptions extends D1ClientBaseOptions {
|
|
347
|
+
/** connection is the D1ConnectionDriver wrapping the D1 binding. */
|
|
348
|
+
connection: D1ConnectionDriver;
|
|
349
|
+
textSplitter: TextSplitterInterface;
|
|
350
|
+
maxWriteBatchSize?: number;
|
|
351
|
+
searchQueryBuilder: D1SearchQueryBuilder;
|
|
352
|
+
/**
|
|
353
|
+
* vectorSearch syncs chunk vectors to the outside-D1 vector index (Phase C).
|
|
354
|
+
* Only active when an embeddingService is also configured; otherwise chunks
|
|
355
|
+
* stay keyword-only.
|
|
356
|
+
*/
|
|
357
|
+
vectorSearch?: VectorSearchIndex;
|
|
358
|
+
worldId?: string;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* D1VectorSync keeps the outside-D1 vector index (Vectorize) in step with the
|
|
362
|
+
* chunk rows the shared commit core writes to D1. D1 batches and Vectorize
|
|
363
|
+
* writes cannot share a transaction, so the vectors are synced after the D1
|
|
364
|
+
* write lands: a failure there is counted and logged as drift, never thrown
|
|
365
|
+
* (D1 stays the source of truth and a reindex repairs it).
|
|
366
|
+
*/
|
|
367
|
+
declare class D1VectorSync {
|
|
368
|
+
private readonly options;
|
|
369
|
+
/** report accumulates everything this sync did to the vector index. */
|
|
370
|
+
report: VectorSyncReport;
|
|
371
|
+
private pending;
|
|
372
|
+
constructor(options: ProjectSearchChunksOptions);
|
|
373
|
+
/** collect remembers the vectors of chunk rows the core just built. */
|
|
374
|
+
collect: (rows: readonly EmbeddedChunk[]) => void;
|
|
375
|
+
/** flush upserts the collected vectors into the outside-D1 index. */
|
|
376
|
+
flush(): Promise<void>;
|
|
377
|
+
/**
|
|
378
|
+
* beforePage runs before each page of a rebuild: the previous page is
|
|
379
|
+
* fully written by now, so its vectors sync, and the vectors of the chunk
|
|
380
|
+
* rows this page is about to replace are removed.
|
|
381
|
+
*/
|
|
382
|
+
beforePage: (quads: rdfjs.Quad[]) => Promise<void>;
|
|
383
|
+
/** purgeWorld deletes every vector of this world from the outside-D1 index. */
|
|
384
|
+
purgeWorld(): Promise<void>;
|
|
385
|
+
/** deleteStale removes the vectors of the chunk rows about to be replaced for these quads. */
|
|
386
|
+
deleteStale(quadIds: string[]): Promise<void>;
|
|
387
|
+
/** logDrift logs one structured error when this sync left the index out of step with D1. */
|
|
388
|
+
logDrift(operation: string): void;
|
|
389
|
+
private merge;
|
|
390
|
+
}
|
|
391
|
+
interface D1SearchIndexProjectorOptions extends ProjectSearchChunksOptions {}
|
|
392
|
+
/**
|
|
393
|
+
* D1SearchIndexProjector holds what search projection needs beyond the shared
|
|
394
|
+
* SQL commit core: the chunking and embedding options, the outside-D1 vector
|
|
395
|
+
* sync, and the full rebuild. The commit itself runs in `commitD1Patch`.
|
|
396
|
+
*/
|
|
397
|
+
declare class D1SearchIndexProjector {
|
|
398
|
+
private readonly options;
|
|
399
|
+
constructor(options: D1SearchIndexProjectorOptions);
|
|
400
|
+
/** projection is the shared core's chunking and embedding configuration. */
|
|
401
|
+
get projection(): SqlProjectionOptions;
|
|
402
|
+
/** createVectorSync starts a sync of chunk-row vectors to the outside-D1 index for one commit or rebuild. */
|
|
403
|
+
createVectorSync(): D1VectorSync;
|
|
404
|
+
/**
|
|
405
|
+
* reindexAll rebuilds the entire search index directly from durable quads.
|
|
406
|
+
*/
|
|
407
|
+
reindexAll(): Promise<void>;
|
|
408
|
+
/**
|
|
409
|
+
* purgeVectors deletes every vector this world holds in the outside-D1
|
|
410
|
+
* vector index (worlds-cloudflare#71 item 3).
|
|
411
|
+
*/
|
|
412
|
+
purgeVectors(): Promise<VectorSyncReport>;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* RebuildD1SearchIndexFromQuadsResult reports how many quads and chunk rows were processed.
|
|
416
|
+
*/
|
|
417
|
+
interface RebuildD1SearchIndexFromQuadsResult {
|
|
418
|
+
/** processedQuadCount is the number of quads read from durable storage. */
|
|
419
|
+
processedQuadCount: number;
|
|
420
|
+
/** chunkRowCount is the number of chunk rows written to FTS tables. */
|
|
421
|
+
chunkRowCount: number;
|
|
422
|
+
/** vectorSync reports what reached the outside-D1 vector index (#40). */
|
|
423
|
+
vectorSync: VectorSyncReport;
|
|
424
|
+
}
|
|
425
|
+
interface ReadProjectSearchChunksOptions extends ProjectSearchChunksOptions {
|
|
426
|
+
readPageSize?: number;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* rebuildD1SearchIndexFromQuads rebuilds FTS chunk rows from the `quads` table
|
|
430
|
+
* without re-importing graph data, through the shared `rebuildSqlSearchIndex`.
|
|
431
|
+
*
|
|
432
|
+
* Use after schema upgrades, label predicate changes, or discovery-index tuning so existing corpora pick up refreshed `fts_value`.
|
|
433
|
+
*
|
|
434
|
+
* An unscoped rebuild clears the world's chunk rows first, so rows of quads
|
|
435
|
+
* that no longer exist go too. With an include/exclude filter the rebuild is
|
|
436
|
+
* scoped: it replaces only the chunk rows of the matching quads and leaves the
|
|
437
|
+
* rest alone. `processedQuadCount` counts every stored quad scanned.
|
|
438
|
+
*
|
|
439
|
+
* When vector sync is on and no include/exclude filter narrows the rebuild,
|
|
440
|
+
* the world's vectors are purged first (worlds-cloudflare#71 item 3): quads
|
|
441
|
+
* removed since the last projection have no surviving D1 row to derive a
|
|
442
|
+
* vector id from, so a rebuild that only upserts would leave their vectors
|
|
443
|
+
* searchable forever. Deleting first and re-upserting makes reindex a true
|
|
444
|
+
* reconcile; a purge failure is counted as drift, not thrown. An embedding
|
|
445
|
+
* failure throws.
|
|
446
|
+
*/
|
|
447
|
+
declare function rebuildD1SearchIndexFromQuads(options: ReadProjectSearchChunksOptions): Promise<RebuildD1SearchIndexFromQuadsResult>;
|
|
448
|
+
/**
|
|
449
|
+
* createD1SearchIndexRebuilder returns a closure that rebuilds search chunks using stable D1 dependencies.
|
|
450
|
+
*/
|
|
451
|
+
declare function createD1SearchIndexRebuilder(dependencies: ReadProjectSearchChunksOptions): () => Promise<RebuildD1SearchIndexFromQuadsResult>;
|
|
452
|
+
export { D1SearchQueryBuilder as C, D1ClientBaseOptions as D, sanitizeFtsQuery as E, InferenceOptions as O, VectorizeIndexLike as S, RRF_REFERENCE_CONSTANT as T, logVectorSyncDrift as _, RebuildD1SearchIndexFromQuadsResult as a, vectorSyncSucceeded as b, D1SearchIndexProjector as c, ProjectSearchChunksOptions as d, CloudflareSearchIndex as f, emptyVectorSyncReport as g, VectorSyncReport as h, ReadProjectSearchChunksOptions as i, ProvenanceOptions as k, D1SearchIndexProjectorOptions as l, CloudflareSearchIndexOptions as m, buildChunkFtsValue as n, createD1SearchIndexRebuilder as o, CloudflareReindexResponse as p, buildSearchResultId as r, rebuildD1SearchIndexFromQuads as s, BuildSearchResultIdOptions as t, D1VectorSync as u, mergeVectorSyncReports as v, D1SearchQueryBuilderOptions as w, VectorSearchIndex as x, recordVectorSyncError as y };
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import * as rdfjs from "@rdfjs/types";
|
|
2
|
+
import { Patch, TransactionContext } from "@wazootech/worlds-sdk/quad-store";
|
|
3
|
+
import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
|
|
4
|
+
import { t as D1SchemaBuilder } from "./d1-schema-builder-sx3v-XjI.js";
|
|
5
|
+
type Listener = (...args: any[]) => void;
|
|
6
|
+
/**
|
|
7
|
+
* D1QuadStream is a minimal RDF/JS Stream backed by an async page generator
|
|
8
|
+
* (D1 keyset-paginated match queries), with the same listener semantics as
|
|
9
|
+
* the postgres, indexeddb, and sqlite streams:
|
|
10
|
+
*
|
|
11
|
+
* - attaching a `data` listener switches to flow mode and emits each quad
|
|
12
|
+
* as pages arrive,
|
|
13
|
+
* - attaching a `readable` listener (or calling `read()`) enables pull mode,
|
|
14
|
+
* - attaching only `end`/`error` listeners (a bare completion signal) runs
|
|
15
|
+
* the generator to exhaustion and ends,
|
|
16
|
+
* - `end` is only emitted after the generator is exhausted and every quad
|
|
17
|
+
* has been consumed.
|
|
18
|
+
*
|
|
19
|
+
* It implements the full EventEmitter surface required by the `rdfjs.Stream`
|
|
20
|
+
* interface without depending on Node's `events` module.
|
|
21
|
+
*/
|
|
22
|
+
declare class D1QuadStream implements rdfjs.Stream<rdfjs.Quad> {
|
|
23
|
+
private readonly quads;
|
|
24
|
+
private _listeners;
|
|
25
|
+
private _maxListeners;
|
|
26
|
+
private _ended;
|
|
27
|
+
private _flowing;
|
|
28
|
+
private _readStarted;
|
|
29
|
+
private _started;
|
|
30
|
+
private _buffer;
|
|
31
|
+
/** quads supplies the quads as an async generator (one page per chunk). */
|
|
32
|
+
constructor(quads: () => AsyncGenerator<rdfjs.Quad>);
|
|
33
|
+
read(): rdfjs.Quad | null;
|
|
34
|
+
[Symbol.iterator](): Iterator<rdfjs.Quad>;
|
|
35
|
+
destroy(error?: Error): void;
|
|
36
|
+
addListener(eventName: string | symbol, listener: Listener): this;
|
|
37
|
+
/** Typed overloads mirror the Node-style surface of rdfjs.Stream. */
|
|
38
|
+
on(eventName: "data", listener: (quad: rdfjs.Quad) => void): this;
|
|
39
|
+
on(eventName: "readable", listener: () => void): this;
|
|
40
|
+
on(eventName: "end", listener: () => void): this;
|
|
41
|
+
on(eventName: "error", listener: (error: Error) => void): this;
|
|
42
|
+
on(eventName: string | symbol, listener: Listener): this;
|
|
43
|
+
once(eventName: "data", listener: (quad: rdfjs.Quad) => void): this;
|
|
44
|
+
once(eventName: "readable", listener: () => void): this;
|
|
45
|
+
once(eventName: "end", listener: () => void): this;
|
|
46
|
+
once(eventName: "error", listener: (error: Error) => void): this;
|
|
47
|
+
once(eventName: string | symbol, listener: Listener): this;
|
|
48
|
+
prependListener(eventName: "data", listener: (quad: rdfjs.Quad) => void): this;
|
|
49
|
+
prependListener(eventName: "readable", listener: () => void): this;
|
|
50
|
+
prependListener(eventName: "end", listener: () => void): this;
|
|
51
|
+
prependListener(eventName: "error", listener: (error: Error) => void): this;
|
|
52
|
+
prependListener(eventName: string | symbol, listener: Listener): this;
|
|
53
|
+
prependOnceListener(eventName: "data", listener: (quad: rdfjs.Quad) => void): this;
|
|
54
|
+
prependOnceListener(eventName: "readable", listener: () => void): this;
|
|
55
|
+
prependOnceListener(eventName: "end", listener: () => void): this;
|
|
56
|
+
prependOnceListener(eventName: "error", listener: (error: Error) => void): this;
|
|
57
|
+
removeListener(eventName: string | symbol, listener: Listener): this;
|
|
58
|
+
off(eventName: string | symbol, listener: Listener): this;
|
|
59
|
+
removeAllListeners(eventName?: string | symbol): this;
|
|
60
|
+
setMaxListeners(n: number): this;
|
|
61
|
+
getMaxListeners(): number;
|
|
62
|
+
listeners(eventName: string | symbol): Listener[];
|
|
63
|
+
rawListeners(eventName: string | symbol): Listener[];
|
|
64
|
+
emit(eventName: string | symbol, ...args: unknown[]): boolean;
|
|
65
|
+
listenerCount(eventName: string | symbol): number;
|
|
66
|
+
eventNames(): Array<string | symbol>;
|
|
67
|
+
/** _ensureStarted lazily pumps the generator on a microtask. */
|
|
68
|
+
private _ensureStarted;
|
|
69
|
+
private _end;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* D1Transaction is the atomic patch contract a SPARQL update uses to buffer
|
|
73
|
+
* writes. D1 has no interactive transactions, so commit() persists the whole
|
|
74
|
+
* patch in one `db.batch()` call.
|
|
75
|
+
*/
|
|
76
|
+
interface D1Transaction {
|
|
77
|
+
/** add buffers a single quad for insertion on the next commit. */
|
|
78
|
+
add(quad: rdfjs.Quad): unknown;
|
|
79
|
+
/** delete buffers a single quad for deletion on the next commit. */
|
|
80
|
+
delete(quad: rdfjs.Quad): unknown;
|
|
81
|
+
/** commit persists the buffered patch (one D1 batch). */
|
|
82
|
+
commit(): Promise<void>;
|
|
83
|
+
/** rollback discards any uncommitted insertions and deletions. */
|
|
84
|
+
rollback(): void;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* D1RdfjsStoreOptions configures D1RdfjsStore.
|
|
88
|
+
*/
|
|
89
|
+
interface D1RdfjsStoreOptions {
|
|
90
|
+
/** connection is the D1ConnectionDriver wrapping the D1 binding. */
|
|
91
|
+
connection: D1ConnectionDriver;
|
|
92
|
+
/** matchPageSize limits rows per match SQL round-trip (default 1000). */
|
|
93
|
+
matchPageSize?: number;
|
|
94
|
+
/** maxWriteBatchSize caps statements per D1 batch() call (default 2,000). */
|
|
95
|
+
maxWriteBatchSize?: number;
|
|
96
|
+
/** maxLookupChunkSize caps IN-clause / deletion chunk width (default 100). */
|
|
97
|
+
maxLookupChunkSize?: number;
|
|
98
|
+
/** schemaBuilder supplies the DDL the store applies in ensureSchema(). */
|
|
99
|
+
schemaBuilder?: D1SchemaBuilder;
|
|
100
|
+
/** worldId scopes all reads and writes when schema has a world_id column. */
|
|
101
|
+
worldId?: string;
|
|
102
|
+
/** requireDerivedColumn makes ensureSchema verify `quads.derived` (inference). */
|
|
103
|
+
requireDerivedColumn?: boolean;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* D1RdfjsStore is a durable RDF/JS Store over Cloudflare D1. It mirrors the
|
|
107
|
+
* libsql reference shape (10-column `quads` table + 7 covering indexes) and
|
|
108
|
+
* the libsql patch-commit flow, adapted to D1's constraints:
|
|
109
|
+
*
|
|
110
|
+
* - D1 has no interactive transactions; the atomic unit is one `db.batch()`
|
|
111
|
+
* call, which rolls back the whole sequence on any failure. commit() and
|
|
112
|
+
* applyPatch() persist each patch in one batch (chunked only when the
|
|
113
|
+
* staged statements exceed the write batch size),
|
|
114
|
+
* - the 100-bound-params-per-statement cap is respected by inserting
|
|
115
|
+
* 10 quads per statement (10 columns × 10 rows = 100 params),
|
|
116
|
+
* - quad ids are content-addressed (`hashQuads`, RDFC-1.0 canonical ids)
|
|
117
|
+
* exactly like the libsql reference, so the same quad always maps to the
|
|
118
|
+
* same row and insertions are idempotent,
|
|
119
|
+
* - `size` is a synchronous approximation refreshed after every write
|
|
120
|
+
* transaction, mirroring the postgres/sqlite stores.
|
|
121
|
+
*
|
|
122
|
+
* The engine remains store-agnostic and consumes this store through its
|
|
123
|
+
* `createTransaction` hook:
|
|
124
|
+
*
|
|
125
|
+
* const store = new D1RdfjsStore({ connection });
|
|
126
|
+
* const engine = new WazooSparqlEngine({
|
|
127
|
+
* store,
|
|
128
|
+
* createTransaction: () => store.createTransaction(),
|
|
129
|
+
* });
|
|
130
|
+
*/
|
|
131
|
+
declare class D1RdfjsStore implements rdfjs.Store<rdfjs.Quad> {
|
|
132
|
+
private readonly connection;
|
|
133
|
+
private readonly matchPageSize;
|
|
134
|
+
private readonly writeBatchSize;
|
|
135
|
+
private readonly lookupChunkSize;
|
|
136
|
+
private readonly schemaBuilder;
|
|
137
|
+
private readonly worldId?;
|
|
138
|
+
private readonly requireDerivedColumn;
|
|
139
|
+
private readonly writes;
|
|
140
|
+
constructor(options: D1RdfjsStoreOptions);
|
|
141
|
+
/**
|
|
142
|
+
* ensureSchema creates the quads/chunks tables, covering indexes, and the
|
|
143
|
+
* FTS5 external-content table + triggers (idempotent) and seeds the live
|
|
144
|
+
* count. Called by the SDK factory; safe to call again.
|
|
145
|
+
*
|
|
146
|
+
* Statements run through the prepared-statement path (not exec()) because
|
|
147
|
+
* D1's script executor splits on newlines, which would truncate the
|
|
148
|
+
* shared sql-core emitters' multi-line DDL.
|
|
149
|
+
*/
|
|
150
|
+
ensureSchema(): Promise<void>;
|
|
151
|
+
/** flush resolves once every queued write has committed. */
|
|
152
|
+
flush(): Promise<void>;
|
|
153
|
+
/**
|
|
154
|
+
* applyPatch persists a patch atomically in one D1 batch (chunked only when
|
|
155
|
+
* staged statements exceed the write batch size). Quad ids are
|
|
156
|
+
* content-addressed via hashQuads; only truly novel ids are inserted.
|
|
157
|
+
* context.importMode === "replace" clears quads and chunks first (the SDK's
|
|
158
|
+
* replace-import contract).
|
|
159
|
+
*/
|
|
160
|
+
applyPatch(patch: Patch, context?: TransactionContext): Promise<void>;
|
|
161
|
+
/** createTransaction returns a fresh transaction over this store. */
|
|
162
|
+
createTransaction(): D1Transaction;
|
|
163
|
+
addQuad(quad: rdfjs.Quad): this;
|
|
164
|
+
addQuad(subject: rdfjs.Term, predicate: rdfjs.Term, object: rdfjs.Term, graph?: rdfjs.Term): this;
|
|
165
|
+
removeQuad(quad: rdfjs.Quad): this;
|
|
166
|
+
remove(stream: rdfjs.Stream<rdfjs.Quad>): rdfjs.Stream<rdfjs.Quad>;
|
|
167
|
+
import(stream: rdfjs.Stream<rdfjs.Quad>): rdfjs.Stream<rdfjs.Quad>;
|
|
168
|
+
/**
|
|
169
|
+
* match returns a stream of quads matching the given quad pattern.
|
|
170
|
+
* Queries resolve via a single hexastore index seek with no in-memory
|
|
171
|
+
* hydration; reads are keyset-paged by content-addressed quad id.
|
|
172
|
+
*/
|
|
173
|
+
match(subject?: rdfjs.Term | null, predicate?: rdfjs.Term | null, object?: rdfjs.Term | null, graph?: rdfjs.Term | null): D1QuadStream;
|
|
174
|
+
/** getQuads collects the matching quads into an array. */
|
|
175
|
+
getQuads(subject?: rdfjs.Term | null, predicate?: rdfjs.Term | null, object?: rdfjs.Term | null, graph?: rdfjs.Term | null): Promise<rdfjs.Quad[]>;
|
|
176
|
+
/** countQuads returns the number of quads matching the pattern. */
|
|
177
|
+
countQuads(subject?: rdfjs.Term | null, predicate?: rdfjs.Term | null, object?: rdfjs.Term | null, graph?: rdfjs.Term | null): Promise<number>;
|
|
178
|
+
/**
|
|
179
|
+
* removeMatches deletes every matching quad in one D1 batch and streams the
|
|
180
|
+
* removed quads.
|
|
181
|
+
*/
|
|
182
|
+
removeMatches(subject?: rdfjs.Term | null, predicate?: rdfjs.Term | null, object?: rdfjs.Term | null, graph?: rdfjs.Term | null): D1QuadStream;
|
|
183
|
+
/** deleteGraph removes every quad in the named graph. */
|
|
184
|
+
deleteGraph(graph: rdfjs.Quad_Graph | string): D1QuadStream;
|
|
185
|
+
/**
|
|
186
|
+
* size is the synchronous count approximation — refreshed after every
|
|
187
|
+
* write transaction and on ensureSchema. D1 has no synchronous count;
|
|
188
|
+
* consumers needing the exact count await countQuads() instead.
|
|
189
|
+
*/
|
|
190
|
+
get size(): number;
|
|
191
|
+
}
|
|
192
|
+
export { D1QuadStream as i, D1RdfjsStoreOptions as n, D1Transaction as r, D1RdfjsStore as t };
|