import sqlite3InitModule from "sqlite-wasm-vec"; import sqliteWasmUrl from "sqlite-wasm-vec/sqlite3.wasm?url"; import { buildSearchQuery } from "../lib/searchQuery"; /** * Search index worker. Keeps `index.sqlite` (OPFS when cross-origin isolation * allows it, memory otherwise) with FTS5 plus an optional sqlite-vec table * for semantic search. The main thread sends flattened blocks (see the wasm * `flattenDocument` pass) and asks queries here. All text search state lives * in this worker and nowhere else. */ export interface IndexedBlock { kind: string; plain: string; /** Wasm `FlattenedBlock` fields are snake_case. Keep them as sent. */ range_start: number; range_end: number; /** raw byte offset per plain byte, as a plain number array over the wire */ map: number[]; } export interface SearchHit { docId: string; path: string; title: string; blockIndex: number; kind: string; plain: string; rangeStart: number; rangeEnd: number; /** FTS offsets within plain: [start, end] pairs. */ offsets: Array<[number, number]>; bm25: number; semantic?: number; } export interface IndexStatus { mode: "opfs" | "memory"; docs: number; blocks: number; vecReady: boolean; } type WorkerRequest = | { type: "init"; dbName: string } | { type: "upsert"; docId: string; path: string; title: string; updatedAt: number; contentHash: string; blocks: IndexedBlock[]; } | { type: "delete"; docId: string } | { type: "query"; text: string; limit: number } | { type: "semantic-query"; vector: number[]; limit: number } | { type: "put-vector"; blockId: number; vector: number[] } | { type: "vectors-for"; docId: string } | { type: "indexed" } | { type: "status" } | { type: "wipe" }; type WorkerResponse = { id?: number; type: "status" | "query" | "semantic-query" | "vectors" | "upserted" | "indexed" | "error"; status?: IndexStatus; hits?: SearchHit[]; /** The strict query found nothing and these hits use the OR fallback. */ loose?: boolean; blockIds?: number[]; docId?: string; pages?: Array<{ docId: string; updatedAt: number; hash: string }>; vectors?: Array<{ blockId: number; vector: number[] }>; /** Request type that failed. Lets `queryWorker` resolve its callers. */ requestType?: string; error?: string; }; type Sqlite3 = Awaited>; // sqlite3.oo1.DB is the constructor. The instance is what we keep. type SqliteDb = InstanceType; let sqlite3: Sqlite3 | undefined; let db: SqliteDb | undefined; let mode: "opfs" | "memory" = "memory"; let vecReady = false; /** bge-small embedding width. The vec table is declared with it. */ const VECTOR_DIM = 384; /** Blocks returned per page, so a page with many matches does not fill the list. */ const MAX_HITS_PER_PAGE = 3; async function ensureDb(dbName: string): Promise { if (db) return; // Ask Vite for the wasm asset URL instead of letting the package resolve it. // Vite's wasm plugin serves `.wasm` module ids as wasm-bindgen glue, which // the Emscripten loader cannot instantiate. The query makes the dev server // return the raw binary. const binary = `${sqliteWasmUrl}${sqliteWasmUrl.includes("?") ? "&" : "?"}binary`; sqlite3 = await sqlite3InitModule({ locateFile: () => binary }); // OpfsDb is installed only when the OPFS VFS is available (see the // package docs). `"opfs" in sqlite3` never matches because the property // lives on sqlite3.oo1. const hasOpfs = "OpfsDb" in sqlite3.oo1; mode = hasOpfs ? "opfs" : "memory"; const opened = hasOpfs ? new sqlite3.oo1.OpfsDb(`/typbase/${dbName}.sqlite3`) : new sqlite3.oo1.DB(`:memory:`); db = opened; opened.exec(` CREATE TABLE IF NOT EXISTS pages( doc_id TEXT PRIMARY KEY, path TEXT NOT NULL, title TEXT NOT NULL, updated_at INTEGER NOT NULL, content_hash TEXT NOT NULL DEFAULT '' ); CREATE TABLE IF NOT EXISTS blocks( id INTEGER PRIMARY KEY AUTOINCREMENT, doc_id TEXT NOT NULL, block_index INTEGER NOT NULL, kind TEXT NOT NULL, plain TEXT NOT NULL, range_start INTEGER NOT NULL, range_end INTEGER NOT NULL, map BLOB NOT NULL ); CREATE INDEX IF NOT EXISTS blocks_doc ON blocks(doc_id); CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(plain); `); // The index is a rebuildable cache. Existing databases predate the content // hash column, so add it and let the startup check reindex their pages. const columns = opened.selectArrays("PRAGMA table_info(pages)"); if (!columns.some((row) => row[1] === "content_hash")) { opened.exec("ALTER TABLE pages ADD COLUMN content_hash TEXT NOT NULL DEFAULT ''"); } try { // The OPFS VFS has no shared memory, so WAL is not available there. The // default journal is fine for a rebuildable cache. Keep this separate // from the schema so a refusal cannot take the whole index down. opened.exec("PRAGMA journal_mode = WAL"); } catch { // Ignore: journal mode is an optimization, not a requirement. } try { opened.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS vec USING vec0(embedding float[384])`); vecReady = true; } catch { // sqlite-vec unavailable in this build: semantic search degrades to FTS. vecReady = false; } } async function handle(request: WorkerRequest): Promise { if (request.type === "init") { await ensureDb(request.dbName); post({ type: "status", status: status() }); return; } if (!db) throw new Error("Index worker not initialized"); switch (request.type) { case "upsert": { const blockIds: number[] = []; db.exec("BEGIN"); try { db.exec("DELETE FROM fts WHERE rowid IN (SELECT id FROM blocks WHERE doc_id = ?)", { bind: [request.docId], }); // Vectors key on the block row id, so the old ones have to go with // the rows or they pile up and shadow real hits in semantic queries. db.exec("DELETE FROM vec WHERE rowid IN (SELECT id FROM blocks WHERE doc_id = ?)", { bind: [request.docId], }); db.exec("DELETE FROM blocks WHERE doc_id = ?", { bind: [request.docId], }); db.exec( "INSERT INTO pages(doc_id, path, title, updated_at, content_hash) VALUES(?, ?, ?, ?, ?) " + "ON CONFLICT(doc_id) DO UPDATE SET path=excluded.path, title=excluded.title, updated_at=excluded.updated_at, content_hash=excluded.content_hash", { bind: [ request.docId, request.path, request.title, request.updatedAt, request.contentHash, ], }, ); for (const [i, block] of request.blocks.entries()) { if (!block.plain.trim()) { // Keep blockIds aligned with the request. 0 means "not stored". blockIds.push(0); continue; } const ids = db.selectArrays( "INSERT INTO blocks(doc_id, block_index, kind, plain, range_start, range_end, map) VALUES(?, ?, ?, ?, ?, ?, ?) RETURNING id", [ request.docId, i, block.kind, block.plain, block.range_start, block.range_end, packMap(block.map), ], ); const rowid = Number(ids[0]?.[0]); blockIds.push(rowid > 0 ? rowid : 0); if (rowid > 0) { db.exec("INSERT INTO fts(rowid, plain) VALUES(?, ?)", { bind: [rowid, block.plain], }); } } db.exec("COMMIT"); post({ type: "upserted", docId: request.docId, blockIds }); } catch (error) { db.exec("ROLLBACK"); throw error; } break; } case "delete": { db.exec("DELETE FROM fts WHERE rowid IN (SELECT id FROM blocks WHERE doc_id = ?)", { bind: [request.docId], }); db.exec("DELETE FROM vec WHERE rowid IN (SELECT id FROM blocks WHERE doc_id = ?)", { bind: [request.docId], }); db.exec("DELETE FROM blocks WHERE doc_id = ?", { bind: [request.docId] }); db.exec("DELETE FROM pages WHERE doc_id = ?", { bind: [request.docId] }); break; } case "query": { const parsed = buildSearchQuery(request.text); if (!parsed) { post({ type: "query", hits: [] }); break; } let hits = queryHits(parsed.strict, request.limit); let loose = false; if (hits.length === 0 && parsed.loose) { hits = queryHits(parsed.loose, request.limit); loose = hits.length > 0; } post({ type: "query", hits, loose }); break; } case "semantic-query": { if (!vecReady) { post({ type: "semantic-query", hits: [] }); break; } const vectorJson = JSON.stringify(request.vector); const rows = db.selectArrays( "SELECT rowid, distance FROM vec WHERE embedding MATCH ? ORDER BY distance LIMIT ?", [vectorJson, request.limit], ); const hits: SearchHit[] = []; for (const row of rows) { const [blockId, distance] = row as [number, number]; const block = db.selectArrays( "SELECT b.doc_id, b.block_index, b.kind, b.plain, b.range_start, b.range_end, p.path, p.title " + "FROM blocks b JOIN pages p ON p.doc_id = b.doc_id WHERE b.id = ?", [blockId], ); const m = block[0]; if (!m) continue; hits.push({ docId: String(m[0]), path: String(m[6]), title: String(m[7]), blockIndex: Number(m[1]), kind: String(m[2]), plain: String(m[3]), rangeStart: Number(m[4]), rangeEnd: Number(m[5]), offsets: [], bm25: 0, semantic: 1 - Number(distance), }); } post({ type: "semantic-query", hits }); break; } case "put-vector": { if (!vecReady) break; if (request.vector.length !== VECTOR_DIM) { // Without this the insert fails deep in sqlite-vec and the palette // shows the raw SQLITE_ERROR instead of what went wrong. throw new Error( `Embedding model returned ${request.vector.length} dimensions; the index expects ${VECTOR_DIM}.`, ); } db.exec("DELETE FROM vec WHERE rowid = ?", { bind: [request.blockId] }); db.exec("INSERT INTO vec(rowid, embedding) VALUES(?, ?)", { bind: [request.blockId, JSON.stringify(request.vector)], }); break; } case "vectors-for": { if (!vecReady) { post({ type: "vectors", vectors: [] }); break; } const rows = db.selectArrays( `SELECT b.id, v.embedding FROM blocks b JOIN vec v ON v.rowid = b.id WHERE b.doc_id = ?`, [request.docId], ); const vectors = rows.map((row) => { const raw = String(row[1]); const vector = JSON.parse(raw) as number[]; return { blockId: Number(row[0]), vector }; }); post({ type: "vectors", vectors }); break; } case "indexed": { const rows = db.selectArrays("SELECT doc_id, updated_at, content_hash FROM pages"); post({ type: "indexed", pages: rows.map((row) => ({ docId: String(row[0]), updatedAt: Number(row[1]), hash: String(row[2] ?? ""), })), }); break; } case "wipe": { db.exec("DELETE FROM fts; DELETE FROM blocks; DELETE FROM pages; DELETE FROM vec;"); break; } case "status": { post({ type: "status", status: status() }); break; } } } /** Hits for one MATCH expression, at most three blocks per page. */ function queryHits(match: string, limit: number): SearchHit[] { // `bm25()` cannot run inside a window function, so the score is computed in // the CTE and the row number reads it from there. const rows = db!.selectArrays( `WITH scored AS ( SELECT b.doc_id, b.block_index, b.kind, b.plain, b.range_start, b.range_end, p.path, p.title, bm25(fts) AS score, highlight(fts, 0, char(2), char(3)) AS marked FROM fts JOIN blocks b ON b.id = fts.rowid JOIN pages p ON p.doc_id = b.doc_id WHERE fts MATCH ? ) SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY doc_id ORDER BY score) AS rn FROM scored ) WHERE rn <= ? ORDER BY score LIMIT ?`, [match, MAX_HITS_PER_PAGE, limit], ); const hits: SearchHit[] = []; for (const row of rows) { const [docId, blockIndex, kind, plain, rangeStart, rangeEnd, path, title, score, marked] = row as [string, number, string, string, number, number, string, string, number, string]; hits.push({ docId: String(docId), path: String(path), title: String(title), blockIndex: Number(blockIndex), kind: String(kind), plain: String(plain), rangeStart: Number(rangeStart), rangeEnd: Number(rangeEnd), offsets: offsetsFromHighlight(String(marked)), bm25: Number(score), }); } return hits; } function status(): IndexStatus { if (!db) return { mode, docs: 0, blocks: 0, vecReady }; const pages = db.selectArrays("SELECT COUNT(*) FROM pages")[0]?.[0] ?? 0; const blocks = db.selectArrays("SELECT COUNT(*) FROM blocks")[0]?.[0] ?? 0; return { mode, docs: Number(pages), blocks: Number(blocks), vecReady }; } /** Match spans in `plain`, recovered from `highlight()` markers. */ function offsetsFromHighlight(marked: string): Array<[number, number]> { const open = "\u0002"; const close = "\u0003"; const offsets: Array<[number, number]> = []; let cursor = 0; while (true) { const start = marked.indexOf(open, cursor); if (start < 0) break; // Marker characters are not in the source, so subtract them from the // prefix to get the offset in `plain`. FTS offsets and the wasm byte map // both count UTF-8 bytes, so encode before measuring. const before = marked.slice(0, start).split(open).join("").split(close).join(""); const end = marked.indexOf(close, start + 1); const term = end < 0 ? marked.slice(start + 1) : marked.slice(start + 1, end); const from = utf8Length(before); offsets.push([from, from + utf8Length(term)]); cursor = end < 0 ? marked.length : end + 1; } return offsets; } const utf8 = new TextEncoder(); function utf8Length(text: string): number { return utf8.encode(text).length; } function packMap(map: number[]): Uint8Array { const buffer = new Uint8Array(new Uint32Array(map).buffer); return buffer; } function post(response: WorkerResponse): void { (self as unknown as Worker).postMessage(response); } // Requests run in order: a query that lands while `init` is still loading // sqlite waits its turn instead of failing with "not initialized". let queue: Promise = Promise.resolve(); self.addEventListener("message", (event: MessageEvent) => { queue = queue .then(() => handle(event.data)) .catch((error: unknown) => { post({ type: "error", docId: (event.data as { docId?: string }).docId, requestType: event.data.type, error: error instanceof Error ? error.message : String(error), }); }); });