@superbee/core 0.2.0-pre.52 → 0.2.0-pre.54
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/README.md +39 -1
- package/dist/backend.d.ts +9 -0
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +9 -0
- package/dist/backend.js.map +1 -1
- package/dist/body-replace-guards.d.ts +1 -1
- package/dist/body-replace-guards.d.ts.map +1 -1
- package/dist/body-replace-guards.js.map +1 -1
- package/dist/dependencies.d.ts +107 -1
- package/dist/dependencies.d.ts.map +1 -1
- package/dist/dependencies.js +160 -0
- package/dist/dependencies.js.map +1 -1
- package/dist/document-mutation.d.ts.map +1 -1
- package/dist/document-mutation.js +6 -3
- package/dist/document-mutation.js.map +1 -1
- package/dist/document-replace-rules.d.ts +44 -0
- package/dist/document-replace-rules.d.ts.map +1 -0
- package/dist/document-replace-rules.js +41 -0
- package/dist/document-replace-rules.js.map +1 -0
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +3 -2
- package/dist/engine.js.map +1 -1
- package/dist/filesystem-identity.d.ts +10 -0
- package/dist/filesystem-identity.d.ts.map +1 -1
- package/dist/filesystem-identity.js +28 -9
- package/dist/filesystem-identity.js.map +1 -1
- package/dist/hosted-transport/carrier.d.ts +3 -0
- package/dist/hosted-transport/carrier.d.ts.map +1 -1
- package/dist/hosted-transport/carrier.js +6 -1
- package/dist/hosted-transport/carrier.js.map +1 -1
- package/dist/hosted-transport/whole-document-transport.d.ts.map +1 -1
- package/dist/hosted-transport/whole-document-transport.js +2 -0
- package/dist/hosted-transport/whole-document-transport.js.map +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/kind-authoring.d.ts +2 -0
- package/dist/kind-authoring.d.ts.map +1 -1
- package/dist/kind-authoring.js +31 -3
- package/dist/kind-authoring.js.map +1 -1
- package/dist/kinds.js +3 -3
- package/dist/kinds.js.map +1 -1
- package/dist/link-add.d.ts +81 -0
- package/dist/link-add.d.ts.map +1 -0
- package/dist/link-add.js +94 -0
- package/dist/link-add.js.map +1 -0
- package/dist/local-search-index.d.ts +62 -0
- package/dist/local-search-index.d.ts.map +1 -0
- package/dist/local-search-index.js +690 -0
- package/dist/local-search-index.js.map +1 -0
- package/dist/okf-authoring.d.ts +1 -1
- package/dist/okf-authoring.d.ts.map +1 -1
- package/dist/okf-authoring.js +10 -3
- package/dist/okf-authoring.js.map +1 -1
- package/dist/recipe-lifecycle/evolution.d.ts.map +1 -1
- package/dist/recipe-lifecycle/evolution.js +5 -2
- package/dist/recipe-lifecycle/evolution.js.map +1 -1
- package/dist/recipe-lifecycle/install.d.ts +4 -3
- package/dist/recipe-lifecycle/install.d.ts.map +1 -1
- package/dist/recipe-lifecycle/install.js +22 -20
- package/dist/recipe-lifecycle/install.js.map +1 -1
- package/dist/search-index.d.ts +7 -0
- package/dist/search-index.d.ts.map +1 -0
- package/dist/search-index.js +7 -0
- package/dist/search-index.js.map +1 -0
- package/dist/source-profiles/index.d.ts +1 -1
- package/dist/source-profiles/index.js +1 -1
- package/package.json +13 -1
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The local search index: a `SearchSource` whose index lives in one SQLite file outside the bundle,
|
|
3
|
+
* through Node's built-in `node:sqlite`. It stores what `searchRowText` derives from each document
|
|
4
|
+
* (per-field token texts in a contentless FTS5 table, plus the fields ranking and facets read) and
|
|
5
|
+
* never the bodies. Core's engine still ranks, pages and facets; this source answers `evidence()`
|
|
6
|
+
* and `text()`, so on the same corpus it answers what `searchSourceFromBackend` answers.
|
|
7
|
+
*
|
|
8
|
+
* Every `evidence()` call first brings the index up to date: the bundle is listed, each file's
|
|
9
|
+
* content stamp is compared with the one recorded, and only files whose stamp moved, was never
|
|
10
|
+
* trusted, or was recorded before it settled are read again. A read whose version is unchanged
|
|
11
|
+
* only records the new stamp. The index holds no corpus-size limit; `maxTermsPerDocument` still
|
|
12
|
+
* skips and counts an over-long document.
|
|
13
|
+
*
|
|
14
|
+
* The file is derived state: a missing, corrupt, foreign, older-schema or other-text-version file is
|
|
15
|
+
* rebuilt. Several processes may share it: SQLite's WAL journal and a busy timeout serialize the
|
|
16
|
+
* short write transactions, and each search reads one consistent snapshot.
|
|
17
|
+
*/
|
|
18
|
+
import { mkdir, open as openFile, realpath, unlink } from "node:fs/promises";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { FilesystemBackend, filesystemDocumentStamp } from "./backend.js";
|
|
21
|
+
import { isConventionRecord } from "./convention-record.js";
|
|
22
|
+
import { readManyExisting } from "./document-scan.js";
|
|
23
|
+
import { readBundleOkfVersion } from "./engine.js";
|
|
24
|
+
import { headsDigest } from "./heads-digest.js";
|
|
25
|
+
import { sha256HexOfUtf8 } from "./sha256.js";
|
|
26
|
+
import { SEARCH_LIMITS, SEARCH_MATCH_FIELDS, SIGNAL_INTERVAL, documentDescription, documentTags, documentTitle, documentType, } from "./search/contract.js";
|
|
27
|
+
import { stopIfAsked } from "./search/errors.js";
|
|
28
|
+
import { canonicalJson, codeUnitCompare } from "./search/identity.js";
|
|
29
|
+
import { searchRowText, textVersion } from "./search/row-text.js";
|
|
30
|
+
/** Bumped whenever the tables below change shape; an index of another schema is rebuilt. */
|
|
31
|
+
const SCHEMA_VERSION = "1";
|
|
32
|
+
/**
|
|
33
|
+
* Names what an index file was built by: this file's schema and `textVersion()` (the ranking
|
|
34
|
+
* algorithm, the text revision and the runtime's normalizer fingerprint). Two builds with different
|
|
35
|
+
* keys cannot share a file; put the key in the index file name so two tool versions or two Node
|
|
36
|
+
* versions sharing a state folder each keep their own index instead of rebuilding each other's.
|
|
37
|
+
* Sixteen lowercase hex characters. The file still records and checks these inputs itself.
|
|
38
|
+
*/
|
|
39
|
+
export function localSearchIndexFileKey() {
|
|
40
|
+
return sha256HexOfUtf8(`local-search-index\u0000${SCHEMA_VERSION}\u0000${textVersion()}`).slice(0, 16);
|
|
41
|
+
}
|
|
42
|
+
/** Documents read and derived between cancellation checks and memory bounds. */
|
|
43
|
+
const BATCH = 128;
|
|
44
|
+
/** A write transaction's most changes and most token text: each commit flushes and merges FTS5
|
|
45
|
+
* segments, so fewer, larger commits build faster, while a bound keeps the lock and memory short. */
|
|
46
|
+
const WRITE_CHANGES = 2_048;
|
|
47
|
+
const WRITE_TEXT_UNITS = 16 * 1024 * 1024;
|
|
48
|
+
/** Files stamped at once. */
|
|
49
|
+
const STAMP_CONCURRENCY = 64;
|
|
50
|
+
/** How long a search waits for another process's write transaction. */
|
|
51
|
+
const BUSY_TIMEOUT_MS = 10_000;
|
|
52
|
+
const INDEXED = 0;
|
|
53
|
+
/** Over SEARCH_LIMITS.maxTermsPerDocument body terms: counted, not searched. */
|
|
54
|
+
const OVER_TERM_CAP = 1;
|
|
55
|
+
/** Unreadable: reported in `skipped` with its reason, as the in-memory path reports it. */
|
|
56
|
+
const MALFORMED = 2;
|
|
57
|
+
/** The local index cannot be used here. A caller can fall back to the in-memory source. */
|
|
58
|
+
export class LocalSearchIndexUnavailableError extends Error {
|
|
59
|
+
reason;
|
|
60
|
+
constructor(reason, options) {
|
|
61
|
+
super(MESSAGES[reason], options);
|
|
62
|
+
this.name = "LocalSearchIndexUnavailableError";
|
|
63
|
+
this.reason = reason;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const MESSAGES = {
|
|
67
|
+
"sqlite-unavailable": "The local search index needs node:sqlite, which this Node.js does not provide.",
|
|
68
|
+
"fts5-unavailable": "The local search index needs SQLite FTS5 with contentless delete, which this Node.js's SQLite does not provide.",
|
|
69
|
+
"index-inside-bundle": "The local search index must be kept outside the bundle folder.",
|
|
70
|
+
"index-unusable": "The local search index file cannot be created or opened.",
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Opens (creating or rebuilding as needed) the index for one bundle. Throws
|
|
74
|
+
* `LocalSearchIndexUnavailableError` when this host cannot keep one.
|
|
75
|
+
*/
|
|
76
|
+
export function openLocalSearchIndex(options) {
|
|
77
|
+
return openLocalSearchIndexWith(options, {});
|
|
78
|
+
}
|
|
79
|
+
export async function openLocalSearchIndexWith(options, seams) {
|
|
80
|
+
const { backend } = options;
|
|
81
|
+
if (typeof options.root !== "string" || options.root === "")
|
|
82
|
+
throw new TypeError("openLocalSearchIndex needs the bundle root");
|
|
83
|
+
if (typeof options.indexPath !== "string" || options.indexPath === "")
|
|
84
|
+
throw new TypeError("openLocalSearchIndex needs an index path");
|
|
85
|
+
const root = path.resolve(options.root);
|
|
86
|
+
const indexPath = path.resolve(options.indexPath);
|
|
87
|
+
await refuseInsideBundle(root, indexPath);
|
|
88
|
+
let sqlite;
|
|
89
|
+
try {
|
|
90
|
+
sqlite = (await (seams.loadSqlite ?? loadSqlite)());
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
throw new LocalSearchIndexUnavailableError("sqlite-unavailable", { cause: error });
|
|
94
|
+
}
|
|
95
|
+
await prepareIndexFile(indexPath);
|
|
96
|
+
// Only a filesystem backend's files can vouch for themselves; any other backend is read each search.
|
|
97
|
+
const contentStamp = seams.contentStamp ??
|
|
98
|
+
(backend instanceof FilesystemBackend ? (id) => filesystemDocumentStamp(backend, id) : async () => undefined);
|
|
99
|
+
const busyTimeoutMs = seams.busyTimeoutMs ?? BUSY_TIMEOUT_MS;
|
|
100
|
+
let db = await openDatabase(sqlite, indexPath, busyTimeoutMs);
|
|
101
|
+
let closed = false;
|
|
102
|
+
/** Runs `body`; a corrupt or non-database file is deleted and rebuilt once. */
|
|
103
|
+
const recovering = async (body) => {
|
|
104
|
+
try {
|
|
105
|
+
return await body();
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (!isCorruption(error))
|
|
109
|
+
throw error;
|
|
110
|
+
db = await discardAndReopen(sqlite, db, indexPath, busyTimeoutMs);
|
|
111
|
+
return body();
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const source = {
|
|
115
|
+
async evidence(terms, filters, bounds, stop) {
|
|
116
|
+
if (closed)
|
|
117
|
+
throw new TypeError("the local search index is closed");
|
|
118
|
+
stopIfAsked(stop);
|
|
119
|
+
try {
|
|
120
|
+
return await recovering(async () => {
|
|
121
|
+
await refresh(db, backend, contentStamp, stop);
|
|
122
|
+
stopIfAsked(stop);
|
|
123
|
+
return readEvidence(db, terms, filters, bounds, stop);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
// A busy, full, read-only or failing index is one typed condition a caller can fall back on.
|
|
128
|
+
if (isSqliteError(error))
|
|
129
|
+
throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
async text(hits) {
|
|
134
|
+
if (closed)
|
|
135
|
+
throw new TypeError("the local search index is closed");
|
|
136
|
+
return readTexts(backend, hits);
|
|
137
|
+
},
|
|
138
|
+
close() {
|
|
139
|
+
if (closed)
|
|
140
|
+
return;
|
|
141
|
+
closed = true;
|
|
142
|
+
db.close();
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
return Object.freeze(source);
|
|
146
|
+
}
|
|
147
|
+
// ── host edges ───────────────────────────────────────────────────────────────
|
|
148
|
+
/**
|
|
149
|
+
* `node:sqlite` with its one-time ExperimentalWarning (Node 22 and 24) left unprinted. Only a
|
|
150
|
+
* warning of that type naming SQLite is dropped, and only while the module loads; every other
|
|
151
|
+
* warning still reaches `process.emitWarning`.
|
|
152
|
+
*/
|
|
153
|
+
async function loadSqlite() {
|
|
154
|
+
const emitWarning = process.emitWarning;
|
|
155
|
+
const quiet = function (warning, ...rest) {
|
|
156
|
+
const type = typeof rest[0] === "string" ? rest[0] : rest[0]?.type;
|
|
157
|
+
const name = typeof warning === "string" ? type : warning.name;
|
|
158
|
+
const message = typeof warning === "string" ? warning : warning.message;
|
|
159
|
+
if (name === "ExperimentalWarning" && /\bSQLite\b/.test(message))
|
|
160
|
+
return;
|
|
161
|
+
return emitWarning.call(this, warning, ...rest);
|
|
162
|
+
};
|
|
163
|
+
process.emitWarning = quiet;
|
|
164
|
+
try {
|
|
165
|
+
return await import("node:sqlite");
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
if (process.emitWarning === quiet)
|
|
169
|
+
process.emitWarning = emitWarning;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The real path of `target`, resolving its longest existing ancestor (the rest may not exist yet). */
|
|
173
|
+
async function realPathOf(target) {
|
|
174
|
+
const pending = [];
|
|
175
|
+
let current = target;
|
|
176
|
+
for (;;) {
|
|
177
|
+
try {
|
|
178
|
+
return path.join(await realpath(current), ...pending.reverse());
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
const parent = path.dirname(current);
|
|
182
|
+
if (parent === current)
|
|
183
|
+
throw error;
|
|
184
|
+
pending.push(path.basename(current));
|
|
185
|
+
current = parent;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async function refuseInsideBundle(root, indexPath) {
|
|
190
|
+
const fold = (value) => (process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value);
|
|
191
|
+
const bundle = fold(await realPathOf(root));
|
|
192
|
+
const index = fold(await realPathOf(indexPath));
|
|
193
|
+
const relative = path.relative(bundle, index);
|
|
194
|
+
if (relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)))
|
|
195
|
+
throw new LocalSearchIndexUnavailableError("index-inside-bundle");
|
|
196
|
+
}
|
|
197
|
+
/** Creates the folder (owner only) and an empty owner-only file, so SQLite's journals inherit its mode. */
|
|
198
|
+
async function prepareIndexFile(indexPath) {
|
|
199
|
+
try {
|
|
200
|
+
await mkdir(path.dirname(indexPath), { recursive: true, mode: 0o700 });
|
|
201
|
+
const handle = await openFile(indexPath, "a", 0o600);
|
|
202
|
+
await handle.close();
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async function openDatabase(sqlite, indexPath, busyTimeoutMs) {
|
|
209
|
+
let db;
|
|
210
|
+
try {
|
|
211
|
+
db = new sqlite.DatabaseSync(indexPath);
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
probeFts5(sqlite);
|
|
218
|
+
db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
|
|
219
|
+
await useWal(db, busyTimeoutMs);
|
|
220
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
221
|
+
return db;
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (isCorruption(error))
|
|
225
|
+
return db; // The first search discards and rebuilds it.
|
|
226
|
+
db.close();
|
|
227
|
+
if (error instanceof LocalSearchIndexUnavailableError)
|
|
228
|
+
throw error;
|
|
229
|
+
throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* WAL mode, once per file. The switch needs the file to itself, and SQLite answers it busy without
|
|
234
|
+
* waiting while another connection opens the same new file, so the switch is retried here.
|
|
235
|
+
*/
|
|
236
|
+
async function useWal(db, busyTimeoutMs) {
|
|
237
|
+
const deadline = Date.now() + busyTimeoutMs;
|
|
238
|
+
for (;;) {
|
|
239
|
+
try {
|
|
240
|
+
const { journal_mode: mode } = db.prepare("PRAGMA journal_mode").get();
|
|
241
|
+
if (mode === "wal")
|
|
242
|
+
return;
|
|
243
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
if (!isBusy(error) || Date.now() > deadline)
|
|
247
|
+
throw error;
|
|
248
|
+
await new Promise((resolve) => setTimeout(resolve, 10 + Math.random() * 40));
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** In a private in-memory database, so another process's lock on the index cannot fail it. */
|
|
253
|
+
function probeFts5(sqlite) {
|
|
254
|
+
const probe = new sqlite.DatabaseSync(":memory:");
|
|
255
|
+
try {
|
|
256
|
+
probe.exec("CREATE VIRTUAL TABLE probe USING fts5(a, content='', contentless_delete=1); CREATE VIRTUAL TABLE vocab USING fts5vocab(probe, instance);");
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
throw new LocalSearchIndexUnavailableError("fts5-unavailable", { cause: error });
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
probe.close();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
// SQLite's own result codes when the error carries them, else its fixed result-code text, so a
|
|
266
|
+
// Node whose `node:sqlite` errors have no `errcode` still classifies them.
|
|
267
|
+
const SQLITE_BUSY = 5;
|
|
268
|
+
const SQLITE_CORRUPT = 11;
|
|
269
|
+
const SQLITE_NOTADB = 26;
|
|
270
|
+
function sqliteCode(error) {
|
|
271
|
+
const code = error?.errcode;
|
|
272
|
+
return typeof code === "number" ? code & 0xff : undefined;
|
|
273
|
+
}
|
|
274
|
+
function sqliteMessage(error) {
|
|
275
|
+
const record = error;
|
|
276
|
+
return `${typeof record?.errstr === "string" ? record.errstr : ""} ${typeof record?.message === "string" ? record.message : ""}`;
|
|
277
|
+
}
|
|
278
|
+
/** An error raised by `node:sqlite` (by its code, or SQLite's result code). */
|
|
279
|
+
function isSqliteError(error) {
|
|
280
|
+
return sqliteCode(error) !== undefined || error?.code === "ERR_SQLITE_ERROR";
|
|
281
|
+
}
|
|
282
|
+
/** SQLITE_CORRUPT or SQLITE_NOTADB: the file is not an index this source can read. */
|
|
283
|
+
function isCorruption(error) {
|
|
284
|
+
const code = sqliteCode(error);
|
|
285
|
+
if (code !== undefined)
|
|
286
|
+
return code === SQLITE_CORRUPT || code === SQLITE_NOTADB;
|
|
287
|
+
return isSqliteError(error) && /database disk image is malformed|file is not a database/.test(sqliteMessage(error));
|
|
288
|
+
}
|
|
289
|
+
function isBusy(error) {
|
|
290
|
+
const code = sqliteCode(error);
|
|
291
|
+
if (code !== undefined)
|
|
292
|
+
return code === SQLITE_BUSY;
|
|
293
|
+
return isSqliteError(error) && /database is locked/.test(sqliteMessage(error));
|
|
294
|
+
}
|
|
295
|
+
async function discardAndReopen(sqlite, db, indexPath, busyTimeoutMs) {
|
|
296
|
+
try {
|
|
297
|
+
db.close();
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
// Already unusable.
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
for (const file of [indexPath, `${indexPath}-wal`, `${indexPath}-shm`])
|
|
304
|
+
await unlink(file).catch((error) => {
|
|
305
|
+
if (error.code !== "ENOENT")
|
|
306
|
+
throw error;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
// Windows refuses to delete a file another process holds open.
|
|
311
|
+
throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
|
|
312
|
+
}
|
|
313
|
+
await prepareIndexFile(indexPath);
|
|
314
|
+
return openDatabase(sqlite, indexPath, busyTimeoutMs);
|
|
315
|
+
}
|
|
316
|
+
// ── schema ───────────────────────────────────────────────────────────────────
|
|
317
|
+
/** FTS5 columns, in the contract's field order; the vocabulary tables report these names. */
|
|
318
|
+
const FTS_COLUMNS = SEARCH_MATCH_FIELDS;
|
|
319
|
+
/** Drops whatever holds this schema's names in a foreign or older file: tables, views, triggers,
|
|
320
|
+
* indexes, and FTS5 shadow tables (dropped with their table, or alone when orphaned). */
|
|
321
|
+
function dropOwnNames(db) {
|
|
322
|
+
db.exec("DROP TABLE IF EXISTS temp.vocab_instance; DROP TABLE IF EXISTS temp.vocab_row;");
|
|
323
|
+
const objects = db
|
|
324
|
+
.prepare("SELECT type, name FROM main.sqlite_master WHERE name IN ('meta', 'docs', 'fts') OR name LIKE 'fts\\_%' ESCAPE '\\'")
|
|
325
|
+
.all();
|
|
326
|
+
const order = ["trigger", "view", "index", "table"];
|
|
327
|
+
objects.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type) || (a.name === "fts" ? -1 : b.name === "fts" ? 1 : 0));
|
|
328
|
+
for (const { type, name } of objects) {
|
|
329
|
+
const kind = type === "view" ? "VIEW" : type === "trigger" ? "TRIGGER" : type === "index" ? "INDEX" : "TABLE";
|
|
330
|
+
db.exec(`DROP ${kind} IF EXISTS main."${name.replaceAll('"', '""')}"`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function createSchema(db, edition) {
|
|
334
|
+
dropOwnNames(db);
|
|
335
|
+
db.exec(`
|
|
336
|
+
CREATE TABLE main.meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
|
|
337
|
+
CREATE TABLE main.docs (
|
|
338
|
+
rowid INTEGER PRIMARY KEY,
|
|
339
|
+
id TEXT NOT NULL UNIQUE,
|
|
340
|
+
version TEXT,
|
|
341
|
+
stamp TEXT,
|
|
342
|
+
settled INTEGER NOT NULL,
|
|
343
|
+
state INTEGER NOT NULL,
|
|
344
|
+
reason TEXT,
|
|
345
|
+
title TEXT,
|
|
346
|
+
type TEXT,
|
|
347
|
+
tags TEXT NOT NULL,
|
|
348
|
+
title_phrase TEXT NOT NULL,
|
|
349
|
+
id_phrase TEXT NOT NULL
|
|
350
|
+
);
|
|
351
|
+
CREATE VIRTUAL TABLE main.fts USING fts5(${FTS_COLUMNS.join(", ")}, tokenize = 'ascii', content = '', contentless_delete = 1, detail = full);
|
|
352
|
+
`);
|
|
353
|
+
const put = db.prepare("INSERT INTO main.meta (key, value) VALUES (?, ?)");
|
|
354
|
+
put.run("schema", SCHEMA_VERSION);
|
|
355
|
+
put.run("textVersion", textVersion());
|
|
356
|
+
put.run("edition", edition);
|
|
357
|
+
}
|
|
358
|
+
function readMeta(db) {
|
|
359
|
+
try {
|
|
360
|
+
const rows = db.prepare("SELECT key, value FROM main.meta").all();
|
|
361
|
+
return new Map(rows.map((row) => [row.key, row.value]));
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
// A busy or corrupt file is not an answer; any other failure to read meta rows (no table, other
|
|
365
|
+
// columns, a view over something else) means the file is not this schema's index: rebuild it.
|
|
366
|
+
if (!isSqliteError(error) || isCorruption(error) || isBusy(error))
|
|
367
|
+
throw error;
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function current(meta, edition) {
|
|
372
|
+
return (meta !== undefined &&
|
|
373
|
+
meta.get("schema") === SCHEMA_VERSION &&
|
|
374
|
+
meta.get("textVersion") === textVersion() &&
|
|
375
|
+
meta.get("edition") === edition);
|
|
376
|
+
}
|
|
377
|
+
/** Rebuilds the tables when the file holds another schema, text version or bundle edition. */
|
|
378
|
+
function ensureSchema(db, edition) {
|
|
379
|
+
if (current(readMeta(db), edition))
|
|
380
|
+
return ensureVocabulary(db);
|
|
381
|
+
transaction(db, () => {
|
|
382
|
+
// Another process may have rebuilt it while this one waited for the lock.
|
|
383
|
+
if (!current(readMeta(db), edition))
|
|
384
|
+
createSchema(db, edition);
|
|
385
|
+
});
|
|
386
|
+
ensureVocabulary(db);
|
|
387
|
+
}
|
|
388
|
+
/** Per-connection vocabulary views over the FTS index: per-instance rows and per-term totals.
|
|
389
|
+
* Made again on every refresh, so a table another process rebuilt is never read through a stale view. */
|
|
390
|
+
function ensureVocabulary(db) {
|
|
391
|
+
db.exec(`
|
|
392
|
+
DROP TABLE IF EXISTS temp.vocab_instance;
|
|
393
|
+
DROP TABLE IF EXISTS temp.vocab_row;
|
|
394
|
+
CREATE VIRTUAL TABLE temp.vocab_instance USING fts5vocab(main, fts, instance);
|
|
395
|
+
CREATE VIRTUAL TABLE temp.vocab_row USING fts5vocab(main, fts, row);
|
|
396
|
+
`);
|
|
397
|
+
}
|
|
398
|
+
function transaction(db, body) {
|
|
399
|
+
db.exec("BEGIN IMMEDIATE");
|
|
400
|
+
try {
|
|
401
|
+
body();
|
|
402
|
+
db.exec("COMMIT");
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
try {
|
|
406
|
+
db.exec("ROLLBACK");
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
// The failed statement may already have ended the transaction.
|
|
410
|
+
}
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/** Brings the index up to the bundle: re-reads every file whose stamp cannot vouch for its row. */
|
|
415
|
+
async function refresh(db, backend, contentStamp, stop) {
|
|
416
|
+
// The edition decides how every document parses, so a change re-derives every row.
|
|
417
|
+
const edition = JSON.stringify((await readBundleOkfVersion(backend, { allowMalformedRoot: true })) ?? null);
|
|
418
|
+
ensureSchema(db, edition);
|
|
419
|
+
const manifest = new Map();
|
|
420
|
+
for (const row of db.prepare("SELECT id, version, stamp, settled, state FROM main.docs").all())
|
|
421
|
+
manifest.set(row.id, row);
|
|
422
|
+
const ids = await backend.list();
|
|
423
|
+
const stale = [];
|
|
424
|
+
for (let start = 0; start < ids.length; start += STAMP_CONCURRENCY) {
|
|
425
|
+
stopIfAsked(stop);
|
|
426
|
+
const batch = ids.slice(start, start + STAMP_CONCURRENCY);
|
|
427
|
+
// Each stamp is taken before its file is read, so a write after it moves the stamp again.
|
|
428
|
+
const stamps = await Promise.all(batch.map((id) => contentStamp(id)));
|
|
429
|
+
for (const [index, id] of batch.entries()) {
|
|
430
|
+
const stamp = stamps[index];
|
|
431
|
+
const row = manifest.get(id);
|
|
432
|
+
if (row !== undefined && stamp !== undefined && row.settled === 1 && row.stamp === stamp.value)
|
|
433
|
+
continue;
|
|
434
|
+
stale.push({ id, stamp });
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
let pending = [];
|
|
438
|
+
let pendingText = 0;
|
|
439
|
+
const flush = () => {
|
|
440
|
+
apply(db, pending);
|
|
441
|
+
pending = [];
|
|
442
|
+
pendingText = 0;
|
|
443
|
+
};
|
|
444
|
+
const queue = (change) => {
|
|
445
|
+
pending.push(change);
|
|
446
|
+
if (change.kind === "row")
|
|
447
|
+
for (const column of change.columns ?? [])
|
|
448
|
+
pendingText += column.length;
|
|
449
|
+
if (pending.length >= WRITE_CHANGES || pendingText >= WRITE_TEXT_UNITS)
|
|
450
|
+
flush();
|
|
451
|
+
};
|
|
452
|
+
for (let start = 0; start < stale.length; start += BATCH) {
|
|
453
|
+
stopIfAsked(stop);
|
|
454
|
+
const batch = stale.slice(start, start + BATCH);
|
|
455
|
+
const malformed = new Map();
|
|
456
|
+
const results = await readManyExisting(backend, batch.map((entry) => entry.id), (skip) => void malformed.set(skip.id, skip));
|
|
457
|
+
let next = 0;
|
|
458
|
+
for (const [position, { id, stamp }] of batch.entries()) {
|
|
459
|
+
if (position % SIGNAL_INTERVAL === 0)
|
|
460
|
+
stopIfAsked(stop);
|
|
461
|
+
const skip = malformed.get(id);
|
|
462
|
+
if (skip !== undefined) {
|
|
463
|
+
queue(malformedRow(id, stamp, skip.reason));
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
const result = results[next];
|
|
467
|
+
if (result === undefined || result.doc.id !== id) {
|
|
468
|
+
queue({ kind: "delete", id }); // Gone between the listing and the read.
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
next += 1;
|
|
472
|
+
const row = manifest.get(id);
|
|
473
|
+
if (row !== undefined && row.state !== MALFORMED && row.version === result.version) {
|
|
474
|
+
// An unchanged stamp (an untrusted one is always null) needs no write, so a search that
|
|
475
|
+
// finds nothing changed takes no write lock.
|
|
476
|
+
if (row.stamp !== (stamp?.value ?? null) || row.settled !== (stamp?.settled ? 1 : 0))
|
|
477
|
+
queue({ kind: "stamp", id, version: result.version, stamp });
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
queue(derivedRow({ ...result.doc, version: result.version }, stamp));
|
|
481
|
+
}
|
|
482
|
+
if (next !== results.length)
|
|
483
|
+
throw new TypeError("Search backend returned a different document identity.");
|
|
484
|
+
}
|
|
485
|
+
const listed = new Set(ids);
|
|
486
|
+
for (const id of manifest.keys())
|
|
487
|
+
if (!listed.has(id))
|
|
488
|
+
queue({ kind: "delete", id });
|
|
489
|
+
flush();
|
|
490
|
+
}
|
|
491
|
+
function malformedRow(id, stamp, reason) {
|
|
492
|
+
return { kind: "row", id, version: null, stamp, state: MALFORMED, reason, title: null, type: null, tags: "[]", titlePhrase: "", idPhrase: "" };
|
|
493
|
+
}
|
|
494
|
+
function derivedRow(document, stamp) {
|
|
495
|
+
const text = searchRowText(document);
|
|
496
|
+
const searched = text.bodyTermCount <= SEARCH_LIMITS.maxTermsPerDocument;
|
|
497
|
+
const byField = {
|
|
498
|
+
title: text.titleTerms,
|
|
499
|
+
type: text.typeTerms,
|
|
500
|
+
tag: text.tagTerms,
|
|
501
|
+
description: text.descriptionTerms,
|
|
502
|
+
id: text.idTerms,
|
|
503
|
+
body: text.bodyTerms,
|
|
504
|
+
};
|
|
505
|
+
return {
|
|
506
|
+
kind: "row",
|
|
507
|
+
id: document.id,
|
|
508
|
+
version: document.version,
|
|
509
|
+
stamp,
|
|
510
|
+
state: searched ? INDEXED : OVER_TERM_CAP,
|
|
511
|
+
reason: null,
|
|
512
|
+
title: documentTitle(document) ?? null,
|
|
513
|
+
type: documentType(document) ?? null,
|
|
514
|
+
tags: JSON.stringify(documentTags(document)),
|
|
515
|
+
titlePhrase: text.titlePhrase,
|
|
516
|
+
idPhrase: text.idPhrase,
|
|
517
|
+
...(searched ? { columns: FTS_COLUMNS.map((field) => byField[field]) } : {}),
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* One write transaction. Each change is applied against the row as it is now, not as this process
|
|
522
|
+
* last saw it, so two processes refreshing at once both leave a row derived from a real read.
|
|
523
|
+
*/
|
|
524
|
+
function apply(db, changes) {
|
|
525
|
+
if (changes.length === 0)
|
|
526
|
+
return;
|
|
527
|
+
const find = db.prepare("SELECT rowid, state FROM main.docs WHERE id = ?");
|
|
528
|
+
const stampOnly = db.prepare("UPDATE main.docs SET stamp = ?, settled = ? WHERE id = ? AND version = ? AND state != ?");
|
|
529
|
+
const update = db.prepare("UPDATE main.docs SET version = ?, stamp = ?, settled = ?, state = ?, reason = ?, title = ?, type = ?, tags = ?, title_phrase = ?, id_phrase = ? WHERE rowid = ?");
|
|
530
|
+
const insert = db.prepare("INSERT INTO main.docs (id, version, stamp, settled, state, reason, title, type, tags, title_phrase, id_phrase) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING rowid");
|
|
531
|
+
const remove = db.prepare("DELETE FROM main.docs WHERE rowid = ?");
|
|
532
|
+
const unindex = db.prepare("DELETE FROM main.fts WHERE rowid = ?");
|
|
533
|
+
const index = db.prepare(`INSERT INTO main.fts (rowid, ${FTS_COLUMNS.join(", ")}) VALUES (?, ${FTS_COLUMNS.map(() => "?").join(", ")})`);
|
|
534
|
+
// A write through FTS5 can report a shadow-table rowid past 2^53 as its last insert rowid, which
|
|
535
|
+
// Node 26 refuses to convert to a number; nothing here reads it.
|
|
536
|
+
for (const statement of [stampOnly, update, insert, remove, unindex, index])
|
|
537
|
+
statement.setReadBigInts(true);
|
|
538
|
+
transaction(db, () => {
|
|
539
|
+
for (const change of changes) {
|
|
540
|
+
const existing = find.get(change.id);
|
|
541
|
+
if (change.kind === "stamp") {
|
|
542
|
+
stampOnly.run(change.stamp?.value ?? null, change.stamp?.settled ? 1 : 0, change.id, change.version, MALFORMED);
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (existing !== undefined && existing.state === INDEXED)
|
|
546
|
+
unindex.run(existing.rowid);
|
|
547
|
+
if (change.kind === "delete") {
|
|
548
|
+
if (existing !== undefined)
|
|
549
|
+
remove.run(existing.rowid);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
const values = [
|
|
553
|
+
change.version,
|
|
554
|
+
change.stamp?.value ?? null,
|
|
555
|
+
change.stamp?.settled ? 1 : 0,
|
|
556
|
+
change.state,
|
|
557
|
+
change.reason,
|
|
558
|
+
change.title,
|
|
559
|
+
change.type,
|
|
560
|
+
change.tags,
|
|
561
|
+
change.titlePhrase,
|
|
562
|
+
change.idPhrase,
|
|
563
|
+
];
|
|
564
|
+
let rowid;
|
|
565
|
+
if (existing !== undefined) {
|
|
566
|
+
update.run(...values, existing.rowid);
|
|
567
|
+
rowid = existing.rowid;
|
|
568
|
+
}
|
|
569
|
+
else {
|
|
570
|
+
rowid = Number(insert.get(change.id, ...values).rowid);
|
|
571
|
+
}
|
|
572
|
+
if (change.columns !== undefined)
|
|
573
|
+
index.run(rowid, ...change.columns);
|
|
574
|
+
}
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
/** One read transaction: the corpus identity and sizes, the volume and the evidence agree. */
|
|
578
|
+
function readEvidence(db, terms, filters, bounds, stop) {
|
|
579
|
+
db.exec("BEGIN");
|
|
580
|
+
try {
|
|
581
|
+
const corpus = db.prepare("SELECT id, version, state, reason FROM main.docs").all();
|
|
582
|
+
const heads = [];
|
|
583
|
+
const skipped = [];
|
|
584
|
+
let indexed = 0;
|
|
585
|
+
for (const row of corpus) {
|
|
586
|
+
if (row.state === MALFORMED)
|
|
587
|
+
skipped.push(Object.freeze({ id: row.id, reason: row.reason ?? "" }));
|
|
588
|
+
else
|
|
589
|
+
heads.push({ id: row.id, version: row.version });
|
|
590
|
+
if (row.state === INDEXED)
|
|
591
|
+
indexed += 1;
|
|
592
|
+
}
|
|
593
|
+
skipped.sort((a, b) => codeUnitCompare(a.id, b.id));
|
|
594
|
+
const digest = headsDigest(heads);
|
|
595
|
+
const key = skipped.length === 0 ? digest : sha256HexOfUtf8(canonicalJson({ heads: digest, skipped }));
|
|
596
|
+
const size = Object.freeze({
|
|
597
|
+
documents: corpus.length,
|
|
598
|
+
indexed,
|
|
599
|
+
skipped: corpus.length - indexed,
|
|
600
|
+
reindexPending: 0,
|
|
601
|
+
});
|
|
602
|
+
const answer = (volume, documents) => ({
|
|
603
|
+
key,
|
|
604
|
+
size,
|
|
605
|
+
...(skipped.length === 0 ? {} : { skipped: Object.freeze(skipped) }),
|
|
606
|
+
volume,
|
|
607
|
+
documents,
|
|
608
|
+
});
|
|
609
|
+
if (terms.length === 0)
|
|
610
|
+
return answer(0, []);
|
|
611
|
+
const json = JSON.stringify(terms);
|
|
612
|
+
const volume = Number(db.prepare("SELECT coalesce(sum(cnt), 0) AS volume FROM temp.vocab_row WHERE term IN (SELECT value FROM json_each(?))").get(json).volume);
|
|
613
|
+
// Over the bound nothing is walked, as the engine refuses the request.
|
|
614
|
+
if (volume > bounds.maxInstances)
|
|
615
|
+
return answer(volume, []);
|
|
616
|
+
const instances = db
|
|
617
|
+
.prepare("SELECT term, doc, col, count(*) AS n FROM temp.vocab_instance WHERE term IN (SELECT value FROM json_each(?)) GROUP BY term, doc, col")
|
|
618
|
+
.all(json);
|
|
619
|
+
const held = new Map();
|
|
620
|
+
for (const { term, doc, col, n } of instances) {
|
|
621
|
+
let perDoc = held.get(doc);
|
|
622
|
+
if (perDoc === undefined)
|
|
623
|
+
held.set(doc, (perDoc = new Map()));
|
|
624
|
+
let perTerm = perDoc.get(term);
|
|
625
|
+
if (perTerm === undefined)
|
|
626
|
+
perDoc.set(term, (perTerm = { fields: new Set(), body: 0 }));
|
|
627
|
+
perTerm.fields.add(col);
|
|
628
|
+
if (col === "body")
|
|
629
|
+
perTerm.body = n;
|
|
630
|
+
}
|
|
631
|
+
const rows = db
|
|
632
|
+
.prepare("SELECT rowid, id, version, title, type, tags, title_phrase, id_phrase FROM main.docs WHERE rowid IN (SELECT value FROM json_each(?))")
|
|
633
|
+
.all(JSON.stringify([...held.keys()]));
|
|
634
|
+
const documents = [];
|
|
635
|
+
for (const [position, row] of rows.entries()) {
|
|
636
|
+
if (position % SIGNAL_INTERVAL === 0)
|
|
637
|
+
stopIfAsked(stop);
|
|
638
|
+
const type = row.type ?? undefined;
|
|
639
|
+
const tags = Object.freeze(JSON.parse(row.tags));
|
|
640
|
+
if (filters.type !== undefined && type !== filters.type)
|
|
641
|
+
continue;
|
|
642
|
+
if (filters.tag !== undefined && !tags.includes(filters.tag))
|
|
643
|
+
continue;
|
|
644
|
+
if (filters.prefix !== undefined && !row.id.startsWith(filters.prefix))
|
|
645
|
+
continue;
|
|
646
|
+
if (filters.excludeConventions && isConventionRecord(row.id, type))
|
|
647
|
+
continue;
|
|
648
|
+
const perDoc = held.get(row.rowid);
|
|
649
|
+
const termEvidence = new Map();
|
|
650
|
+
for (const term of terms) {
|
|
651
|
+
const entry = perDoc.get(term);
|
|
652
|
+
if (entry === undefined)
|
|
653
|
+
continue;
|
|
654
|
+
termEvidence.set(term, {
|
|
655
|
+
fields: Object.freeze(SEARCH_MATCH_FIELDS.filter((field) => entry.fields.has(field))),
|
|
656
|
+
bodyOccurrences: entry.body,
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
documents.push({
|
|
660
|
+
id: row.id,
|
|
661
|
+
version: row.version,
|
|
662
|
+
...(row.title === null ? {} : { title: row.title }),
|
|
663
|
+
...(type === undefined ? {} : { type }),
|
|
664
|
+
tags,
|
|
665
|
+
titlePhrase: row.title_phrase,
|
|
666
|
+
idPhrase: row.id_phrase,
|
|
667
|
+
terms: termEvidence,
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
return answer(volume, documents);
|
|
671
|
+
}
|
|
672
|
+
finally {
|
|
673
|
+
db.exec("COMMIT");
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/** Description and body of the hits, read again; a file changed since its evidence gives none. */
|
|
677
|
+
async function readTexts(backend, hits) {
|
|
678
|
+
const texts = new Map();
|
|
679
|
+
const wanted = new Map(hits.map((hit) => [hit.id, hit.version]));
|
|
680
|
+
if (wanted.size === 0)
|
|
681
|
+
return texts;
|
|
682
|
+
const results = await readManyExisting(backend, [...wanted.keys()], () => { });
|
|
683
|
+
for (const { doc, version } of results) {
|
|
684
|
+
if (wanted.get(doc.id) !== version)
|
|
685
|
+
continue;
|
|
686
|
+
texts.set(doc.id, { description: documentDescription({ ...doc, version }) ?? "", body: doc.body });
|
|
687
|
+
}
|
|
688
|
+
return texts;
|
|
689
|
+
}
|
|
690
|
+
//# sourceMappingURL=local-search-index.js.map
|