llm-large-files 0.1.0 → 0.3.0

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 (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
package/src/plan.ts CHANGED
@@ -1,98 +1,120 @@
1
- import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
- import type { SearchableDocument } from "./search.js";
3
-
4
- /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
- const REQUEST_BYTES_MARGIN = 256 * 1024;
6
- const CARD_HEAD_LINES = 25;
7
- const CARD_OUTLINE_ENTRIES = 40;
8
-
9
- /**
10
- * Decides which documents go into the prompt in full and which the model reaches through
11
- * tools. Smaller documents are inlined first, so as many as possible are read in full.
12
- */
13
- export function planDocuments(
14
- documents: DocumentMeta[],
15
- budget: Budget,
16
- base: { tokens: number; bytes: number },
17
- ): DocumentPlan {
18
- const tokenRoom = Math.min(budget.inlineTokens, budget.contextTokens - budget.reservedTokens - base.tokens);
19
- const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
20
- const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
21
- for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
22
- const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
23
- if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
24
- plan.inline.push(meta);
25
- plan.inlineTokens += meta.estimatedTokens;
26
- plan.inlineBytes += bytes;
27
- } else {
28
- plan.searchable.push(meta);
29
- }
30
- }
31
- return plan;
32
- }
33
-
34
- function formatCount(value: number): string {
35
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
36
- if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
37
- return value.toLocaleString("en-US");
38
- }
39
-
40
- export function formatBytes(bytes: number): string {
41
- if (bytes >= 1024 * 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
42
- if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
43
- return `${bytes} B`;
44
- }
45
-
46
- /** "L12 Title" lines, indented relative to the shallowest heading. */
47
- export function outlineLines(outline: OutlineEntry[]): string[] {
48
- const top = Math.min(...outline.map((entry) => entry.level));
49
- return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
50
- }
51
-
52
- export function renderInline(document: SearchableDocument): string {
53
- const { meta } = document;
54
- return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
55
- }
56
-
57
- /** A compact stand-in for a document that is too large for the prompt. */
58
- export function renderCard(document: SearchableDocument): string {
59
- const { meta } = document;
60
- const out = [
61
- `--- Large attached file: ${meta.name} ---`,
62
- `document_id: ${meta.id}`,
63
- `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
64
- "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
65
- ];
66
- const profile = meta.logProfile;
67
- if (profile) {
68
- const levels = Object.entries(profile.levels).map(([level, count]) => `${level} ${count.toLocaleString("en-US")}`).join(", ");
69
- if (levels) out.push(`Log levels: ${levels}`);
70
- if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
71
- if (profile.topIssues.length) {
72
- out.push("Most frequent problems (count, first line):");
73
- for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${issue.template}`);
74
- }
75
- }
76
- if (meta.outline.length) {
77
- out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
78
- out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
79
- }
80
- out.push(`First lines:`, document.lines.numbered(1, CARD_HEAD_LINES).split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
81
- out.push(`--- End large attached file: ${meta.name} ---`);
82
- return out.join("\n");
83
- }
84
-
85
- export function documentToolsInstruction(searchable: DocumentMeta[]): string {
86
- if (searchable.length === 0) return "";
87
- const names = searchable.map((meta) => `${meta.name} (document_id ${meta.id})`).join("; ");
88
- return [
89
- `Some attached files are too large for your context: ${names}.`,
90
- "You see only a summary card for each. Read them through the tools:",
91
- "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
92
- "- read_document reads a line range. Read around search hits before you rely on them.",
93
- "- get_document_overview returns the outline, log profile, and the start and end of a file.",
94
- "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
95
- "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
96
- "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
97
- ].join("\n");
98
- }
1
+ import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
+ import type { SearchableDocument } from "./search.js";
3
+
4
+ /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
+ export const REQUEST_BYTES_MARGIN = 256 * 1024;
6
+ const CARD_HEAD_LINES = 25;
7
+ const CARD_OUTLINE_ENTRIES = 40;
8
+
9
+ /**
10
+ * Decides which documents go into the prompt in full and which the model reaches through
11
+ * tools. Smaller documents are inlined first, so as many as possible are read in full.
12
+ */
13
+ export function planDocuments(
14
+ documents: DocumentMeta[],
15
+ budget: Budget,
16
+ base: { tokens: number; bytes: number },
17
+ ): DocumentPlan {
18
+ const tokenRoom = Math.min(budget.inlineTokens, budget.contextTokens - budget.reservedTokens - base.tokens);
19
+ const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
20
+ const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
21
+ for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
22
+ const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
23
+ if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
24
+ plan.inline.push(meta);
25
+ plan.inlineTokens += meta.estimatedTokens;
26
+ plan.inlineBytes += bytes;
27
+ } else {
28
+ plan.searchable.push(meta);
29
+ }
30
+ }
31
+ return plan;
32
+ }
33
+
34
+ function formatCount(value: number): string {
35
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
36
+ if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
37
+ return value.toLocaleString("en-US");
38
+ }
39
+
40
+ export function formatBytes(bytes: number): string {
41
+ if (bytes >= 1024 * 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
42
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
43
+ return `${bytes} B`;
44
+ }
45
+
46
+ /** "L12 Title" lines, indented relative to the shallowest heading. */
47
+ export function outlineLines(outline: OutlineEntry[]): string[] {
48
+ let top = Number.POSITIVE_INFINITY;
49
+ for (const entry of outline) if (entry.level < top) top = entry.level;
50
+ return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
51
+ }
52
+
53
+ export function renderInline(document: SearchableDocument): string {
54
+ const { meta } = document;
55
+ return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
56
+ }
57
+
58
+ /**
59
+ * A compact stand-in for a document that is too large for the prompt. `viewable` adds a line
60
+ * saying that its pages can be looked at with `view_pages`.
61
+ */
62
+ export function renderCard(document: SearchableDocument, viewable = false): string {
63
+ const { meta } = document;
64
+ const out = [
65
+ `--- Large attached file: ${meta.name} ---`,
66
+ `document_id: ${meta.id}`,
67
+ `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
68
+ "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
69
+ ...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
70
+ ];
71
+ const profile = meta.logProfile;
72
+ if (profile) {
73
+ const levels = Object.entries(profile.levels).map(([level, count]) => `${level} ${count.toLocaleString("en-US")}`).join(", ");
74
+ if (levels) out.push(`Log levels: ${levels}`);
75
+ if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
76
+ if (profile.topIssues.length) {
77
+ out.push("Most frequent problems (count, first line):");
78
+ for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${issue.template}`);
79
+ }
80
+ }
81
+ if (meta.outline.length) {
82
+ out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
83
+ out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
84
+ }
85
+ out.push(`First lines:`, document.lines.numbered(1, CARD_HEAD_LINES).split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
86
+ out.push(`--- End large attached file: ${meta.name} ---`);
87
+ return out.join("\n");
88
+ }
89
+
90
+ /**
91
+ * The tool guide for the system prompt. `searchable` are the files the model reads through the
92
+ * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
93
+ * may be searchable, and some may have their whole text in the prompt.
94
+ */
95
+ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = []): string {
96
+ // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
97
+ const named = (meta: DocumentMeta, detail = "") => `${JSON.stringify(meta.name)} (document_id ${meta.id}${detail})`;
98
+ const guide: string[] = [];
99
+ if (searchable.length > 0) {
100
+ guide.push(
101
+ `Some attached files are too large for your context: ${searchable.map((meta) => named(meta)).join("; ")}.`,
102
+ "You see only a summary card for each. Read them through the tools:",
103
+ "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
104
+ "- read_document reads a line range. Read around search hits before you rely on them.",
105
+ "- get_document_overview returns the outline, log profile, and the start and end of a file.",
106
+ "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
107
+ "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
108
+ "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
109
+ );
110
+ }
111
+ if (viewable.length > 0) {
112
+ guide.push(
113
+ `The text of a PDF does not show its pictures, charts or diagrams. You can look at the real pages of these PDFs with view_pages: ${viewable.map((meta) => named(meta, meta.pages ? `, ${meta.pages} ${meta.pages === 1 ? "page" : "pages"}` : "")).join("; ")}.`,
114
+ "- Use view_pages when the answer depends on a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or on how a page is laid out. A page is worth a look when its text says it has a picture or has no text, or mentions a figure.",
115
+ "- Page numbers are the N of the \"--- Page N ---\" lines in the text. Ask only for the pages you need: you have a limited number of tool turns.",
116
+ "- Do not use view_pages to read text, and do not describe a picture you have not looked at. If you could not look at a page, say so.",
117
+ );
118
+ }
119
+ return guide.join("\n");
120
+ }
package/src/search.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { LineIndex } from "./text.js";
1
+ import { createContext, Script, type Context } from "node:vm";
2
+ import { foldCase, LineIndex } from "./text.js";
2
3
  import type { DocumentMeta, StoredDocument } from "./types.js";
3
4
 
4
5
  const PASSAGE_CHARACTERS = 1_500;
@@ -20,6 +21,7 @@ export class SearchableDocument {
20
21
  readonly lines: LineIndex;
21
22
  private lowerText?: string;
22
23
  private passageStarts?: number[];
24
+ private pageStarts?: number[];
23
25
 
24
26
  constructor(document: StoredDocument) {
25
27
  this.meta = document.meta;
@@ -27,13 +29,10 @@ export class SearchableDocument {
27
29
  this.lines = new LineIndex(document.text);
28
30
  }
29
31
 
30
- /** Lowercased text for case-insensitive search, or undefined if lowercasing changes offsets. */
31
- get lower(): string | undefined {
32
- if (this.lowerText === undefined) {
33
- const lower = this.text.toLowerCase();
34
- this.lowerText = lower.length === this.text.length ? lower : "";
35
- }
36
- return this.lowerText || undefined;
32
+ /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
33
+ get lower(): string {
34
+ this.lowerText ??= foldCase(this.text);
35
+ return this.lowerText;
37
36
  }
38
37
 
39
38
  /** First line of each passage: groups of lines up to about 1,500 characters. */
@@ -72,6 +71,42 @@ export class SearchableDocument {
72
71
  }
73
72
  return low;
74
73
  }
74
+
75
+ /**
76
+ * The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
77
+ * a text without them, and for lines above the first one. Only markers that count up from 1 are
78
+ * used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
79
+ */
80
+ pageOfLine(line: number): number | undefined {
81
+ if (!this.pageStarts) {
82
+ const starts: number[] = [];
83
+ const marker = "--- Page ";
84
+ for (let at = this.text.indexOf(marker); at !== -1; at = this.text.indexOf(marker, at + marker.length)) {
85
+ if (at > 0 && this.text[at - 1] !== "\n") continue;
86
+ const found = this.lines.lineAt(at);
87
+ if (this.lines.line(found) === `--- Page ${starts.length + 1} ---`) starts.push(found);
88
+ }
89
+ this.pageStarts = starts;
90
+ }
91
+ const starts = this.pageStarts;
92
+ if (starts.length === 0 || line < starts[0]!) return undefined;
93
+ let low = 0;
94
+ let high = starts.length - 1;
95
+ while (low < high) {
96
+ const middle = (low + high + 1) >> 1;
97
+ if (starts[middle]! <= line) low = middle;
98
+ else high = middle - 1;
99
+ }
100
+ return low + 1;
101
+ }
102
+
103
+ /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
104
+ pagesOfLines(from: number, to: number): string | undefined {
105
+ const last = this.pageOfLine(to);
106
+ if (last === undefined) return undefined;
107
+ const first = this.pageOfLine(from) ?? 1;
108
+ return first === last ? String(last) : `${first}-${last}`;
109
+ }
75
110
  }
76
111
 
77
112
  export type LineMatch = { line: number; text: string; before?: string[]; after?: string[] };
@@ -89,7 +124,36 @@ function clip(line: string, column: number): string {
89
124
  return `${start > 0 ? "…" : ""}${line.slice(start, start + SHOWN_LINE_CHARACTERS)}${start + SHOWN_LINE_CHARACTERS < line.length ? "…" : ""}`;
90
125
  }
91
126
 
92
- /** Rejects patterns with nested quantifiers such as (a+)+, the usual cause of catastrophic backtracking. */
127
+ const RUN_SCAN = new Script("scan()");
128
+ let scanSandbox: { scan: () => void } | undefined;
129
+ let scanContext: Context | undefined;
130
+
131
+ /**
132
+ * Runs `scan` and stops it after `milliseconds`, returning false if it was stopped.
133
+ *
134
+ * A check between lines cannot interrupt one regex match, and a pattern such as `(a|a)+$` can
135
+ * take longer than the age of the universe on a single 40-character line. Node's `vm` timeout
136
+ * can: V8 checks for it while a regex backtracks, even in a function called from the script.
137
+ */
138
+ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
139
+ scanSandbox ??= { scan };
140
+ scanContext ??= createContext(scanSandbox);
141
+ scanSandbox.scan = scan;
142
+ try {
143
+ RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
144
+ return true;
145
+ } catch (error) {
146
+ if ((error as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return false;
147
+ throw error;
148
+ } finally {
149
+ scanSandbox.scan = () => undefined;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * A quick refusal for the most common catastrophic shape, a nested quantifier such as (a+)+.
155
+ * It does not catch every slow pattern; the time limit in `grep` is what bounds the search.
156
+ */
93
157
  export function unsafeRegexReason(pattern: string): string | null {
94
158
  if (pattern.length > 300) return "Regex is longer than 300 characters.";
95
159
  if (/\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/.test(pattern)) {
@@ -107,7 +171,7 @@ export function unsafeRegexReason(pattern: string): string | null {
107
171
  export function grep(
108
172
  document: SearchableDocument,
109
173
  query: string,
110
- options: { regex?: boolean; caseSensitive?: boolean; maxResults: number; contextLines: number },
174
+ options: { regex?: boolean; caseSensitive?: boolean; maxResults: number; contextLines: number; /** Regex mode only. Defaults to 3 seconds. */ timeLimitMs?: number },
111
175
  ): GrepResult {
112
176
  const { lines } = document;
113
177
  if (!query) throw new Error("The search query is empty.");
@@ -123,20 +187,16 @@ export function grep(
123
187
  const problem = unsafeRegexReason(query);
124
188
  if (problem) throw new Error(problem);
125
189
  const pattern = new RegExp(query, options.caseSensitive ? "" : "i");
126
- const started = Date.now();
127
- for (let line = 1; line <= lines.lineCount; line++) {
128
- const text = lines.line(line);
129
- const match = pattern.exec(text);
130
- if (match) record(line, match.index);
131
- if (line % 2_000 === 0 && Date.now() - started > REGEX_TIME_LIMIT_MS) {
132
- stoppedEarly = true;
133
- break;
190
+ const finished = withinTimeLimit(() => {
191
+ for (let line = 1; line <= lines.lineCount; line++) {
192
+ const match = pattern.exec(lines.line(line));
193
+ if (match) record(line, match.index);
134
194
  }
135
- }
195
+ }, options.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
196
+ if (!finished) stoppedEarly = true;
136
197
  } else {
137
- const lower = options.caseSensitive ? undefined : document.lower;
138
- const haystack = options.caseSensitive || !lower ? document.text : lower;
139
- const needle = options.caseSensitive || !lower ? query : query.toLowerCase();
198
+ const haystack = options.caseSensitive ? document.text : document.lower;
199
+ const needle = options.caseSensitive ? query : foldCase(query);
140
200
  let lastLine = 0;
141
201
  for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + needle.length)) {
142
202
  const line = lines.lineAt(at);
@@ -165,7 +225,7 @@ export function grep(
165
225
  }
166
226
 
167
227
  export function queryTerms(query: string): string[] {
168
- const terms = query.toLowerCase().split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
228
+ const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
169
229
  return [...new Set(terms)].slice(0, 12);
170
230
  }
171
231
 
@@ -178,7 +238,7 @@ export type RankedPassage = { from: number; to: number; score: number };
178
238
  export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
179
239
  const terms = queryTerms(query);
180
240
  if (terms.length === 0) return [];
181
- const haystack = document.lower ?? document.text;
241
+ const haystack = document.lower;
182
242
  const passageCount = document.passages.length;
183
243
  const averageLength = Math.max(1, document.text.length / passageCount);
184
244
  const scores = new Map<number, number>();
@@ -201,7 +261,7 @@ export function rankPassages(document: SearchableDocument, query: string, topK:
201
261
  }
202
262
  }
203
263
  // Passages that contain the whole phrase rank above passages with scattered terms.
204
- const phrase = query.trim().toLowerCase();
264
+ const phrase = foldCase(query.trim());
205
265
  if (terms.length > 1 && phrase.length <= 200) {
206
266
  const withPhrase = new Set<number>();
207
267
  for (let at = haystack.indexOf(phrase); at !== -1 && withPhrase.size < 10_000; at = haystack.indexOf(phrase, at + phrase.length)) {