@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.
@@ -0,0 +1,609 @@
1
+ import { RRF_FUSION_K, buildChunkFtsValue, buildIncludeExcludeFilterClauses, buildKeywordFtsStatement, buildSearchResultId, buildSearchResultId as buildSearchResultId$1, generatePlaceholders, rebuildSqlSearchIndex, sanitizeFtsQuery, sanitizeFtsQuery as sanitizeFtsQuery$1 } from "@wazootech/worlds-sqlite/sql-core";
2
+ import { normalizeRrfScore } from "@wazootech/worlds-sdk/search-index";
3
+ import { _ as effectiveLookupChunkSize } from "./d1-quad-insert-sql-B4ZiZZe8.js";
4
+ import { i as createD1CommitDriver, n as toProjectionOptions, r as vectorSyncEnabled, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
5
+ import { hashQuads } from "@wazootech/worlds-sdk/quad-store";
6
+ // src/cloudflare/search-index/d1-world-scoped-fts.ts
7
+ /** RRF constant shared with the generic keyword plan (1 / (60 + rank)). */
8
+ const RRF_K = 60;
9
+ /**
10
+ * buildWorldScopedKeywordStatement builds the keyword FTS5 query for a
11
+ * multi-tenant `chunks` table. The `chunks_fts` index is shared by every world,
12
+ * so the world and include/exclude filters are applied in the same join as the
13
+ * MATCH, before ORDER BY rank and LIMIT. The candidate window is therefore
14
+ * filled only with the requesting world's rows and other tenants' rows can
15
+ * neither crowd out nor truncate it.
16
+ *
17
+ * Tradeoff: FTS5 still scores every matching row of the term across all
18
+ * tenants to order the world's rows, so cost grows with the term's global
19
+ * frequency instead of being bounded by `limit`. This favors correctness; a
20
+ * per-world FTS table would be the structural fix.
21
+ */
22
+ function buildWorldScopedKeywordStatement(options) {
23
+ return {
24
+ sql: `
25
+ WITH scoped AS (
26
+ SELECT
27
+ chunks.subject AS subject,
28
+ chunks.predicate AS predicate,
29
+ chunks.graph AS graph,
30
+ chunks.value AS value,
31
+ chunks_fts.rank AS fts_rank
32
+ FROM chunks_fts
33
+ JOIN chunks ON chunks.chunk_id = chunks_fts.rowid
34
+ WHERE ${["chunks_fts MATCH ?", ...options.whereClauses].join(" AND ")}
35
+ ORDER BY chunks_fts.rank
36
+ LIMIT ?
37
+ )
38
+ SELECT
39
+ subject, predicate, graph, value,
40
+ COALESCE(1.0 / (${RRF_K} + row_number() OVER (ORDER BY fts_rank)), 0.0) AS combined_rank
41
+ FROM scoped
42
+ ORDER BY combined_rank DESC
43
+ `,
44
+ args: [
45
+ options.sanitizedQuery,
46
+ ...options.filterArgs,
47
+ options.limit
48
+ ]
49
+ };
50
+ }
51
+ // src/cloudflare/search-index/d1-search-query-sql.ts
52
+ /** CHUNKS_TABLE_COLUMNS maps QuadFilter fields to chunks table column names. */
53
+ const CHUNKS_TABLE_COLUMNS = {
54
+ subjects: "chunks.subject",
55
+ predicates: "chunks.predicate",
56
+ graphs: "chunks.graph"
57
+ };
58
+ /** buildD1KeywordSearchStatement builds the keyword FTS5 chunk query (or the empty-result statement). */
59
+ function buildD1KeywordSearchStatement(request, limit, worldId) {
60
+ const { whereClauses, filterArgs } = buildIncludeExcludeFilterClauses(request, CHUNKS_TABLE_COLUMNS);
61
+ if (worldId) {
62
+ whereClauses.push("chunks.world_id = ?");
63
+ filterArgs.push(worldId);
64
+ }
65
+ const whereFilter = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
66
+ const sanitizedQuery = !!request.query && request.query.trim().length > 0 ? sanitizeFtsQuery$1(request.query) : "";
67
+ const hasKeyword = sanitizedQuery.length > 0;
68
+ if (hasKeyword && worldId) return buildWorldScopedKeywordStatement({
69
+ sanitizedQuery,
70
+ limit,
71
+ whereClauses,
72
+ filterArgs
73
+ });
74
+ if (hasKeyword) {
75
+ const statement = buildKeywordFtsStatement({
76
+ sanitizedQuery,
77
+ limit,
78
+ whereFilter,
79
+ filterArgs
80
+ });
81
+ return {
82
+ ...statement,
83
+ sql: statement.sql.replaceAll("chunks.id", "chunks.chunk_id")
84
+ };
85
+ }
86
+ return {
87
+ sql: "SELECT NULL as subject, NULL as predicate, NULL as graph, NULL as value, 0 as combined_rank WHERE 0 = 1",
88
+ args: []
89
+ };
90
+ }
91
+ // src/cloudflare/search-index/d1-search-query-builder.ts
92
+ /**
93
+ * RRF_REFERENCE_CONSTANT is the reciprocal-rank constant used by both backends
94
+ * (k = 60), kept as a compatibility alias for sql-core's RRF_FUSION_K.
95
+ * @deprecated Import RRF_FUSION_K from @wazootech/worlds-sqlite/sql-core instead.
96
+ */
97
+ const RRF_REFERENCE_CONSTANT = RRF_FUSION_K;
98
+ /** Maximum embedding dimensions accepted by D1SearchQueryBuilder (Vectorize cap: 1536 float32). */
99
+ const D1_SEARCH_QUERY_BUILDER_MAX_VECTOR_DIMENSIONS = 1536;
100
+ var D1SearchQueryBuilder = class {
101
+ vectorDimensions;
102
+ worldId;
103
+ constructor(vectorDimensions, options) {
104
+ const dimensions = Math.floor(Number(vectorDimensions));
105
+ if (!Number.isFinite(dimensions) || dimensions < 1 || dimensions > D1_SEARCH_QUERY_BUILDER_MAX_VECTOR_DIMENSIONS) throw new Error(`vectorDimensions must be a finite integer in [1, ${D1_SEARCH_QUERY_BUILDER_MAX_VECTOR_DIMENSIONS}], received: ${String(vectorDimensions)}`);
106
+ this.vectorDimensions = dimensions;
107
+ this.worldId = options?.worldId;
108
+ }
109
+ buildInsertChunk(insertOptions) {
110
+ const args = [
111
+ insertOptions.quad_id,
112
+ insertOptions.subject,
113
+ insertOptions.predicate,
114
+ insertOptions.graph,
115
+ insertOptions.value,
116
+ insertOptions.fts_value
117
+ ];
118
+ if (insertOptions.vector) args.push(new Uint8Array(insertOptions.vector.buffer));
119
+ else args.push(null);
120
+ if (this.worldId) args.push(insertOptions.world_id ?? this.worldId);
121
+ return {
122
+ sql: `INSERT INTO chunks (quad_id, subject, predicate, graph, value, fts_value, vector${this.worldId ? ", world_id" : ""})
123
+ VALUES (?, ?, ?, ?, ?, ?, ?${this.worldId ? ", ?" : ""})`,
124
+ args
125
+ };
126
+ }
127
+ /** buildClearChunks removes every chunk row of this builder's world (all rows without one). */
128
+ buildClearChunks() {
129
+ return this.worldId ? {
130
+ sql: "DELETE FROM chunks WHERE world_id = ?",
131
+ args: [this.worldId]
132
+ } : {
133
+ sql: "DELETE FROM chunks",
134
+ args: []
135
+ };
136
+ }
137
+ buildDeleteByQuadIds(quadIds) {
138
+ return {
139
+ sql: `DELETE FROM chunks WHERE quad_id IN (${generatePlaceholders(quadIds.length)})${this.worldId ? " AND world_id = ?" : ""}`,
140
+ args: this.worldId ? [...quadIds, this.worldId] : quadIds
141
+ };
142
+ }
143
+ /**
144
+ * buildChunkVectorLookupByQuadIds selects the fields needed to recompute
145
+ * deterministic vector ids (`buildSearchResultId`) for the chunk rows of
146
+ * the given quads — used by the projector to delete stale vectors from the
147
+ * outside-D1 vector index before refreshing chunk rows.
148
+ */
149
+ buildChunkVectorLookupByQuadIds(quadIds) {
150
+ return {
151
+ sql: `SELECT quad_id, subject, predicate, graph, value FROM chunks WHERE quad_id IN (${generatePlaceholders(quadIds.length)})${this.worldId ? " AND world_id = ?" : ""}`,
152
+ args: this.worldId ? [...quadIds, this.worldId] : quadIds
153
+ };
154
+ }
155
+ sanitizeFtsQuery(query) {
156
+ return sanitizeFtsQuery(query);
157
+ }
158
+ buildSearchQuery(request, searchBuildOptions) {
159
+ return buildD1KeywordSearchStatement(request, searchBuildOptions.limit, this.worldId);
160
+ }
161
+ };
162
+ // src/cloudflare/search-index/vector-sync-report.ts
163
+ const MAX_ERRORS = 5;
164
+ /** emptyVectorSyncReport starts a report for a pass with vector sync on or off. */
165
+ function emptyVectorSyncReport(enabled) {
166
+ return {
167
+ enabled,
168
+ attempted: 0,
169
+ upserted: 0,
170
+ failedUpserts: 0,
171
+ embeddingFailures: 0,
172
+ staleDeleteFailures: 0,
173
+ errors: []
174
+ };
175
+ }
176
+ /** mergeVectorSyncReports sums two reports (e.g. across reindex pages). */
177
+ function mergeVectorSyncReports(left, right) {
178
+ return {
179
+ enabled: left.enabled || right.enabled,
180
+ attempted: left.attempted + right.attempted,
181
+ upserted: left.upserted + right.upserted,
182
+ failedUpserts: left.failedUpserts + right.failedUpserts,
183
+ embeddingFailures: left.embeddingFailures + right.embeddingFailures,
184
+ staleDeleteFailures: left.staleDeleteFailures + right.staleDeleteFailures,
185
+ errors: [...left.errors, ...right.errors].slice(0, MAX_ERRORS)
186
+ };
187
+ }
188
+ /** vectorSyncSucceeded is true when nothing was dropped or left stale. */
189
+ function vectorSyncSucceeded(report) {
190
+ return report.failedUpserts === 0 && report.embeddingFailures === 0 && report.staleDeleteFailures === 0;
191
+ }
192
+ /** recordVectorSyncError appends a failure message, keeping the list short. */
193
+ function recordVectorSyncError(report, stage, error) {
194
+ if (report.errors.length >= MAX_ERRORS) return;
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ report.errors.push(`${stage}: ${message}`);
197
+ }
198
+ /**
199
+ * logVectorSyncDrift emits one structured error when a pass left the vector
200
+ * index out of step with D1, so drift is visible in Worker logs.
201
+ */
202
+ function logVectorSyncDrift(report, context) {
203
+ if (!report.enabled || vectorSyncSucceeded(report)) return;
204
+ console.error("[vector-sync] vector index drifted from D1; run reindex to repair", JSON.stringify({
205
+ worldId: context.worldId ?? null,
206
+ operation: context.operation,
207
+ attempted: report.attempted,
208
+ upserted: report.upserted,
209
+ failedUpserts: report.failedUpserts,
210
+ embeddingFailures: report.embeddingFailures,
211
+ staleDeleteFailures: report.staleDeleteFailures,
212
+ errors: report.errors
213
+ }));
214
+ }
215
+ // src/cloudflare/search-index/project-search-chunks-vectors.ts
216
+ /**
217
+ * syncVectors upserts embedded vectors into the outside-D1 vector index and
218
+ * reports the outcome. A failed upsert does not throw (the D1 write already
219
+ * committed); it is counted so callers and logs can see the drift.
220
+ */
221
+ async function syncVectors(options, entries) {
222
+ const report = emptyVectorSyncReport(vectorSyncEnabled(options));
223
+ if (entries.length === 0 || !options.vectorSearch) return report;
224
+ report.attempted = entries.length;
225
+ try {
226
+ await options.vectorSearch.upsert(entries);
227
+ report.upserted = entries.length;
228
+ } catch (error) {
229
+ report.failedUpserts = entries.length;
230
+ recordVectorSyncError(report, "upsert", error);
231
+ }
232
+ return report;
233
+ }
234
+ /**
235
+ * purgeWorldVectors deletes every vector the configured index holds for this
236
+ * client's world (worlds-cloudflare#71 item 3). Used by replace-import wipes
237
+ * and by reindex so vectors for quads that no longer exist stop surfacing in
238
+ * semantic results — vector ids derive from chunk content, which is gone by
239
+ * the time a wipe has run, so ids-targeted deletion is impossible here.
240
+ * A failure leaves stale vectors behind; it is counted, not thrown.
241
+ */
242
+ async function purgeWorldVectors(options) {
243
+ const report = emptyVectorSyncReport(vectorSyncEnabled(options));
244
+ if (!options.vectorSearch || !options.embeddingService) return report;
245
+ try {
246
+ await options.vectorSearch.deleteAll();
247
+ } catch (error) {
248
+ report.staleDeleteFailures += 1;
249
+ recordVectorSyncError(report, "purge-world", error);
250
+ }
251
+ return report;
252
+ }
253
+ /**
254
+ * deleteStaleVectors removes vectors for chunk rows being refreshed, computed
255
+ * deterministically from the chunk quad ids before the D1 rows are replaced.
256
+ * A failure leaves stale vectors behind; it is counted, not thrown.
257
+ */
258
+ async function deleteStaleVectors(options, quadIds, chunkSize) {
259
+ const report = emptyVectorSyncReport(vectorSyncEnabled(options));
260
+ if (!options.vectorSearch || !options.embeddingService) return report;
261
+ for (let index = 0; index < quadIds.length; index += chunkSize) {
262
+ const quadIdBatch = quadIds.slice(index, index + chunkSize);
263
+ const ids = [];
264
+ try {
265
+ const resultSet = await options.connection.execute(options.searchQueryBuilder.buildChunkVectorLookupByQuadIds(quadIdBatch));
266
+ for (const row of resultSet.rows) ids.push(await buildSearchResultId$1({
267
+ subject: String(row.subject),
268
+ predicate: String(row.predicate),
269
+ graph: String(row.graph),
270
+ text: String(row.value)
271
+ }));
272
+ if (ids.length > 0) await options.vectorSearch.deleteByIds(ids);
273
+ } catch (error) {
274
+ report.staleDeleteFailures += Math.max(ids.length, 1);
275
+ recordVectorSyncError(report, "delete-stale", error);
276
+ }
277
+ }
278
+ return report;
279
+ }
280
+ // src/cloudflare/search-index/d1-vector-sync.ts
281
+ /**
282
+ * D1VectorSync keeps the outside-D1 vector index (Vectorize) in step with the
283
+ * chunk rows the shared commit core writes to D1. D1 batches and Vectorize
284
+ * writes cannot share a transaction, so the vectors are synced after the D1
285
+ * write lands: a failure there is counted and logged as drift, never thrown
286
+ * (D1 stays the source of truth and a reindex repairs it).
287
+ */
288
+ var D1VectorSync = class {
289
+ options;
290
+ /** report accumulates everything this sync did to the vector index. */
291
+ report;
292
+ pending = [];
293
+ constructor(options) {
294
+ this.options = options;
295
+ this.report = emptyVectorSyncReport(vectorSyncEnabled(options));
296
+ }
297
+ /** collect remembers the vectors of chunk rows the core just built. */
298
+ collect = (rows) => {
299
+ if (!this.report.enabled) return;
300
+ for (const row of rows) if (row.vector) this.pending.push(row);
301
+ };
302
+ /** flush upserts the collected vectors into the outside-D1 index. */
303
+ async flush() {
304
+ const rows = this.pending.splice(0);
305
+ const entries = [];
306
+ for (const { chunk, vector } of rows) {
307
+ const { subject, predicate, graph, value } = chunk;
308
+ entries.push({
309
+ id: await buildSearchResultId$1({
310
+ subject,
311
+ predicate,
312
+ graph,
313
+ text: value
314
+ }),
315
+ vector: new Float32Array(vector),
316
+ metadata: {
317
+ ...this.options.worldId ? { world_id: this.options.worldId } : {},
318
+ subject,
319
+ predicate,
320
+ graph,
321
+ value
322
+ }
323
+ });
324
+ }
325
+ this.merge(await syncVectors(this.options, entries));
326
+ }
327
+ /**
328
+ * beforePage runs before each page of a rebuild: the previous page is
329
+ * fully written by now, so its vectors sync, and the vectors of the chunk
330
+ * rows this page is about to replace are removed.
331
+ */
332
+ beforePage = async (quads) => {
333
+ await this.flush();
334
+ await this.deleteStale(hashQuads(quads));
335
+ };
336
+ /** purgeWorld deletes every vector of this world from the outside-D1 index. */
337
+ async purgeWorld() {
338
+ this.merge(await purgeWorldVectors(this.options));
339
+ }
340
+ /** deleteStale removes the vectors of the chunk rows about to be replaced for these quads. */
341
+ async deleteStale(quadIds) {
342
+ const chunkSize = effectiveLookupChunkSize(this.options.maxLookupChunkSize, Boolean(this.options.worldId));
343
+ this.merge(await deleteStaleVectors(this.options, quadIds, chunkSize));
344
+ }
345
+ /** logDrift logs one structured error when this sync left the index out of step with D1. */
346
+ logDrift(operation) {
347
+ logVectorSyncDrift(this.report, {
348
+ worldId: this.options.worldId,
349
+ operation
350
+ });
351
+ }
352
+ merge(report) {
353
+ this.report = mergeVectorSyncReports(this.report, report);
354
+ }
355
+ };
356
+ // src/cloudflare/search-index/rebuild-d1-search-index-from-quads.ts
357
+ /**
358
+ * rebuildD1SearchIndexFromQuads rebuilds FTS chunk rows from the `quads` table
359
+ * without re-importing graph data, through the shared `rebuildSqlSearchIndex`.
360
+ *
361
+ * Use after schema upgrades, label predicate changes, or discovery-index tuning so existing corpora pick up refreshed `fts_value`.
362
+ *
363
+ * An unscoped rebuild clears the world's chunk rows first, so rows of quads
364
+ * that no longer exist go too. With an include/exclude filter the rebuild is
365
+ * scoped: it replaces only the chunk rows of the matching quads and leaves the
366
+ * rest alone. `processedQuadCount` counts every stored quad scanned.
367
+ *
368
+ * When vector sync is on and no include/exclude filter narrows the rebuild,
369
+ * the world's vectors are purged first (worlds-cloudflare#71 item 3): quads
370
+ * removed since the last projection have no surviving D1 row to derive a
371
+ * vector id from, so a rebuild that only upserts would leave their vectors
372
+ * searchable forever. Deleting first and re-upserting makes reindex a true
373
+ * reconcile; a purge failure is counted as drift, not thrown. An embedding
374
+ * failure throws.
375
+ */
376
+ async function rebuildD1SearchIndexFromQuads(options) {
377
+ const { worldId } = options.searchQueryBuilder;
378
+ const sync = new D1VectorSync(options);
379
+ if (isFullRebuild(options)) await sync.purgeWorld();
380
+ const driver = createD1CommitDriver({
381
+ ...options,
382
+ worldId,
383
+ inferenceEnabled: options.inference?.enabled === true,
384
+ beforePage: sync.beforePage
385
+ });
386
+ const dialect = createD1CommitDialect({
387
+ searchQueryBuilder: options.searchQueryBuilder,
388
+ worldId,
389
+ lookupChunkSize: effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(worldId)),
390
+ onChunkRows: sync.collect
391
+ });
392
+ const chunkRowCount = await rebuildSqlSearchIndex(driver, dialect, toProjectionOptions(options), {
393
+ scope: {
394
+ include: options.include,
395
+ exclude: options.exclude
396
+ },
397
+ pageSize: Math.max(1, Math.floor(options.readPageSize ?? 1e3))
398
+ });
399
+ await sync.flush();
400
+ sync.logDrift("reindex");
401
+ return {
402
+ processedQuadCount: driver.processedQuadCount,
403
+ chunkRowCount,
404
+ vectorSync: sync.report
405
+ };
406
+ }
407
+ /**
408
+ * createD1SearchIndexRebuilder returns a closure that rebuilds search chunks using stable D1 dependencies.
409
+ */
410
+ function createD1SearchIndexRebuilder(dependencies) {
411
+ return () => rebuildD1SearchIndexFromQuads(dependencies);
412
+ }
413
+ // src/cloudflare/search-index/cloudflare-search-index-fusion.ts
414
+ /**
415
+ * fuseRankedLists merges the keyword and vector ranked lists into the final
416
+ * ranked result set (contract D7, hybrid factor):
417
+ *
418
+ * - Keyword-only: every hit is `rrf` with its normalized keyword rank score.
419
+ * - Vec-only (semantic): every hit is `cosine` with `max(0, cosine)`.
420
+ * - Hybrid: hits present in BOTH lists score the mean of their normalized
421
+ * keyword and vector ranks (rank 0 in both → 1.0) as `rrf` (fused
422
+ * reciprocal rank); hits only in the vector list stay `cosine`; hits only
423
+ * in the keyword list stay `rrf`. Final order is score-descending (stable).
424
+ *
425
+ * `mode` reports what actually ran so consumers never assume semantic.
426
+ */
427
+ function fuseRankedLists(keywordHits, vectorHits) {
428
+ if (vectorHits.length === 0) return {
429
+ mode: "keyword",
430
+ results: keywordHits.map((hit) => ({
431
+ score: hit.score,
432
+ result: hit
433
+ }))
434
+ };
435
+ if (keywordHits.length === 0) return {
436
+ mode: "semantic",
437
+ results: vectorHits.map((hit) => ({
438
+ score: clampCosine(hit.score),
439
+ result: hitToSearchResult(hit)
440
+ }))
441
+ };
442
+ const keywordById = new Map(keywordHits.map((hit) => [hit.id, hit]));
443
+ const results = [];
444
+ for (let vectorRank = 0; vectorRank < vectorHits.length; vectorRank++) {
445
+ const hit = vectorHits[vectorRank];
446
+ const keywordMatch = keywordById.get(hit.id);
447
+ if (keywordMatch) {
448
+ const fused = (keywordMatch.score + normalizeRrfScore(vectorRank)) / 2;
449
+ results.push({
450
+ score: fused,
451
+ result: {
452
+ id: keywordMatch.id,
453
+ subject: keywordMatch.subject,
454
+ predicate: keywordMatch.predicate,
455
+ graph: keywordMatch.graph,
456
+ text: keywordMatch.text,
457
+ score: fused,
458
+ scoreType: "rrf"
459
+ }
460
+ });
461
+ keywordById.delete(hit.id);
462
+ } else results.push({
463
+ score: clampCosine(hit.score),
464
+ result: hitToSearchResult(hit)
465
+ });
466
+ }
467
+ for (const keywordOnly of keywordById.values()) results.push({
468
+ score: keywordOnly.score,
469
+ result: keywordOnly
470
+ });
471
+ results.sort((a, b) => b.score - a.score);
472
+ return {
473
+ mode: "hybrid",
474
+ results
475
+ };
476
+ }
477
+ function hitToSearchResult(hit) {
478
+ return {
479
+ id: hit.id,
480
+ subject: hit.metadata?.subject ?? "",
481
+ predicate: hit.metadata?.predicate ?? "",
482
+ graph: hit.metadata?.graph ?? "",
483
+ text: hit.metadata?.value ?? "",
484
+ score: clampCosine(hit.score),
485
+ scoreType: "cosine"
486
+ };
487
+ }
488
+ /** Vectorize returns cosine similarity in [-1, 1]; clamp to the contract [0, 1]. */
489
+ function clampCosine(score) {
490
+ return Math.max(0, Math.min(1, score));
491
+ }
492
+ // src/cloudflare/search-index/cloudflare-search-index.ts
493
+ /**
494
+ * CloudflareSearchIndex implements the query pathway over D1's FTS5
495
+ * external-content `chunks_fts` table fused with an outside-D1 vector index
496
+ * (Phase C): keyword matches rank via reciprocal rank fusion against the
497
+ * reference constant; when an embeddingService + Vectorize-bound
498
+ * vectorSearch are wired, the query is embedded and the two lists fuse.
499
+ *
500
+ * Ranked semantics come from the reported `mode` — hybrid (both lists),
501
+ * semantic (vector-only), keyword (FTS-only). No JS cosine fallback exists
502
+ * per the cloudflare architecture decision (worlds-sdk-ts#63); any vector
503
+ * failure degrades gracefully to keyword-only.
504
+ */
505
+ var CloudflareSearchIndex = class {
506
+ options;
507
+ constructor(options) {
508
+ this.options = options;
509
+ }
510
+ /**
511
+ * search executes a keyword and/or vector query against the index and fuses
512
+ * the ranked lists on the contract's deterministic result ids.
513
+ */
514
+ async search(request) {
515
+ if (this.options.embeddingService && !this.options.vectorSearch) console.warn("[Search Warning] embeddingService configured without a vector index (Phase C); running keyword-only.");
516
+ const candidateCount = this.options.candidateCount ?? this.options.limit ?? 100;
517
+ const { sql, args } = this.options.searchQueryBuilder.buildSearchQuery(request, { limit: candidateCount });
518
+ const resultSet = await this.options.connection.execute({
519
+ sql,
520
+ args
521
+ });
522
+ const keywordHits = [];
523
+ for (let rowIndex = 0; rowIndex < resultSet.rows.length; rowIndex++) {
524
+ const row = resultSet.rows[rowIndex];
525
+ const searchResultBase = {
526
+ subject: String(row["subject"]),
527
+ predicate: String(row["predicate"]),
528
+ graph: String(row["graph"]),
529
+ text: String(row["value"])
530
+ };
531
+ keywordHits.push({
532
+ id: await buildSearchResultId$1(searchResultBase),
533
+ ...searchResultBase,
534
+ score: normalizeRrfScore(rowIndex),
535
+ scoreType: "rrf",
536
+ rankIndex: rowIndex
537
+ });
538
+ }
539
+ let vectorHits = [];
540
+ if (this.options.embeddingService && this.options.vectorSearch) try {
541
+ const embedded = await this.options.embeddingService.embed([request.query]);
542
+ const queryVector = embedded[0] ? new Float32Array(embedded[0]) : void 0;
543
+ if (queryVector) vectorHits = await this.options.vectorSearch.query(Array.from(queryVector), {
544
+ topK: candidateCount,
545
+ ...this.options.worldId ? { filter: { world_id: this.options.worldId } } : {}
546
+ });
547
+ } catch (error) {
548
+ console.warn("[Search Warning] vector query failed; falling back to keyword-only", error);
549
+ }
550
+ const { results, mode } = fuseRankedLists(keywordHits, vectorHits);
551
+ const minScore = request.minScore ?? 0;
552
+ return {
553
+ mode,
554
+ results: results.filter(({ score }) => score >= minScore).map(({ result }) => result)
555
+ };
556
+ }
557
+ /**
558
+ * reindex rebuilds FTS chunk rows (and, when wired, re-embeds and re-upserts
559
+ * vectors) from durable quads without re-importing graph data. It is the
560
+ * repair path for vector drift; `vectorSync` reports what reached the index.
561
+ */
562
+ async reindex(request) {
563
+ const textSplitter = this.options.textSplitter;
564
+ if (!textSplitter) throw new Error("CloudflareSearchIndex reindex requires textSplitter in CloudflareSearchIndexOptions");
565
+ const include = request?.include ?? this.options.include;
566
+ const exclude = request?.exclude ?? this.options.exclude;
567
+ return await rebuildD1SearchIndexFromQuads({
568
+ ...this.options,
569
+ textSplitter,
570
+ include,
571
+ exclude,
572
+ readPageSize: request?.readPageSize
573
+ });
574
+ }
575
+ };
576
+ // src/cloudflare/search-index/d1-search-index-projector.ts
577
+ /**
578
+ * D1SearchIndexProjector holds what search projection needs beyond the shared
579
+ * SQL commit core: the chunking and embedding options, the outside-D1 vector
580
+ * sync, and the full rebuild. The commit itself runs in `commitD1Patch`.
581
+ */
582
+ var D1SearchIndexProjector = class {
583
+ options;
584
+ constructor(options) {
585
+ this.options = options;
586
+ }
587
+ /** projection is the shared core's chunking and embedding configuration. */
588
+ get projection() {
589
+ return toProjectionOptions(this.options);
590
+ }
591
+ /** createVectorSync starts a sync of chunk-row vectors to the outside-D1 index for one commit or rebuild. */
592
+ createVectorSync() {
593
+ return new D1VectorSync(this.options);
594
+ }
595
+ /**
596
+ * reindexAll rebuilds the entire search index directly from durable quads.
597
+ */
598
+ async reindexAll() {
599
+ await rebuildD1SearchIndexFromQuads({ ...this.options });
600
+ }
601
+ /**
602
+ * purgeVectors deletes every vector this world holds in the outside-D1
603
+ * vector index (worlds-cloudflare#71 item 3).
604
+ */
605
+ async purgeVectors() {
606
+ return await purgeWorldVectors(this.options);
607
+ }
608
+ };
609
+ export { createD1SearchIndexRebuilder as a, emptyVectorSyncReport as c, recordVectorSyncError as d, vectorSyncSucceeded as f, sanitizeFtsQuery as h, CloudflareSearchIndex as i, logVectorSyncDrift as l, RRF_REFERENCE_CONSTANT as m, buildSearchResultId as n, rebuildD1SearchIndexFromQuads as o, D1SearchQueryBuilder as p, D1SearchIndexProjector as r, D1VectorSync as s, buildChunkFtsValue as t, mergeVectorSyncReports as u };
@@ -0,0 +1,2 @@
1
+ import { C as D1SearchQueryBuilder, E as sanitizeFtsQuery, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, y as recordVectorSyncError } from "./mod-Do_hSIzo.js";
2
+ export { type BuildSearchResultIdOptions, type CloudflareReindexResponse, CloudflareSearchIndex, type CloudflareSearchIndexOptions, D1SearchIndexProjector, D1SearchIndexProjectorOptions, D1SearchQueryBuilder, D1SearchQueryBuilderOptions, D1VectorSync, type ProjectSearchChunksOptions, RRF_REFERENCE_CONSTANT, ReadProjectSearchChunksOptions, RebuildD1SearchIndexFromQuadsResult, VectorSyncReport, buildChunkFtsValue, buildSearchResultId, createD1SearchIndexRebuilder, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, vectorSyncSucceeded };
@@ -0,0 +1 @@
1
+ export { i as CloudflareSearchIndex, r as D1SearchIndexProjector, p as D1SearchQueryBuilder, s as D1VectorSync, m as RRF_REFERENCE_CONSTANT, t as buildChunkFtsValue, n as buildSearchResultId, a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, l as logVectorSyncDrift, u as mergeVectorSyncReports, o as rebuildD1SearchIndexFromQuads, d as recordVectorSyncError, h as sanitizeFtsQuery, f as vectorSyncSucceeded } from "./search-index-DVbbsc3z.js";