polite-crawler 0.7.0 → 0.7.2

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.
Files changed (33) hide show
  1. package/README.md +2 -1
  2. package/build/{cli-daemon-Bke7kU1e.mjs → cli-daemon-KjIlGd_Q.mjs} +2 -2
  3. package/build/{cli-daemon-Bke7kU1e.mjs.map → cli-daemon-KjIlGd_Q.mjs.map} +1 -1
  4. package/build/{cli-recipes-CUFd9ORK.mjs → cli-recipes-BVz-P6q0.mjs} +2 -2
  5. package/build/{cli-recipes-CUFd9ORK.mjs.map → cli-recipes-BVz-P6q0.mjs.map} +1 -1
  6. package/build/cli.mjs +7 -7
  7. package/build/{daemon-Dh32XlZq.mjs → daemon-CF2st2kh.mjs} +56 -14
  8. package/build/daemon-CF2st2kh.mjs.map +1 -0
  9. package/build/{diff-ZEIt8xv3.mjs → diff-BsYl-M4P.mjs} +2 -2
  10. package/build/{diff-ZEIt8xv3.mjs.map → diff-BsYl-M4P.mjs.map} +1 -1
  11. package/build/{extract-B_Tsv1UC.mjs → extract-CP3VLyJh.mjs} +2 -2
  12. package/build/{extract-B_Tsv1UC.mjs.map → extract-CP3VLyJh.mjs.map} +1 -1
  13. package/build/index.d.mts +11 -5
  14. package/build/index.mjs +10 -10
  15. package/build/{open-Dx1gCR6l.mjs → open-DE3mCat8.mjs} +86 -900
  16. package/build/open-DE3mCat8.mjs.map +1 -0
  17. package/build/{recipe-BO3V_1Kr.mjs → recipe-D2758Xqp.mjs} +3 -3
  18. package/build/{recipe-BO3V_1Kr.mjs.map → recipe-D2758Xqp.mjs.map} +1 -1
  19. package/build/{recipe-product-BOQMCTGh.mjs → recipe-product-DZsncwAl.mjs} +35 -8
  20. package/build/recipe-product-DZsncwAl.mjs.map +1 -0
  21. package/build/{runtime-BVC7iOG4.mjs → runtime-DMem_UuO.mjs} +803 -16
  22. package/build/runtime-DMem_UuO.mjs.map +1 -0
  23. package/build/{version-DxUGcHQr.mjs → version-J_JYtS-2.mjs} +2 -2
  24. package/build/{version-DxUGcHQr.mjs.map → version-J_JYtS-2.mjs.map} +1 -1
  25. package/build/{wacz-DjgklRod.mjs → wacz-DoeRTqqi.mjs} +3 -3
  26. package/build/{wacz-DjgklRod.mjs.map → wacz-DoeRTqqi.mjs.map} +1 -1
  27. package/build/{warc-CgkNdXyG.mjs → warc-5f582tZO.mjs} +2 -2
  28. package/build/{warc-CgkNdXyG.mjs.map → warc-5f582tZO.mjs.map} +1 -1
  29. package/package.json +4 -3
  30. package/build/daemon-Dh32XlZq.mjs.map +0 -1
  31. package/build/open-Dx1gCR6l.mjs.map +0 -1
  32. package/build/recipe-product-BOQMCTGh.mjs.map +0 -1
  33. package/build/runtime-BVC7iOG4.mjs.map +0 -1
@@ -1,13 +1,13 @@
1
+ import { cacheKeyOf, canonicalUrl } from "./urls.mjs";
1
2
  import { extractPage, typesOf } from "./html.mjs";
2
3
  import { decodeBody } from "./text.mjs";
3
- import { cacheKeyOf, canonicalUrl } from "./urls.mjs";
4
4
  import { classify, parseHttpDate } from "./classify.mjs";
5
5
  import { n as reactToOutcome, t as outcomeResult } from "./reaction-BWTIe95J.mjs";
6
6
  import { DEFAULT_POLICY, HostScheduler, HostStopped, checkPolicy, equalJitterMs, policyFor, realClock, restAfter, validatorsToSend } from "./politeness.mjs";
7
7
  import { n as RenderRefused } from "./render-B0NrFDkJ.mjs";
8
8
  import { decide, isProductToken, robotsFromResponse, robotsFromStatus, signalsFor, unreachableRobots } from "./robots.mjs";
9
9
  import { NO_SIGNALS, metaSignals, readSignals } from "./signals.mjs";
10
- import { n as DEFAULT_TOKEN } from "./version-DxUGcHQr.mjs";
10
+ import { n as DEFAULT_TOKEN } from "./version-J_JYtS-2.mjs";
11
11
  import { a as signerOf } from "./webbotauth-DbiWmibz.mjs";
12
12
  import { createHash } from "node:crypto";
13
13
  import { Transform } from "node:stream";
@@ -15,6 +15,7 @@ import { brotliDecompressSync, constants, createBrotliDecompress, createGunzip,
15
15
  import { Agent, request } from "undici";
16
16
  import { lookup } from "node:dns";
17
17
  import { isIP } from "node:net";
18
+ import { ensureProjection, openDatabase, tableColumns, transaction } from "@mark1russell7/sqlite";
18
19
  import { getDocumentProxy, getMeta } from "unpdf";
19
20
  // src/egress.ts
20
21
  /**
@@ -622,7 +623,7 @@ var Slots = class {
622
623
  const missingBrowser = (message) => message.startsWith("rendering needs the package playwright-core and a browser: npm install playwright-core, then npx playwright-core install chromium-headless-shell. For the MCP server with npx, start it with npx -y -p polite-crawler-mcp -p playwright-core polite-crawler-mcp") || /Executable doesn't exist|Cannot find (?:module|package) 'playwright-core'/.test(message);
623
624
  /** This text tells why the crawler did not fetch a page: a rule of the site, or no robots.txt to read. */
624
625
  const robotsRefusal = (robots, by) => robots.unreachable === void 0 ? `robots.txt disallows it for ${by}` : `robots.txt could not be read (${robots.unreachable}), so nothing on the site is fetched`;
625
- const messageOf$1 = (error) => error instanceof Error ? error.message.split(/\r?\n/)[0] ?? "" : String(error);
626
+ const messageOf$2 = (error) => error instanceof Error ? error.message.split(/\r?\n/)[0] ?? "" : String(error);
626
627
  const isoOf = (ms) => Number.isFinite(ms) && Math.abs(ms) < LAST_DATE_MS ? new Date(ms).toISOString() : void 0;
627
628
  const stopNote = (reason, until) => {
628
629
  const end = isoOf(until);
@@ -714,7 +715,7 @@ var Lru = class {
714
715
  var BodyError = class extends Error {
715
716
  kind;
716
717
  constructor(kind, cause) {
717
- super(messageOf$1(cause), { cause });
718
+ super(messageOf$2(cause), { cause });
718
719
  this.kind = kind;
719
720
  }
720
721
  };
@@ -752,7 +753,7 @@ const decoderFor = (coding) => {
752
753
  throw new BodyError("decode", /* @__PURE__ */ new Error(`unsupported content-encoding "${coding}"`));
753
754
  };
754
755
  /** This function tells if a decoder stopped because the compressed body ended early: the server cut it. */
755
- const endedEarly = (error) => typeof error === "object" && error !== null && "code" in error && (error.code === "Z_BUF_ERROR" || /unexpected end of file/i.test(messageOf$1(error)));
756
+ const endedEarly = (error) => typeof error === "object" && error !== null && "code" in error && (error.code === "Z_BUF_ERROR" || /unexpected end of file/i.test(messageOf$2(error)));
756
757
  /**
757
758
  * This function reads a body as a stream and decodes each content coding in sequence. It counts
758
759
  * the decoded bytes and keeps at most `maxBytes`. Thus a decompression bomb stops at the
@@ -1186,7 +1187,7 @@ var Crawler = class {
1186
1187
  try {
1187
1188
  given = this.signer.sign(target, this.clock.now());
1188
1189
  } catch (error) {
1189
- return { error: `the signer did not sign the request: ${messageOf$1(error)}` };
1190
+ return { error: `the signer did not sign the request: ${messageOf$2(error)}` };
1190
1191
  }
1191
1192
  const headers = {};
1192
1193
  for (const [name, value] of Object.entries(given)) {
@@ -1379,7 +1380,7 @@ var Crawler = class {
1379
1380
  return {
1380
1381
  ...closedResult(request_.url),
1381
1382
  outcome: "error",
1382
- note: `crawler error: ${messageOf$1(error)}`
1383
+ note: `crawler error: ${messageOf$2(error)}`
1383
1384
  };
1384
1385
  }
1385
1386
  }
@@ -1446,7 +1447,7 @@ var Crawler = class {
1446
1447
  good: cached?.good
1447
1448
  };
1448
1449
  entry.verdict = this.fetchRobots(target, policy, waiting).catch((error) => ({
1449
- robots: unreachableRobots(`robots.txt failed: ${messageOf$1(error)}`),
1450
+ robots: unreachableRobots(`robots.txt failed: ${messageOf$2(error)}`),
1450
1451
  capture: void 0,
1451
1452
  retryAfterMs: void 0
1452
1453
  })).then(async (read) => {
@@ -1687,7 +1688,7 @@ var Crawler = class {
1687
1688
  const timeout = AbortSignal.timeout(policy.requestTimeoutMs);
1688
1689
  const abort = AbortSignal.any([timeout, signal]);
1689
1690
  const cancelled = () => request_.signal?.aborted === true;
1690
- const failedNote = (prefix, error) => timeout.aborted ? `${prefix}: timed out after ${String(Math.round(policy.requestTimeoutMs / 1e3))} s` : `${prefix}: ${messageOf$1(error)}`;
1691
+ const failedNote = (prefix, error) => timeout.aborted ? `${prefix}: timed out after ${String(Math.round(policy.requestTimeoutMs / 1e3))} s` : `${prefix}: ${messageOf$2(error)}`;
1691
1692
  this.emit({
1692
1693
  type: "request",
1693
1694
  url,
@@ -1793,7 +1794,7 @@ var Crawler = class {
1793
1794
  blob = (await this.options.blobs.put(body)).hash;
1794
1795
  } catch (error) {
1795
1796
  outcome = "error";
1796
- note = `blob store: ${messageOf$1(error)}`;
1797
+ note = `blob store: ${messageOf$2(error)}`;
1797
1798
  body = void 0;
1798
1799
  result = "neutral";
1799
1800
  }
@@ -2061,7 +2062,7 @@ var Crawler = class {
2061
2062
  return this.track(this.renderOnce(request_).catch((error) => this.closed ? closedResult(request_.url) : {
2062
2063
  ...closedResult(request_.url),
2063
2064
  outcome: "error",
2064
- note: `crawler error: ${messageOf$1(error)}`
2065
+ note: `crawler error: ${messageOf$2(error)}`
2065
2066
  }));
2066
2067
  }
2067
2068
  async renderOnce(request_) {
@@ -2194,7 +2195,7 @@ var Crawler = class {
2194
2195
  },
2195
2196
  delayMs: restAfter(policy, rest(0)).ms
2196
2197
  };
2197
- const refused = error instanceof RenderRefused ? error : missingBrowser(messageOf$1(error)) ? new RenderRefused("browser", `rendering needs a browser: ${messageOf$1(error)}`) : void 0;
2198
+ const refused = error instanceof RenderRefused ? error : missingBrowser(messageOf$2(error)) ? new RenderRefused("browser", `rendering needs a browser: ${messageOf$2(error)}`) : void 0;
2198
2199
  if (refused !== void 0) {
2199
2200
  if (refused.reason === "browser") this.renderOff = refused.message;
2200
2201
  const delayMs = this.settle(host, policy, {
@@ -2226,7 +2227,7 @@ var Crawler = class {
2226
2227
  return {
2227
2228
  value: {
2228
2229
  kind: "failed",
2229
- note: `render failed: ${messageOf$1(error)}`,
2230
+ note: `render failed: ${messageOf$2(error)}`,
2230
2231
  elapsedMs
2231
2232
  },
2232
2233
  delayMs
@@ -2352,7 +2353,7 @@ var Crawler = class {
2352
2353
  blob = (await this.options.blobs.put(body)).hash;
2353
2354
  } catch (error) {
2354
2355
  outcome = "error";
2355
- note = `blob store: ${messageOf$1(error)}`;
2356
+ note = `blob store: ${messageOf$2(error)}`;
2356
2357
  body = void 0;
2357
2358
  }
2358
2359
  }
@@ -2742,6 +2743,792 @@ const snippetOf = (text, terms, width = 160) => {
2742
2743
  const clean = (part) => part.replace(/\s+/g, " ");
2743
2744
  return `${from > 0 ? "…" : ""}${clean(text.slice(from, start))}[${clean(text.slice(start, end))}]${clean(text.slice(end, to))}${to < text.length ? "…" : ""}`;
2744
2745
  };
2746
+ /** The search index reads this many characters of each text, at most. */
2747
+ const MAX_INDEX_CHARS = 2e5;
2748
+ /**
2749
+ * In the mode `fast`, a part is common when more than this share of the documents hold it.
2750
+ *
2751
+ * @beta
2752
+ */
2753
+ const FAST_RANK_SHARE = .2;
2754
+ /** The text of the error of hybrid search with no embedder. */
2755
+ const NO_EMBEDDER = "hybrid search needs an embedder: open the crawler with the option embedder (transformersEmbedder or ollamaEmbedder), or give --embedder transformers or ollama to the command line";
2756
+ /** This function gives the rank mode of an option. A value that is not a rank mode throws a `RangeError`. */
2757
+ const rankModeOf = (value) => {
2758
+ if (value === void 0 || value === "exact") return "exact";
2759
+ if (value === "fast") return "fast";
2760
+ if (value === "hybrid") throw new RangeError("the index ranks with \"exact\" and \"fast\" only: rank \"hybrid\" needs the vectors of an embedder, so use find or rankWithin of a crawler with the option embedder");
2761
+ throw new RangeError(`rank must be "exact" or "fast", not ${JSON.stringify(value) ?? "undefined"}`);
2762
+ };
2763
+ const namesOf = (generation) => ({
2764
+ docs: `docs_${String(generation)}`,
2765
+ fts: `fts_${String(generation)}`,
2766
+ versions: `versions_${String(generation)}`,
2767
+ texts: `texts_${String(generation)}`,
2768
+ latest: `latest_${String(generation)}`
2769
+ });
2770
+ const GENERATION_TABLE = /^(docs|fts|versions|texts|latest)_(\d+)$/;
2771
+ /** A build that started this long ago and did not finish belongs to a process that stopped. */
2772
+ const ABANDONED_MS = 864e5;
2773
+ /** The FTS5 tokenizer: folded text, English stems, and spacing marks kept in the words. */
2774
+ const TOKENIZER = `tokenize = "porter unicode61 remove_diacritics 0 categories 'L* N* Co Mc'"`;
2775
+ const ddlOf = (n) => `
2776
+ CREATE TABLE IF NOT EXISTS ${n.texts} (
2777
+ sha TEXT PRIMARY KEY,
2778
+ body TEXT NOT NULL
2779
+ );
2780
+ CREATE TABLE IF NOT EXISTS ${n.versions} (
2781
+ doc TEXT NOT NULL,
2782
+ capture TEXT NOT NULL,
2783
+ recipe TEXT NOT NULL,
2784
+ rendered INTEGER NOT NULL,
2785
+ fetched_at TEXT NOT NULL,
2786
+ blob TEXT,
2787
+ kind TEXT NOT NULL,
2788
+ title TEXT NOT NULL,
2789
+ url TEXT,
2790
+ meta_sha TEXT NOT NULL,
2791
+ text_sha TEXT NOT NULL,
2792
+ text_chars INTEGER NOT NULL,
2793
+ full_sha TEXT,
2794
+ ai_input TEXT NOT NULL,
2795
+ merge TEXT NOT NULL,
2796
+ scope TEXT,
2797
+ labels TEXT,
2798
+ PRIMARY KEY (doc, capture)
2799
+ );
2800
+ CREATE INDEX IF NOT EXISTS ${n.versions}_time ON ${n.versions} (doc, recipe, rendered, fetched_at);
2801
+ CREATE INDEX IF NOT EXISTS ${n.versions}_capture ON ${n.versions} (capture);
2802
+ CREATE INDEX IF NOT EXISTS ${n.versions}_fetched ON ${n.versions} (fetched_at);
2803
+ CREATE INDEX IF NOT EXISTS ${n.versions}_recipe ON ${n.versions} (recipe);
2804
+ CREATE TABLE IF NOT EXISTS ${n.docs} (
2805
+ doc TEXT PRIMARY KEY,
2806
+ kind TEXT NOT NULL,
2807
+ title TEXT NOT NULL,
2808
+ url TEXT,
2809
+ meta TEXT NOT NULL,
2810
+ text_sha TEXT NOT NULL,
2811
+ full_sha TEXT,
2812
+ captures TEXT NOT NULL,
2813
+ capture_count INTEGER NOT NULL,
2814
+ capture TEXT NOT NULL,
2815
+ blob TEXT,
2816
+ fetched_at TEXT NOT NULL,
2817
+ recipe TEXT NOT NULL,
2818
+ rendered INTEGER NOT NULL,
2819
+ ai_input TEXT NOT NULL,
2820
+ scope TEXT,
2821
+ labels TEXT,
2822
+ updated_at TEXT NOT NULL
2823
+ );
2824
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${n.fts} USING fts5(
2825
+ title, text, content = '', contentless_delete = 1, ${TOKENIZER}
2826
+ );
2827
+ CREATE TABLE IF NOT EXISTS ${n.latest} (
2828
+ url TEXT NOT NULL,
2829
+ variant TEXT NOT NULL,
2830
+ capture TEXT NOT NULL,
2831
+ blob TEXT,
2832
+ etag TEXT,
2833
+ last_modified TEXT,
2834
+ content_type TEXT,
2835
+ fetched_at TEXT NOT NULL,
2836
+ status INTEGER NOT NULL,
2837
+ ai_input TEXT NOT NULL,
2838
+ location TEXT,
2839
+ truncated INTEGER,
2840
+ fresh_until TEXT,
2841
+ vary_key TEXT,
2842
+ PRIMARY KEY (url, variant)
2843
+ );
2844
+ CREATE INDEX IF NOT EXISTS ${n.latest}_fetched ON ${n.latest} (fetched_at);
2845
+ `;
2846
+ const RENDERED_MARK$1 = "#rendered";
2847
+ /** This function splits a cache key into its URL and its variant. A key in the form of version 0.1 (`…#rendered`) is a rendered variant. */
2848
+ const keyOf = (url, variant) => {
2849
+ if (url.endsWith(RENDERED_MARK$1)) return {
2850
+ url: cacheKeyOf(url.slice(0, -9)),
2851
+ variant: "rendered"
2852
+ };
2853
+ return {
2854
+ url: cacheKeyOf(url),
2855
+ variant: variant ?? "plain"
2856
+ };
2857
+ };
2858
+ const sha = (text) => createHash("sha256").update(text, "utf8").digest("hex");
2859
+ const parseJson = (text, fallback) => {
2860
+ if (text === null || text === void 0) return fallback;
2861
+ try {
2862
+ return JSON.parse(text);
2863
+ } catch {
2864
+ return fallback;
2865
+ }
2866
+ };
2867
+ const toLatest = (row) => ({
2868
+ url: row.url,
2869
+ capture: row.capture,
2870
+ blob: row.blob,
2871
+ etag: row.etag,
2872
+ last_modified: row.last_modified,
2873
+ content_type: row.content_type,
2874
+ fetched_at: row.fetched_at,
2875
+ status: row.status,
2876
+ ai_input: row.ai_input,
2877
+ location: row.location,
2878
+ truncated: row.truncated === 1 ? true : void 0,
2879
+ fresh_until: row.fresh_until,
2880
+ vary_key: row.vary_key,
2881
+ variant: row.variant
2882
+ });
2883
+ const toVersion = (row) => ({
2884
+ doc: row.doc,
2885
+ capture: row.capture,
2886
+ recipe: row.recipe,
2887
+ rendered: row.rendered === 1,
2888
+ fetched_at: row.fetched_at,
2889
+ blob: row.blob,
2890
+ kind: row.kind,
2891
+ title: row.title,
2892
+ url: row.url,
2893
+ ai_input: row.ai_input,
2894
+ chars: row.text_chars,
2895
+ cut: row.full_sha !== null
2896
+ });
2897
+ const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
2898
+ /** @beta */
2899
+ var DocIndex = class {
2900
+ path;
2901
+ db;
2902
+ statements = /* @__PURE__ */ new Map();
2903
+ depth = 0;
2904
+ closed = false;
2905
+ empty;
2906
+ /**
2907
+ * This value is true when the file had a different schema, or no tables, so the index opened
2908
+ * empty. A store with captures then needs `reindex`. The commit of a rebuild makes it false.
2909
+ */
2910
+ get stale() {
2911
+ return this.empty;
2912
+ }
2913
+ constructor(path, options = {}) {
2914
+ this.path = path;
2915
+ this.db = openDatabase(path, {
2916
+ wal: path !== ":memory:",
2917
+ synchronous: "NORMAL",
2918
+ busyTimeoutMs: Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4)),
2919
+ makeFolder: true,
2920
+ folderMode: 448
2921
+ });
2922
+ try {
2923
+ this.db.exec("CREATE VIRTUAL TABLE temp.polite_fts5_probe USING fts5(x, content = '', contentless_delete = 1); DROP TABLE temp.polite_fts5_probe;");
2924
+ } catch (cause) {
2925
+ this.db.close();
2926
+ throw new Error(`polite-crawler needs SQLite FTS5 with contentless_delete, and the SQLite of Node.js ${process.version} does not have it: use Node.js 22.19 or later`, { cause });
2927
+ }
2928
+ try {
2929
+ this.empty = this.write(() => this.prepareSchema());
2930
+ } catch (error) {
2931
+ this.db.close();
2932
+ throw error;
2933
+ }
2934
+ }
2935
+ /** This method makes the tables of the schema. It gives true when the index opened empty. */
2936
+ prepareSchema() {
2937
+ const { rebuilt } = ensureProjection(this.db, (db) => {
2938
+ db.exec("CREATE TABLE index_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
2939
+ db.exec(ddlOf(namesOf(1)));
2940
+ this.statements.clear();
2941
+ this.setMeta("generation", "1");
2942
+ this.setMeta("next_generation", "2");
2943
+ }, {
2944
+ version: 2,
2945
+ check: (db) => tableColumns(db, "index_meta").length > 0
2946
+ });
2947
+ if (!rebuilt) this.dropAbandoned();
2948
+ return rebuilt;
2949
+ }
2950
+ setMeta(key, value) {
2951
+ this.stmt("INSERT INTO index_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
2952
+ }
2953
+ getMeta(key) {
2954
+ return this.stmt("SELECT value FROM index_meta WHERE key = ?").get(key)?.value;
2955
+ }
2956
+ stmt(sql) {
2957
+ let statement = this.statements.get(sql);
2958
+ if (statement === void 0) {
2959
+ statement = this.db.prepare(sql);
2960
+ this.statements.set(sql, statement);
2961
+ }
2962
+ return statement;
2963
+ }
2964
+ /**
2965
+ * This method does a write in one transaction. A transaction in progress takes the write in,
2966
+ * also a transaction that the caller opened on the connection. The write is then a savepoint of
2967
+ * that transaction.
2968
+ */
2969
+ write(work) {
2970
+ if (this.closed) throw new Error("the index is closed");
2971
+ this.depth += 1;
2972
+ try {
2973
+ return transaction(this.db, work, { nested: "savepoint" });
2974
+ } finally {
2975
+ this.depth -= 1;
2976
+ }
2977
+ }
2978
+ generation() {
2979
+ return Number(this.getMeta("generation") ?? "1");
2980
+ }
2981
+ /**
2982
+ * This method does a step on the tables of the current generation. A rebuild of a different
2983
+ * process can remove those tables in the meantime. Then the method reads the generation again
2984
+ * and does the step once more.
2985
+ */
2986
+ live(step) {
2987
+ if (this.closed) throw new Error("the index is closed");
2988
+ try {
2989
+ return step(namesOf(this.generation()));
2990
+ } catch (error) {
2991
+ if (!/no such table/i.test(messageOf$1(error)) || this.depth > 0) throw error;
2992
+ this.statements.clear();
2993
+ return step(namesOf(this.generation()));
2994
+ }
2995
+ }
2996
+ /** This method removes the tables of a generation. */
2997
+ dropGeneration(generation) {
2998
+ const n = namesOf(generation);
2999
+ for (const table of [
3000
+ n.fts,
3001
+ n.docs,
3002
+ n.versions,
3003
+ n.texts,
3004
+ n.latest
3005
+ ]) this.db.exec(`DROP TABLE IF EXISTS ${table}`);
3006
+ this.db.prepare("DELETE FROM index_meta WHERE key = ?").run(`building:${String(generation)}`);
3007
+ this.statements.clear();
3008
+ }
3009
+ /** This method removes the generations of builds that a stopped process left. */
3010
+ dropAbandoned() {
3011
+ const current = this.generation();
3012
+ const generations = /* @__PURE__ */ new Set();
3013
+ for (const { name } of this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()) {
3014
+ const match = GENERATION_TABLE.exec(name);
3015
+ if (match !== null) generations.add(Number(match[2]));
3016
+ }
3017
+ for (const generation of generations) {
3018
+ if (generation === current) continue;
3019
+ const started = this.getMeta(`building:${String(generation)}`);
3020
+ if (!((started === void 0 ? Number.POSITIVE_INFINITY : Date.now() - Date.parse(started)) < ABANDONED_MS)) this.dropGeneration(generation);
3021
+ }
3022
+ }
3023
+ putText(n, body) {
3024
+ const key = sha(body);
3025
+ this.stmt(`INSERT OR IGNORE INTO ${n.texts} (sha, body) VALUES (?, ?)`).run(key, body);
3026
+ return key;
3027
+ }
3028
+ textOf(n, key) {
3029
+ if (key === null) return void 0;
3030
+ return this.stmt(`SELECT body FROM ${n.texts} WHERE sha = ?`).get(key)?.body;
3031
+ }
3032
+ putVersion(n, input, now) {
3033
+ const full = input.full_text !== void 0 && input.full_text !== input.text ? this.putText(n, input.full_text) : null;
3034
+ this.stmt(`INSERT INTO ${n.versions} (doc, capture, recipe, rendered, fetched_at, blob, kind, title, url,
3035
+ meta_sha, text_sha, text_chars, full_sha, ai_input, merge, scope, labels)
3036
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3037
+ ON CONFLICT(doc, capture) DO UPDATE SET recipe = excluded.recipe, rendered = excluded.rendered,
3038
+ fetched_at = excluded.fetched_at, blob = excluded.blob, kind = excluded.kind, title = excluded.title,
3039
+ url = excluded.url, meta_sha = excluded.meta_sha, text_sha = excluded.text_sha,
3040
+ text_chars = excluded.text_chars, full_sha = excluded.full_sha, ai_input = excluded.ai_input,
3041
+ merge = excluded.merge, scope = excluded.scope, labels = excluded.labels`).run(input.doc, input.capture ?? input.captures[0] ?? "", input.recipe ?? "", input.rendered === true ? 1 : 0, input.fetched_at ?? now, input.blob ?? null, input.kind, input.title, input.url, this.putText(n, JSON.stringify(input.meta ?? {})), this.putText(n, input.text), input.text.length, full, input.ai_input ?? "unset", input.merge ?? "richest", input.scope ?? null, input.labels === void 0 ? null : JSON.stringify(input.labels));
3042
+ }
3043
+ /** This method gives the newest version of a document for one recipe and one variant, at `until` or before when it is given. */
3044
+ newest(n, doc, recipe, rendered, until) {
3045
+ if (until === void 0) return this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = ?
3046
+ ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered);
3047
+ return this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = ? AND fetched_at <= ?
3048
+ ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered, until);
3049
+ }
3050
+ /**
3051
+ * This method chooses the current version of a document with the rules of the class. With
3052
+ * `until`, it uses only the versions that the crawler fetched at that time or before. Thus it
3053
+ * gives the version that was current at that time. It gives undefined when no version agrees.
3054
+ */
3055
+ choose(n, doc, until) {
3056
+ const groups = until === void 0 ? this.stmt(`SELECT DISTINCT recipe, rendered FROM ${n.versions} WHERE doc = ?`).all(doc) : this.stmt(`SELECT DISTINCT recipe, rendered FROM ${n.versions} WHERE doc = ? AND fetched_at <= ?`).all(doc, until);
3057
+ if (groups.length === 0) return void 0;
3058
+ const byRecipe = /* @__PURE__ */ new Map();
3059
+ for (const group of groups) {
3060
+ const row = this.newest(n, doc, group.recipe, group.rendered, until);
3061
+ if (row === void 0) continue;
3062
+ const entry = byRecipe.get(group.recipe) ?? {};
3063
+ if (group.rendered === 1) entry.rendered = row;
3064
+ else entry.plain = row;
3065
+ byRecipe.set(group.recipe, entry);
3066
+ }
3067
+ const candidates = [];
3068
+ for (const [recipe, { plain, rendered }] of byRecipe) {
3069
+ let pick;
3070
+ if (rendered === void 0) pick = plain;
3071
+ else if (plain === void 0 || rendered.fetched_at >= plain.fetched_at) pick = rendered;
3072
+ else {
3073
+ const base = this.stmt(`SELECT blob FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = 0 AND fetched_at <= ?
3074
+ ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered.fetched_at);
3075
+ pick = base !== void 0 && base.blob !== null && base.blob === plain.blob ? rendered : plain;
3076
+ }
3077
+ const newest = plain === void 0 ? rendered : rendered === void 0 || plain.fetched_at > rendered.fetched_at ? plain : rendered;
3078
+ const others = [plain, rendered].filter((row) => row !== void 0 && row !== pick);
3079
+ candidates.push({
3080
+ row: pick,
3081
+ ai: newest.ai_input,
3082
+ others
3083
+ });
3084
+ }
3085
+ let winner = candidates[0];
3086
+ if (candidates.length > 1) {
3087
+ const latest = candidates.every((candidate) => candidate.row.merge === "latest");
3088
+ for (const candidate of candidates.slice(1)) {
3089
+ const a = candidate.row;
3090
+ const b = winner.row;
3091
+ if (latest ? a.fetched_at > b.fetched_at : a.text_chars > b.text_chars || a.text_chars === b.text_chars && a.fetched_at > b.fetched_at) winner = candidate;
3092
+ }
3093
+ }
3094
+ const aiInput = winner.row.ai_input === "no" || candidates.some((candidate) => candidate.ai === "no") ? "no" : winner.ai !== "unset" ? winner.ai : candidates.some((candidate) => candidate.ai === "yes") ? "yes" : "unset";
3095
+ return {
3096
+ winner,
3097
+ candidates,
3098
+ aiInput
3099
+ };
3100
+ }
3101
+ /** This method chooses the current version of a document from its versions, and writes it with its search entry. */
3102
+ recompute(n, doc, now) {
3103
+ const before = this.stmt(`SELECT rowid, text_sha, title FROM ${n.docs} WHERE doc = ?`).get(doc);
3104
+ const choice = this.choose(n, doc);
3105
+ if (choice === void 0) {
3106
+ if (before !== void 0) {
3107
+ this.stmt(`DELETE FROM ${n.fts} WHERE rowid = ?`).run(before.rowid);
3108
+ this.stmt(`DELETE FROM ${n.docs} WHERE doc = ?`).run(doc);
3109
+ }
3110
+ return;
3111
+ }
3112
+ const { winner, candidates, aiInput } = choice;
3113
+ const row = winner.row;
3114
+ let meta = parseJson(this.textOf(n, row.meta_sha), {});
3115
+ for (const candidate of candidates) if (candidate !== winner) meta = {
3116
+ ...parseJson(this.textOf(n, candidate.row.meta_sha), {}),
3117
+ ...meta
3118
+ };
3119
+ const same = this.stmt(`SELECT capture FROM ${n.versions} WHERE doc = ? AND text_sha = ?
3120
+ ORDER BY fetched_at DESC, capture DESC LIMIT ?`).all(doc, row.text_sha, 10);
3121
+ const captures = [.../* @__PURE__ */ new Set([
3122
+ row.capture,
3123
+ ...same.map((entry) => entry.capture),
3124
+ ...winner.others.map((other) => other.capture),
3125
+ ...candidates.filter((candidate) => candidate !== winner).map((candidate) => candidate.row.capture)
3126
+ ])].slice(0, 10);
3127
+ const count = this.stmt(`SELECT count(*) AS n FROM ${n.versions} WHERE doc = ?`).get(doc).n;
3128
+ const url = row.url ?? candidates.map((candidate) => candidate.row.url).find((value) => value !== null) ?? null;
3129
+ const saved = this.stmt(`INSERT INTO ${n.docs} (doc, kind, title, url, meta, text_sha, full_sha, captures, capture_count, capture,
3130
+ blob, fetched_at, recipe, rendered, ai_input, scope, labels, updated_at)
3131
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3132
+ ON CONFLICT(doc) DO UPDATE SET kind = excluded.kind, title = excluded.title, url = excluded.url,
3133
+ meta = excluded.meta, text_sha = excluded.text_sha, full_sha = excluded.full_sha,
3134
+ captures = excluded.captures, capture_count = excluded.capture_count, capture = excluded.capture,
3135
+ blob = excluded.blob, fetched_at = excluded.fetched_at, recipe = excluded.recipe,
3136
+ rendered = excluded.rendered, ai_input = excluded.ai_input, scope = excluded.scope,
3137
+ labels = excluded.labels, updated_at = excluded.updated_at
3138
+ RETURNING rowid`).get(doc, row.kind, row.title, url, JSON.stringify(meta), row.text_sha, row.full_sha, JSON.stringify(captures), count, row.capture, row.blob, row.fetched_at, row.recipe, row.rendered, aiInput, row.scope, row.labels, now);
3139
+ const text = this.textOf(n, row.text_sha) ?? "";
3140
+ if (before === void 0 || before.text_sha !== row.text_sha || before.title !== row.title) {
3141
+ if (before !== void 0) this.stmt(`DELETE FROM ${n.fts} WHERE rowid = ?`).run(before.rowid);
3142
+ this.stmt(`INSERT INTO ${n.fts} (rowid, title, text) VALUES (?, ?, ?)`).run(saved.rowid, fold(row.title, "search"), fold(text.length > MAX_INDEX_CHARS ? text.slice(0, MAX_INDEX_CHARS) : text, "search"));
3143
+ }
3144
+ return this.docOf(n, doc, text);
3145
+ }
3146
+ docOf(n, doc, knownText) {
3147
+ const row = this.stmt(`SELECT rowid, * FROM ${n.docs} WHERE doc = ?`).get(doc);
3148
+ if (row === void 0) return void 0;
3149
+ return this.toDoc(n, row, knownText);
3150
+ }
3151
+ toDoc(n, row, knownText) {
3152
+ const labels = parseJson(row.labels, void 0);
3153
+ return {
3154
+ doc: row.doc,
3155
+ kind: row.kind,
3156
+ title: row.title,
3157
+ text: knownText ?? this.textOf(n, row.text_sha) ?? "",
3158
+ url: row.url,
3159
+ meta: parseJson(row.meta, {}),
3160
+ captures: parseJson(row.captures, []),
3161
+ capture_count: row.capture_count,
3162
+ capture: row.capture,
3163
+ blob: row.blob,
3164
+ fetched_at: row.fetched_at,
3165
+ recipe: row.recipe,
3166
+ rendered: row.rendered === 1,
3167
+ ai_input: row.ai_input,
3168
+ cut: row.full_sha !== null,
3169
+ ...row.scope !== null ? { scope: row.scope } : {},
3170
+ ...labels !== void 0 ? { labels } : {},
3171
+ updated_at: row.updated_at
3172
+ };
3173
+ }
3174
+ versionTextOf(n, row) {
3175
+ return {
3176
+ ...toVersion(row),
3177
+ text: this.textOf(n, row.text_sha) ?? "",
3178
+ full_text: this.textOf(n, row.full_sha),
3179
+ meta: parseJson(this.textOf(n, row.meta_sha), {})
3180
+ };
3181
+ }
3182
+ get(doc) {
3183
+ return this.live((n) => this.docOf(n, doc));
3184
+ }
3185
+ /**
3186
+ * This method adds one version of a document, and it gives the current document. The rules of
3187
+ * the class choose the current version. An upsert of a known capture replaces that version.
3188
+ */
3189
+ upsert(input, now) {
3190
+ return this.live((n) => this.write(() => {
3191
+ this.putVersion(n, input, now);
3192
+ return this.recompute(n, input.doc, now);
3193
+ }));
3194
+ }
3195
+ /** This method gives the versions of a document, the newest first. */
3196
+ versions(doc, options = {}) {
3197
+ const limit = Math.max(1, Math.floor(options.limit ?? 100));
3198
+ return this.live((n) => this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? ORDER BY fetched_at DESC, capture DESC LIMIT ?`).all(doc, limit).map(toVersion));
3199
+ }
3200
+ /**
3201
+ * This method gives the text of one version of a document. With no capture, it gives the current
3202
+ * version. It also gives the text of a held-back version: the caller applies `isHeldBack` to the
3203
+ * `ai_input` of the version.
3204
+ */
3205
+ versionText(doc, capture) {
3206
+ return this.live((n) => {
3207
+ const id = capture ?? this.docOf(n, doc)?.capture;
3208
+ if (id === void 0) return void 0;
3209
+ const row = this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND capture = ?`).get(doc, id);
3210
+ return row === void 0 ? void 0 : this.versionTextOf(n, row);
3211
+ });
3212
+ }
3213
+ /**
3214
+ * This method gives the version of a document that was current at a time (ISO 8601). It applies
3215
+ * the rules of the class to the versions that the crawler fetched at that time or before. Thus
3216
+ * a later capture does not change the answer. It also gives a held-back version: its `ai_input`
3217
+ * is `no` when the document was held back at that time, and the caller applies `isHeldBack`.
3218
+ */
3219
+ versionAt(doc, at) {
3220
+ return this.live((n) => {
3221
+ const first = this.stmt(`SELECT min(fetched_at) AS first FROM ${n.versions} WHERE doc = ?`).get(doc)?.first ?? void 0;
3222
+ const choice = this.choose(n, doc, at);
3223
+ if (choice === void 0) return {
3224
+ version: void 0,
3225
+ first
3226
+ };
3227
+ const version = this.versionTextOf(n, choice.winner.row);
3228
+ return {
3229
+ version: choice.aiInput === "no" ? {
3230
+ ...version,
3231
+ ai_input: "no"
3232
+ } : version,
3233
+ first
3234
+ };
3235
+ });
3236
+ }
3237
+ /**
3238
+ * This method gives the texts of the earlier versions of a document, the newest first. Each
3239
+ * text comes one time, with the newest version that has it. It skips the current text. It also
3240
+ * gives held-back texts: the caller applies `isHeldBack` to the `ai_input` of each version.
3241
+ */
3242
+ earlierTexts(doc, options = {}) {
3243
+ const limit = Math.max(1, Math.floor(options.limit ?? 50));
3244
+ return this.live((n) => {
3245
+ const head = this.stmt(`SELECT text_sha FROM ${n.docs} WHERE doc = ?`).get(doc);
3246
+ if (head === void 0) return [];
3247
+ const rows = this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND text_sha != ? ORDER BY fetched_at DESC, capture DESC`).all(doc, head.text_sha);
3248
+ const seen = /* @__PURE__ */ new Set();
3249
+ const out = [];
3250
+ for (const row of rows) {
3251
+ if (seen.has(row.text_sha)) continue;
3252
+ seen.add(row.text_sha);
3253
+ out.push(this.versionTextOf(n, row));
3254
+ if (out.length >= limit) break;
3255
+ }
3256
+ return out;
3257
+ });
3258
+ }
3259
+ /** This method tells if a capture gave a version of a document. */
3260
+ hasVersion(capture) {
3261
+ return this.live((n) => this.stmt(`SELECT 1 AS found FROM ${n.versions} WHERE capture = ? LIMIT 1`).get(capture) !== void 0);
3262
+ }
3263
+ /**
3264
+ * This method gives the hash of the current text of documents, with no text. It gives the
3265
+ * documents of `docs`, or each document after `after` in the sequence of the ids, to `limit`.
3266
+ */
3267
+ digests(options = {}) {
3268
+ return this.live((n) => {
3269
+ if (options.docs !== void 0) {
3270
+ if (options.docs.length === 0) return [];
3271
+ return this.stmt(`SELECT doc, kind, ai_input, text_sha FROM ${n.docs} WHERE doc IN (SELECT value FROM json_each(?))`).all(JSON.stringify(options.docs));
3272
+ }
3273
+ const limit = Math.max(1, Math.floor(options.limit ?? 500));
3274
+ return this.stmt(`SELECT doc, kind, ai_input, text_sha FROM ${n.docs} WHERE doc > ? ORDER BY doc LIMIT ?`).all(options.after ?? "", limit);
3275
+ });
3276
+ }
3277
+ /** This method gives the newest fetch time of the cache entries, or undefined for an empty index. */
3278
+ newestFetch() {
3279
+ return this.live((n) => this.stmt(`SELECT max(fetched_at) AS newest FROM ${n.latest}`).get()?.newest ?? void 0);
3280
+ }
3281
+ /** This method gives the current documents that a capture gave. */
3282
+ docsOfCapture(capture) {
3283
+ return this.live((n) => this.stmt(`SELECT DISTINCT doc FROM ${n.versions} WHERE capture = ?`).all(capture).map((row) => this.docOf(n, row.doc)).filter((doc) => doc !== void 0));
3284
+ }
3285
+ /**
3286
+ * This method searches the documents with BM25, the best first. The syntax of the query is the
3287
+ * syntax of `parseQuery`. It first asks for each part. When that gives too few documents, it
3288
+ * adds the documents that match one part. A document that asked not to be AI input is not in
3289
+ * the results, so a search cannot show its text. The option `rank` chooses the ranking (`RankMode`).
3290
+ */
3291
+ find(q, options) {
3292
+ const rank = rankModeOf(options.rank);
3293
+ const query = parseQuery(q);
3294
+ if (query === void 0) return [];
3295
+ const limit = Math.max(1, Math.min(1e3, Math.floor(options.limit) || 10));
3296
+ return this.live((n) => {
3297
+ const kindClause = options.kind === void 0 || options.kind === null ? "" : "AND d.kind = ?";
3298
+ const sql = `SELECT d.rowid AS rowid, d.*, bm25(${n.fts}, 3.0, 1.0) AS rank
3299
+ FROM ${n.fts} JOIN ${n.docs} d ON d.rowid = ${n.fts}.rowid
3300
+ WHERE ${n.fts} MATCH ? AND d.ai_input != 'no' ${kindClause}
3301
+ ORDER BY rank LIMIT ?`;
3302
+ const run = (match) => {
3303
+ const params = [match];
3304
+ if (kindClause.length > 0) params.push(options.kind);
3305
+ params.push(limit);
3306
+ return this.stmt(sql).all(...params);
3307
+ };
3308
+ const rows = run(query.all);
3309
+ if (rows.length < limit && query.parts > 1) {
3310
+ const seen = new Set(rows.map((row) => row.doc));
3311
+ for (const row of run(rank === "fast" ? this.rareParts(n, query.anyParts) : query.any)) {
3312
+ if (rows.length >= limit) break;
3313
+ if (!seen.has(row.doc)) rows.push(row);
3314
+ }
3315
+ }
3316
+ return rows.map((row) => ({
3317
+ doc: row.doc,
3318
+ kind: row.kind,
3319
+ title: row.title,
3320
+ url: row.url,
3321
+ snippet: snippetOf(this.textOf(n, row.text_sha) ?? "", query.terms),
3322
+ score: Math.round(-row.rank * 1e3) / 1e3,
3323
+ ai_input: row.ai_input,
3324
+ fetched_at: row.fetched_at,
3325
+ capture: row.capture
3326
+ }));
3327
+ });
3328
+ }
3329
+ /**
3330
+ * This method scores a set of documents against a query, with the best first. It leaves out a
3331
+ * document that matches no term, and a document that asked not to be AI input. It ranks the
3332
+ * results of a source again, because the order of the source is only as good as its search engine.
3333
+ * In the mode `fast`, it also leaves out a document that holds only common parts (`RankMode`).
3334
+ */
3335
+ rankWithin(q, docs, options = {}) {
3336
+ const rank = rankModeOf(options.rank);
3337
+ const query = parseQuery(q);
3338
+ if (query === void 0 || docs.length === 0) return [];
3339
+ return this.live((n) => this.stmt(`SELECT d.doc AS doc, bm25(${n.fts}, 3.0, 1.0) AS rank
3340
+ FROM ${n.fts} JOIN ${n.docs} d ON d.rowid = ${n.fts}.rowid
3341
+ WHERE ${n.fts} MATCH ? AND d.ai_input != 'no' AND d.doc IN (SELECT value FROM json_each(?))
3342
+ ORDER BY rank`).all(rank === "fast" ? this.rareParts(n, query.anyParts) : query.any, JSON.stringify(docs)).map((row) => ({
3343
+ doc: row.doc,
3344
+ score: Math.round(-row.rank * 1e3) / 1e3
3345
+ })));
3346
+ }
3347
+ /**
3348
+ * This method gives the form of a query that needs one part, without the common parts (the mode
3349
+ * `fast` of `RankMode`). It counts the documents that hold each part. When each part is common,
3350
+ * it keeps the rarest part.
3351
+ */
3352
+ rareParts(n, parts) {
3353
+ if (parts.length < 2) return parts.join(" OR ");
3354
+ const total = this.stmt(`SELECT count(*) AS n FROM ${n.docs}`).get().n;
3355
+ const counted = parts.map((part) => ({
3356
+ part,
3357
+ count: this.stmt(`SELECT count(*) AS n FROM ${n.fts} WHERE ${n.fts} MATCH ?`).get(part).n
3358
+ }));
3359
+ const rare = counted.filter((one) => one.count <= FAST_RANK_SHARE * total);
3360
+ if (rare.length > 0) return rare.map((one) => one.part).join(" OR ");
3361
+ return counted.reduce((best, one) => one.count < best.count ? one : best).part;
3362
+ }
3363
+ /** This method gives the cache entry of a URL. The key is canonical, so two spellings of one URL give one entry. */
3364
+ latest(url, variant) {
3365
+ const key = keyOf(url, variant);
3366
+ return this.live((n) => {
3367
+ const row = this.stmt(`SELECT * FROM ${n.latest} WHERE url = ? AND variant = ?`).get(key.url, key.variant);
3368
+ return row === void 0 ? void 0 : toLatest(row);
3369
+ });
3370
+ }
3371
+ putLatest(n, entry) {
3372
+ const key = keyOf(entry.url, entry.variant);
3373
+ this.stmt(`INSERT INTO ${n.latest} (url, variant, capture, blob, etag, last_modified, content_type, fetched_at,
3374
+ status, ai_input, location, truncated, fresh_until, vary_key)
3375
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3376
+ ON CONFLICT(url, variant) DO UPDATE SET capture = excluded.capture, blob = excluded.blob,
3377
+ etag = excluded.etag, last_modified = excluded.last_modified, content_type = excluded.content_type,
3378
+ fetched_at = excluded.fetched_at, status = excluded.status, ai_input = excluded.ai_input,
3379
+ location = excluded.location, truncated = excluded.truncated, fresh_until = excluded.fresh_until,
3380
+ vary_key = excluded.vary_key
3381
+ WHERE excluded.fetched_at >= ${n.latest}.fetched_at`).run(key.url, key.variant, entry.capture, entry.blob, entry.etag, entry.last_modified, entry.content_type, entry.fetched_at, entry.status, entry.ai_input, entry.location ?? null, entry.truncated === true ? 1 : null, entry.fresh_until ?? null, entry.vary_key ?? null);
3382
+ }
3383
+ /** This method keeps the last answer for a URL. An entry that is older than the stored entry changes nothing. */
3384
+ setLatest(entry) {
3385
+ this.live((n) => this.write(() => this.putLatest(n, entry)));
3386
+ }
3387
+ counts() {
3388
+ return this.live((n) => ({
3389
+ docs: this.stmt(`SELECT count(*) AS n FROM ${n.docs}`).get().n,
3390
+ urls: this.stmt(`SELECT count(*) AS n FROM ${n.latest}`).get().n
3391
+ }));
3392
+ }
3393
+ /** This method empties the current generation. A rebuild uses `beginRebuild`, which keeps the index until its commit. */
3394
+ reset() {
3395
+ this.live((n) => this.write(() => {
3396
+ for (const table of [
3397
+ n.fts,
3398
+ n.docs,
3399
+ n.versions,
3400
+ n.texts,
3401
+ n.latest
3402
+ ]) this.db.exec(`DELETE FROM ${table}`);
3403
+ }));
3404
+ }
3405
+ /**
3406
+ * This method starts a rebuild into a new generation of the tables. The current generation
3407
+ * answers each read and takes each write until the commit. A failed rebuild thus leaves the
3408
+ * index as it was.
3409
+ */
3410
+ beginRebuild(options = {}) {
3411
+ const batchSize = Math.max(1, Math.floor(options.batch ?? 500));
3412
+ const generation = this.write(() => {
3413
+ const next = Number(this.getMeta("next_generation") ?? "2");
3414
+ this.setMeta("next_generation", String(next + 1));
3415
+ this.setMeta(`building:${String(next)}`, (/* @__PURE__ */ new Date()).toISOString());
3416
+ this.db.exec(ddlOf(namesOf(next)));
3417
+ return next;
3418
+ });
3419
+ const n = namesOf(generation);
3420
+ const versions = [];
3421
+ const latest = /* @__PURE__ */ new Map();
3422
+ let open = true;
3423
+ const keyText = (url, variant) => {
3424
+ const key = keyOf(url, variant);
3425
+ return `${key.variant} ${key.url}`;
3426
+ };
3427
+ const flush = () => {
3428
+ if (!open) throw new Error("the rebuild is over");
3429
+ if (versions.length === 0 && latest.size === 0) return;
3430
+ this.write(() => {
3431
+ const touched = /* @__PURE__ */ new Map();
3432
+ for (const { input, now } of versions) {
3433
+ this.putVersion(n, input, now);
3434
+ touched.set(input.doc, now);
3435
+ }
3436
+ for (const entry of latest.values()) this.putLatest(n, entry);
3437
+ for (const [doc, now] of touched) this.recompute(n, doc, now);
3438
+ });
3439
+ versions.length = 0;
3440
+ latest.clear();
3441
+ };
3442
+ /** This function copies the texts of the versions of the current generation that agree with `where`. */
3443
+ const copyTexts = (current, where, params) => {
3444
+ for (const column of [
3445
+ "text_sha",
3446
+ "meta_sha",
3447
+ "full_sha"
3448
+ ]) this.db.prepare(`INSERT OR IGNORE INTO ${n.texts} (sha, body)
3449
+ SELECT t.sha, t.body FROM ${current.texts} t
3450
+ WHERE t.sha IN (SELECT ${column} FROM ${current.versions} WHERE ${where})`).run(...params);
3451
+ };
3452
+ return {
3453
+ upsert: (input, now) => {
3454
+ if (!open) throw new Error("the rebuild is over");
3455
+ versions.push({
3456
+ input,
3457
+ now
3458
+ });
3459
+ if (versions.length >= batchSize) flush();
3460
+ },
3461
+ setLatest: (entry) => {
3462
+ if (!open) throw new Error("the rebuild is over");
3463
+ const key = keyText(entry.url, entry.variant);
3464
+ const before = latest.get(key);
3465
+ if (before === void 0 || entry.fetched_at >= before.fetched_at) latest.set(key, entry);
3466
+ if (latest.size >= batchSize) flush();
3467
+ },
3468
+ latest: (url, variant) => {
3469
+ const waiting = latest.get(keyText(url, variant));
3470
+ if (waiting !== void 0) return waiting;
3471
+ const key = keyOf(url, variant);
3472
+ const row = this.stmt(`SELECT * FROM ${n.latest} WHERE url = ? AND variant = ?`).get(key.url, key.variant);
3473
+ return row === void 0 ? void 0 : toLatest(row);
3474
+ },
3475
+ flush,
3476
+ carry: (recipes) => {
3477
+ flush();
3478
+ const known = JSON.stringify([...recipes]);
3479
+ const current = namesOf(this.generation());
3480
+ const docs = this.db.prepare(`SELECT DISTINCT doc FROM ${current.versions} WHERE recipe NOT IN (SELECT value FROM json_each(?))`).all(known);
3481
+ const where = "recipe NOT IN (SELECT value FROM json_each(?)) AND doc IN (SELECT value FROM json_each(?))";
3482
+ for (let at = 0; at < docs.length; at += batchSize) {
3483
+ const part = JSON.stringify(docs.slice(at, at + batchSize).map((row) => row.doc));
3484
+ this.write(() => {
3485
+ copyTexts(current, where, [known, part]);
3486
+ this.db.prepare(`INSERT OR IGNORE INTO ${n.versions} SELECT * FROM ${current.versions} WHERE ${where}`).run(known, part);
3487
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3488
+ for (const doc of JSON.parse(part)) this.recompute(n, doc, now);
3489
+ });
3490
+ }
3491
+ return docs.length;
3492
+ },
3493
+ commit: (since) => {
3494
+ flush();
3495
+ open = false;
3496
+ return this.write(() => {
3497
+ const current = this.generation();
3498
+ const old = namesOf(current);
3499
+ copyTexts(old, "fetched_at >= ?", [since]);
3500
+ const added = this.db.prepare(`SELECT DISTINCT doc FROM ${old.versions} WHERE fetched_at >= ?`).all(since);
3501
+ this.db.prepare(`INSERT OR IGNORE INTO ${n.versions} SELECT * FROM ${old.versions} WHERE fetched_at >= ?`).run(since);
3502
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3503
+ for (const { doc } of added) this.recompute(n, doc, now);
3504
+ for (const row of this.db.prepare(`SELECT * FROM ${old.latest} WHERE fetched_at >= ?`).all(since)) this.putLatest(n, toLatest(row));
3505
+ this.setMeta("generation", String(generation));
3506
+ this.db.prepare("DELETE FROM index_meta WHERE key = ?").run(`building:${String(generation)}`);
3507
+ this.dropGeneration(current);
3508
+ this.empty = false;
3509
+ return {
3510
+ docs: this.db.prepare(`SELECT count(*) AS n FROM ${n.docs}`).get().n,
3511
+ urls: this.db.prepare(`SELECT count(*) AS n FROM ${n.latest}`).get().n
3512
+ };
3513
+ });
3514
+ },
3515
+ abort: () => {
3516
+ open = false;
3517
+ versions.length = 0;
3518
+ latest.clear();
3519
+ if (this.closed) return;
3520
+ this.write(() => this.dropGeneration(generation));
3521
+ }
3522
+ };
3523
+ }
3524
+ /** This method closes the file. A second close does nothing. */
3525
+ close() {
3526
+ if (this.closed) return;
3527
+ this.closed = true;
3528
+ this.statements.clear();
3529
+ this.db.close();
3530
+ }
3531
+ };
2745
3532
  // src/pdf.ts
2746
3533
  const MAX_PAGES = 500;
2747
3534
  const MAX_CHARS = 2e5;
@@ -4369,6 +5156,6 @@ const catchUpIndex = async (runtime) => {
4369
5156
  errors: tally.errors
4370
5157
  };
4371
5158
  };
4372
- export { DEADLINE_NOTE as A, fold as C, snippetOf as D, parseQuery as E, EgressRefused as F, egressLookup as I, makeRecord as M, sha256 as N, CAPTURE_SCHEMA as O, stableStringify as P, readPdf as S, locate as T, archivedDocId as _, fetchPage as a, fallbackReason as b, isHeldBack as c, recordOverride as d, reindex as f, archivedCopy as g, archiveExtractor as h, fetchAndIndex as i, DEFAULT_SECRET_PARAMS as j, Crawler as k, isoTime as l, versionAtTime as m, HELD_BACK as n, findDocuments as o, verifyQuote as p, catchUpIndex as r, heldBackMeta as s, Extractors as t, readDocument as u, archivedNote as v, foldText as w, isPdf as x, archivedOf as y };
5159
+ export { snippetOf as A, DocIndex as C, foldText as D, fold as E, makeRecord as F, sha256 as I, stableStringify as L, Crawler as M, DEADLINE_NOTE as N, locate as O, DEFAULT_SECRET_PARAMS as P, EgressRefused as R, readPdf as S, NO_EMBEDDER as T, archivedDocId as _, fetchPage as a, fallbackReason as b, isHeldBack as c, recordOverride as d, reindex as f, archivedCopy as g, archiveExtractor as h, fetchAndIndex as i, CAPTURE_SCHEMA as j, parseQuery as k, isoTime as l, versionAtTime as m, HELD_BACK as n, findDocuments as o, verifyQuote as p, catchUpIndex as r, heldBackMeta as s, Extractors as t, readDocument as u, archivedNote as v, FAST_RANK_SHARE as w, isPdf as x, archivedOf as y, egressLookup as z };
4373
5160
 
4374
- //# sourceMappingURL=runtime-BVC7iOG4.mjs.map
5161
+ //# sourceMappingURL=runtime-DMem_UuO.mjs.map