llm-large-files 0.7.0 → 0.8.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 (184) hide show
  1. package/CHANGELOG.md +319 -1
  2. package/README.md +10 -8
  3. package/dist/analyze.d.ts +3 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +109 -14
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts.map +1 -1
  8. package/dist/anthropic/adapter.js +4 -1
  9. package/dist/anthropic/adapter.js.map +1 -1
  10. package/dist/ask.d.ts +3 -3
  11. package/dist/ask.d.ts.map +1 -1
  12. package/dist/ask.js +72 -17
  13. package/dist/ask.js.map +1 -1
  14. package/dist/decode.d.ts +19 -0
  15. package/dist/decode.d.ts.map +1 -0
  16. package/dist/decode.js +97 -0
  17. package/dist/decode.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +65 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/events.d.ts +6 -0
  23. package/dist/events.d.ts.map +1 -1
  24. package/dist/events.js +5 -1
  25. package/dist/events.js.map +1 -1
  26. package/dist/evidence.d.ts.map +1 -1
  27. package/dist/evidence.js +6 -0
  28. package/dist/evidence.js.map +1 -1
  29. package/dist/extract.d.ts +7 -20
  30. package/dist/extract.d.ts.map +1 -1
  31. package/dist/extract.js +49 -751
  32. package/dist/extract.js.map +1 -1
  33. package/dist/gemini/adapter.d.ts.map +1 -1
  34. package/dist/gemini/adapter.js +9 -5
  35. package/dist/gemini/adapter.js.map +1 -1
  36. package/dist/gemini/endpoints.d.ts +5 -1
  37. package/dist/gemini/endpoints.d.ts.map +1 -1
  38. package/dist/gemini/endpoints.js +11 -2
  39. package/dist/gemini/endpoints.js.map +1 -1
  40. package/dist/gemini/generate.d.ts.map +1 -1
  41. package/dist/gemini/generate.js +20 -3
  42. package/dist/gemini/generate.js.map +1 -1
  43. package/dist/groups.d.ts +54 -0
  44. package/dist/groups.d.ts.map +1 -0
  45. package/dist/groups.js +136 -0
  46. package/dist/groups.js.map +1 -0
  47. package/dist/html.d.ts +11 -0
  48. package/dist/html.d.ts.map +1 -0
  49. package/dist/html.js +1112 -0
  50. package/dist/html.js.map +1 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts.map +1 -1
  56. package/dist/library.js +48 -12
  57. package/dist/library.js.map +1 -1
  58. package/dist/limiter.d.ts +2 -1
  59. package/dist/limiter.d.ts.map +1 -1
  60. package/dist/limiter.js +3 -2
  61. package/dist/limiter.js.map +1 -1
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +8 -1
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts.map +1 -1
  66. package/dist/node/handlers.js +69 -15
  67. package/dist/node/handlers.js.map +1 -1
  68. package/dist/node/index.d.ts +2 -0
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +1 -0
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/ingest-child.d.ts +38 -0
  73. package/dist/node/ingest-child.d.ts.map +1 -0
  74. package/dist/node/ingest-child.js +42 -0
  75. package/dist/node/ingest-child.js.map +1 -0
  76. package/dist/node/isolated.d.ts +88 -0
  77. package/dist/node/isolated.d.ts.map +1 -0
  78. package/dist/node/isolated.js +381 -0
  79. package/dist/node/isolated.js.map +1 -0
  80. package/dist/office.d.ts +105 -0
  81. package/dist/office.d.ts.map +1 -0
  82. package/dist/office.js +1092 -0
  83. package/dist/office.js.map +1 -0
  84. package/dist/openai/adapter.d.ts.map +1 -1
  85. package/dist/openai/adapter.js +15 -1
  86. package/dist/openai/adapter.js.map +1 -1
  87. package/dist/pdf-pages.d.ts.map +1 -1
  88. package/dist/pdf-pages.js +2 -6
  89. package/dist/pdf-pages.js.map +1 -1
  90. package/dist/peers.d.ts +8 -0
  91. package/dist/peers.d.ts.map +1 -0
  92. package/dist/peers.js +32 -0
  93. package/dist/peers.js.map +1 -0
  94. package/dist/plan.d.ts.map +1 -1
  95. package/dist/plan.js +1 -1
  96. package/dist/plan.js.map +1 -1
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +4 -2
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/search.d.ts +99 -22
  101. package/dist/search.d.ts.map +1 -1
  102. package/dist/search.js +744 -140
  103. package/dist/search.js.map +1 -1
  104. package/dist/text-index.d.ts +3 -1
  105. package/dist/text-index.d.ts.map +1 -1
  106. package/dist/text-index.js +3 -1
  107. package/dist/text-index.js.map +1 -1
  108. package/dist/text.d.ts +27 -3
  109. package/dist/text.d.ts.map +1 -1
  110. package/dist/text.js +225 -23
  111. package/dist/text.js.map +1 -1
  112. package/dist/tools.d.ts.map +1 -1
  113. package/dist/tools.js +200 -12
  114. package/dist/tools.js.map +1 -1
  115. package/dist/types.d.ts +3 -3
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/word-styles.d.ts +102 -0
  118. package/dist/word-styles.d.ts.map +1 -0
  119. package/dist/word-styles.js +419 -0
  120. package/dist/word-styles.js.map +1 -0
  121. package/dist/xlsx.d.ts +23 -0
  122. package/dist/xlsx.d.ts.map +1 -0
  123. package/dist/xlsx.js +511 -0
  124. package/dist/xlsx.js.map +1 -0
  125. package/dist/xml-stream.d.ts +55 -0
  126. package/dist/xml-stream.d.ts.map +1 -0
  127. package/dist/xml-stream.js +235 -0
  128. package/dist/xml-stream.js.map +1 -0
  129. package/docs/README.md +8 -8
  130. package/docs/getting-started.md +1 -1
  131. package/docs/guides/costs-and-limits.md +7 -5
  132. package/docs/guides/deployment.md +95 -29
  133. package/docs/guides/errors-and-reliability.md +23 -10
  134. package/docs/guides/pdfs.md +127 -74
  135. package/docs/guides/storage.md +1 -1
  136. package/docs/guides/testing.md +5 -1
  137. package/docs/guides/web-app.md +10 -9
  138. package/docs/how-it-works.md +73 -50
  139. package/docs/reference/ask.md +26 -8
  140. package/docs/reference/errors-and-retries.md +5 -3
  141. package/docs/reference/events.md +14 -6
  142. package/docs/reference/gemini.md +6 -2
  143. package/docs/reference/library.md +205 -74
  144. package/docs/reference/node.md +200 -22
  145. package/docs/reference/openai.md +1 -1
  146. package/docs/reference/tools.md +170 -22
  147. package/docs/security.md +114 -69
  148. package/docs/troubleshooting.md +40 -20
  149. package/package.json +6 -2
  150. package/src/analyze.ts +117 -13
  151. package/src/anthropic/adapter.ts +4 -1
  152. package/src/ask.ts +73 -17
  153. package/src/decode.ts +89 -0
  154. package/src/errors.ts +108 -0
  155. package/src/events.ts +10 -1
  156. package/src/evidence.ts +6 -0
  157. package/src/extract.ts +52 -709
  158. package/src/gemini/adapter.ts +9 -5
  159. package/src/gemini/endpoints.ts +12 -2
  160. package/src/gemini/generate.ts +19 -3
  161. package/src/groups.ts +162 -0
  162. package/src/html.ts +1071 -0
  163. package/src/index.ts +2 -1
  164. package/src/library.ts +43 -12
  165. package/src/limiter.ts +6 -1
  166. package/src/model.ts +8 -1
  167. package/src/node/handlers.ts +66 -16
  168. package/src/node/index.ts +2 -0
  169. package/src/node/ingest-child.ts +61 -0
  170. package/src/node/isolated.ts +464 -0
  171. package/src/office.ts +1047 -0
  172. package/src/openai/adapter.ts +14 -1
  173. package/src/pdf-pages.ts +2 -5
  174. package/src/peers.ts +29 -0
  175. package/src/plan.ts +2 -0
  176. package/src/ranged.ts +4 -2
  177. package/src/search.ts +738 -146
  178. package/src/text-index.ts +4 -2
  179. package/src/text.ts +214 -23
  180. package/src/tools.ts +192 -12
  181. package/src/types.ts +3 -3
  182. package/src/word-styles.ts +420 -0
  183. package/src/xlsx.ts +478 -0
  184. package/src/xml-stream.ts +224 -0
package/src/search.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { createContext, Script, type Context } from "node:vm";
2
+ import { GroupCounter, type GroupBy, type GroupResult } from "./groups.js";
2
3
  import { pause } from "./pause.js";
3
4
  import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
4
- import { foldCase, LineIndex, sliceWhole } from "./text.js";
5
+ import { composed, foldCase, LineIndex, sliceWhole } from "./text.js";
5
6
  import type { DocumentMeta, StoredDocument } from "./types.js";
6
7
 
7
8
  const MAX_OCCURRENCES_PER_TERM = 200_000;
@@ -9,12 +10,30 @@ const MAX_EXACT_MATCHES = 1_000_000;
9
10
  const MAX_PHRASE_PASSAGES = 10_000;
10
11
  /** The most time one regex search may spend matching. */
11
12
  export const REGEX_TIME_LIMIT_MS = 3_000;
13
+ /**
14
+ * The most time one exact search with `wholeWord` or `groupBy` may spend. Exact search takes time in
15
+ * proportion to the text, but of a file of 100 MB, a whole-word search for "a" inside long words
16
+ * took 17 seconds, and a count of a million lines by message shape 10: it stops, as a regex search
17
+ * does. A plain exact search has no such limit: it pauses, and its count stays whole.
18
+ */
19
+ const EXACT_TIME_LIMIT_MS = 3_000;
12
20
  /**
13
21
  * A regex scan runs in slices of this length, and other work gets a turn between two slices. A
14
22
  * line that takes two whole slices is a pattern that backtracks without end on it: the search
15
23
  * stops there, long before its time limit.
16
24
  */
17
25
  const REGEX_SLICE_MS = 250;
26
+ /**
27
+ * A regex scan records the lines it found after this many, within its time slice (see `scanRegex`).
28
+ * Each batch is one run of the time limit, which costs about 0.3 ms to set up.
29
+ */
30
+ const REGEX_BATCH = 1 << 16;
31
+ /** An exact scan of a piece lets other work run after this much time, and goes on after. */
32
+ const EXACT_SLICE_MS = 15;
33
+ /** A scan of a document held in memory lets other work run between two pieces after this much time, as a scan of a document read by range does. */
34
+ const YIELD_AFTER_MS = 15;
35
+ /** About this many characters of a document held in memory are scanned as one piece. */
36
+ const PIECE_CHARACTERS = 1 << 20;
18
37
  const SHOWN_LINE_CHARACTERS = 400;
19
38
 
20
39
  const STOPWORDS = new Set([
@@ -24,8 +43,8 @@ const STOPWORDS = new Set([
24
43
  ]);
25
44
 
26
45
  /**
27
- * A piece of a document's text: whole lines, in order. A document read by range is scanned in
28
- * pieces that start at passage starts; a document held in memory is one piece.
46
+ * A piece of a document's text: whole lines, in order. A document is scanned in pieces of whole
47
+ * passages, whether it is read by range or held in memory.
29
48
  */
30
49
  export type TextChunk = {
31
50
  /** The document line of the piece's first line. */
@@ -106,9 +125,14 @@ export class SearchableDocument implements DocumentSource {
106
125
  readonly meta: DocumentMeta;
107
126
  readonly text: string;
108
127
  readonly lines: LineIndex;
109
- private lowerText?: string;
110
128
  private passageStartList?: number[];
111
129
  private pageStarts?: number[];
130
+ /** The first and the last line of each piece a search scans (see `pieces`). */
131
+ private pieceLines?: Array<readonly [number, number]>;
132
+ /** Each piece lowercased with `foldCase`, once a search has needed it. */
133
+ private readonly lowerPieces: Array<string | undefined> = [];
134
+ /** Each piece's text and line table, made once: a search of a document of short lines rebuilt every table. */
135
+ private readonly madePieces: Array<{ text: string; lines: LineIndex } | undefined> = [];
112
136
 
113
137
  constructor(document: StoredDocument) {
114
138
  this.meta = document.meta;
@@ -125,18 +149,13 @@ export class SearchableDocument implements DocumentSource {
125
149
  }
126
150
 
127
151
  /**
128
- * Memory this document takes once it has been searched: the text, its lowercased copy, and the
129
- * line index. A text of ASCII only is held at one byte a character, any other at two.
152
+ * Memory this document takes once it has been searched: the text, its lowercased copy (a piece
153
+ * at a time), and the line index with each piece's copy of it. A text of ASCII only is held at
154
+ * one byte a character, any other at two.
130
155
  */
131
156
  get memoryBytes(): number {
132
157
  const ascii = this.meta.textBytes !== undefined && this.meta.textBytes === this.text.length;
133
- return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 4 + 1_024;
134
- }
135
-
136
- /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
137
- get lower(): string {
138
- this.lowerText ??= foldCase(this.text);
139
- return this.lowerText;
158
+ return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 8 + 1_024;
140
159
  }
141
160
 
142
161
  /** First line of each passage: groups of lines up to about 1,500 characters. */
@@ -163,15 +182,6 @@ export class SearchableDocument implements DocumentSource {
163
182
  return this.passages;
164
183
  }
165
184
 
166
- passageRange(index: number): { from: number; to: number } {
167
- const starts = this.passages;
168
- return { from: starts[index]!, to: (starts[index + 1] ?? this.lines.lineCount + 1) - 1 };
169
- }
170
-
171
- passageOfLine(line: number): number {
172
- return positionOf(this.passages, line) - 1;
173
- }
174
-
175
185
  /**
176
186
  * The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
177
187
  * a text without them, and for lines above the first one. Only markers that count up from 1 are
@@ -197,13 +207,72 @@ export class SearchableDocument implements DocumentSource {
197
207
  return this.text;
198
208
  }
199
209
 
200
- /** The whole text as one piece. */
210
+ /**
211
+ * The whole text as one piece, for a caller that reads every line of it. Its lowercased copy is
212
+ * not kept: searches lowercase the text a piece at a time (see `pieces`).
213
+ */
201
214
  wholeChunk(): TextChunk {
202
- return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
215
+ return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => foldCase(this.text) };
216
+ }
217
+
218
+ /**
219
+ * The text in pieces of whole passages, about 1M characters each (one passage at least), as a
220
+ * document read by range is scanned. A search scans them one at a time, and other work runs
221
+ * between them (see `scan`): a search of 100 MB held as one piece kept the server from all
222
+ * other work for up to 17 seconds. Each piece is lowercased the first time a search needs it.
223
+ */
224
+ *pieces(): Generator<TextChunk> {
225
+ const ranges = this.pieceRanges();
226
+ for (let index = 0; index < ranges.length; index++) {
227
+ const [firstLine, lastLine] = ranges[index]!;
228
+ const { text, lines } = (this.madePieces[index] ??= this.lines.piece(firstLine, lastLine));
229
+ yield { firstLine, startCharacter: this.lines.startOf(firstLine), text, lines, lower: () => (this.lowerPieces[index] ??= foldCase(text)) };
230
+ }
203
231
  }
204
232
 
205
233
  async *chunks(): AsyncGenerator<TextChunk> {
206
- yield this.wholeChunk();
234
+ yield* this.pieces();
235
+ }
236
+
237
+ /**
238
+ * Feeds the pieces in order to `feed` until it returns true or the text ends, and lets other
239
+ * work run between two pieces every 15 ms or so, and whenever `feed` asks for a piece again.
240
+ */
241
+ async scan(feed: ScanFeed, signal?: AbortSignal): Promise<void> {
242
+ let slice = performance.now();
243
+ for (const chunk of this.pieces()) {
244
+ signal?.throwIfAborted();
245
+ let more = feed(chunk);
246
+ // A scan that asks for the same piece again has stopped part-way to let other work run.
247
+ while (more === "again") {
248
+ await pause();
249
+ signal?.throwIfAborted();
250
+ slice = performance.now();
251
+ more = feed(chunk);
252
+ }
253
+ if (more === true) return;
254
+ if (performance.now() - slice > YIELD_AFTER_MS) {
255
+ await pause();
256
+ slice = performance.now();
257
+ }
258
+ }
259
+ }
260
+
261
+ /** The first and the last line of each piece of `pieces`: whole passages, about `PIECE_CHARACTERS` each. */
262
+ private pieceRanges(): Array<readonly [number, number]> {
263
+ if (!this.pieceLines) {
264
+ const starts = this.passages;
265
+ const ranges: Array<readonly [number, number]> = [];
266
+ for (let passage = 0; passage < starts.length;) {
267
+ const start = this.lines.startOf(starts[passage]!);
268
+ let next = passage + 1;
269
+ while (next < starts.length && this.lines.startOf(starts[next]!) - start < PIECE_CHARACTERS) next++;
270
+ ranges.push([starts[passage]!, next < starts.length ? starts[next]! - 1 : this.lines.lineCount]);
271
+ passage = next;
272
+ }
273
+ this.pieceLines = ranges;
274
+ }
275
+ return this.pieceLines;
207
276
  }
208
277
 
209
278
  private pageLines(): number[] {
@@ -225,7 +294,7 @@ export type LineMatch = { line: number; text: string; before?: string[]; after?:
225
294
 
226
295
  export type GrepResult = {
227
296
  totalMatchingLines: number;
228
- /** True when the scan stopped early (too many matches or the regex time limit). */
297
+ /** True when the scan stopped early (too many matches, or the time limit). */
229
298
  stoppedEarly: boolean;
230
299
  /** The first `maxResults` matching lines. */
231
300
  matches: LineMatch[];
@@ -234,6 +303,10 @@ export type GrepResult = {
234
303
  * scan stopped early: the last line it found need not be the last of the document.
235
304
  */
236
305
  last?: LineMatch;
306
+ /** With `order: "last"`: the first matching line, when it is not among `matches` (without the lines around it). */
307
+ first?: LineMatch;
308
+ /** With `groupBy`: the matching lines counted by group. `matches` is then empty. */
309
+ groups?: GroupResult;
237
310
  };
238
311
 
239
312
  export type GrepOptions = {
@@ -241,10 +314,20 @@ export type GrepOptions = {
241
314
  caseSensitive?: boolean;
242
315
  maxResults: number;
243
316
  contextLines: number;
244
- /** Regex mode only. Defaults to 3 seconds of scanning. */
317
+ /** The most time the scan may take, in either mode. Defaults to 3 seconds of scanning. */
245
318
  timeLimitMs?: number;
246
319
  /** Regex mode only: the time spent matching is added to `usedMs`, for a caller that keeps a budget over several searches. */
247
320
  regexClock?: { usedMs: number };
321
+ /** Only lines from this one on are looked at (1-based). */
322
+ fromLine?: number;
323
+ /** Only lines up to this one are looked at. */
324
+ toLine?: number;
325
+ /** "last": `matches` are the last `maxResults` matching lines, and `first` the first one. Defaults to "first". */
326
+ order?: "first" | "last";
327
+ /** Count the matching lines by group, and show none (see `GroupBy`). */
328
+ groupBy?: GroupBy;
329
+ /** Exact mode: only where the text is a whole word, not part of a longer one. Letters of every script count. */
330
+ wholeWord?: boolean;
248
331
  };
249
332
 
250
333
  function clip(line: string, column: number): string {
@@ -283,14 +366,62 @@ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
283
366
  }
284
367
  }
285
368
 
369
+ /** A group that holds a quantifier and is repeated itself: `(a+)+`, `(\d{1,3}\.){3}`. Group 1 is its body. */
370
+ const NESTED_QUANTIFIER = /\(((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*)\)\s*[+*{]/g;
371
+ /** An atom of a pattern, as `regexAtoms` splits it: an escape, a class, or one character. */
372
+ const REGEX_ATOM = /\\[pPu]\{[^}]*\}|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\.|\[(?:[^\]\\]|\\.)*\]|\{\d*,?\d*\}|[\s\S]/gu;
373
+ /** Escapes that stand for many characters, not for one. */
374
+ const CLASS_ESCAPE = /^\\[dDwWsSbBpP]/;
375
+ const QUANTIFIER = /^(?:[+*?]|\{\d*,?\d*\})$/;
376
+
377
+ /**
378
+ * Whether a repeated group cannot backtrack without end: its body ends in a literal character that
379
+ * none of the quantified atoms before it can match, and has no alternation. Each repeat then ends at
380
+ * the next such character, so the match takes time in proportion to the line. `(\d{1,3}\.){3}`,
381
+ * `(\w+\.)+com` and `(\d+-)+\d+` pass; `(a+)+`, `(\w+\s?)+`, `(.+x)+` and `(\d+\d)+` do not.
382
+ */
383
+ function separatedRepeat(body: string): boolean {
384
+ const atoms: string[] = body.match(REGEX_ATOM) ?? [];
385
+ if (atoms.includes("|")) return false;
386
+ const last = atoms.at(-1);
387
+ if (last === undefined) return false;
388
+ // The separator: one character, written plainly or escaped, not a class, a dot or a quantifier.
389
+ let separator: string;
390
+ if (last.startsWith("\\")) {
391
+ if (last.length !== 2 || CLASS_ESCAPE.test(last) || /^\\[0-9ck]$/.test(last)) return false;
392
+ separator = last[1]!;
393
+ } else {
394
+ if (last.length !== 1 || ".?*+{}()[]|^$".includes(last)) return false;
395
+ separator = last;
396
+ }
397
+ for (let index = 0; index < atoms.length - 1; index++) {
398
+ const next = atoms[index + 1]!;
399
+ if (!QUANTIFIER.test(next) || QUANTIFIER.test(atoms[index]!)) continue;
400
+ try {
401
+ if (new RegExp(`^(?:${atoms[index]})$`, "iu").test(separator)) return false;
402
+ } catch {
403
+ return false;
404
+ }
405
+ }
406
+ return true;
407
+ }
408
+
286
409
  /**
287
410
  * A quick refusal for the most common catastrophic shape, a nested quantifier such as (a+)+.
288
- * It does not catch every slow pattern; the time limit in `grep` is what bounds the search.
411
+ * A repeated group whose repeats are separated by a literal character none of its quantified parts
412
+ * matches, as in an IPv4 address or a domain, is linear, and passes (see `separatedRepeat`). It does
413
+ * not catch every slow pattern; the time limit in `grep` is what bounds the search.
289
414
  */
290
- export function unsafeRegexReason(pattern: string): string | null {
291
- if (pattern.length > 300) return "Regex is longer than 300 characters.";
292
- if (/\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/.test(pattern)) {
293
- return "Regex has a nested quantifier like (a+)+, which can hang on large files. Simplify it.";
415
+ export function unsafeRegexReason(given: string): string | null {
416
+ if (given.length > 300) return "Regex is longer than 300 characters.";
417
+ // Checked as it is compiled (`compileRegex`): composed. As typed, `(\p{L}+e` and a combining
418
+ // acute `)+$` ends in a mark that \p{L} does not match, and passed; composed, it ends in "é",
419
+ // and backtracks without end.
420
+ const pattern = composed(given);
421
+ for (const [, body] of pattern.matchAll(NESTED_QUANTIFIER)) {
422
+ // Checked with \\w and \\W as the pattern is compiled, for letters of every script: (\\w+é)+ is
423
+ // not separated, though é is not an ASCII word character.
424
+ if (!separatedRepeat(unicodeWordPattern(body!, false) ?? body!)) return "Regex has a nested quantifier like (a+)+, which can hang on large files. Simplify it.";
294
425
  }
295
426
  try {
296
427
  new RegExp(pattern);
@@ -300,12 +431,77 @@ export function unsafeRegexReason(pattern: string): string | null {
300
431
  return null;
301
432
  }
302
433
 
434
+ /** A letter, a mark or a digit of any script, or "_": as a class, what `\w` means inside a class of a pattern compiled here. */
435
+ const WORD_CLASS = "\\p{L}\\p{M}\\p{N}_";
436
+ /**
437
+ * Marks that belong to a symbol, not to a letter: the variation selectors (U+FE0F makes "⚠" an
438
+ * emoji, and an ideograph's variant is chosen with one from U+E0100) and the enclosing marks (the
439
+ * keycap U+20E3 of "1️⃣"). They are not word characters: "Warning" in "⚠️Warning" is a whole word.
440
+ */
441
+ const SYMBOL_MARKS = "\\uFE00-\\uFE0F\\u{E0100}-\\u{E01EF}\\p{Me}";
442
+ /** A word character, with the `u` flag: a letter, a mark or a digit of any script, or "_", but not a mark of `SYMBOL_MARKS`. What `\w` means outside a class. */
443
+ const WORD_PATTERN = `(?:(?![${SYMBOL_MARKS}])[${WORD_CLASS}])`;
444
+ /** A character that is not one of `WORD_PATTERN`: what `\W` means. */
445
+ const NOT_WORD_PATTERN = `(?:[${SYMBOL_MARKS}]|[^${WORD_CLASS}])`;
446
+
447
+ /**
448
+ * The pattern with `\w`, `\W`, `\b` and `\B` meaning letters of every script, not only ASCII:
449
+ * in JavaScript, `\bחוזה\b` matches nothing and `\w+` stops at "é". Undefined when the pattern
450
+ * cannot be rewritten that way (`\W` inside a class): it is then compiled as it is. Inside a class,
451
+ * `\w` keeps every mark: a class cannot leave some out.
452
+ *
453
+ * `exact` false is for `unsafeRegexReason`, which splits a pattern into atoms: `\w` and `\W` are
454
+ * each one class there, of what they may match and more, and `\b` and `\B` are left as they are.
455
+ */
456
+ export function unicodeWordPattern(pattern: string, exact = true): string | undefined {
457
+ let out = "";
458
+ let inClass = false;
459
+ for (let at = 0; at < pattern.length; at++) {
460
+ const character = pattern[at]!;
461
+ if (character === "\\") {
462
+ const next = pattern[at + 1];
463
+ if (next === undefined) return undefined;
464
+ at++;
465
+ if (inClass) {
466
+ if (next === "w") out += WORD_CLASS;
467
+ else if (next === "W") return undefined;
468
+ else out += `\\${next}`;
469
+ } else if (next === "w") {
470
+ out += exact ? WORD_PATTERN : `[${WORD_CLASS}]`;
471
+ } else if (next === "W") {
472
+ out += exact ? NOT_WORD_PATTERN : "[^\\p{L}\\p{N}_]";
473
+ } else if (next === "b" && exact) {
474
+ out += `(?:(?<=${WORD_PATTERN})(?!${WORD_PATTERN})|(?<!${WORD_PATTERN})(?=${WORD_PATTERN}))`;
475
+ } else if (next === "B" && exact) {
476
+ out += `(?:(?<=${WORD_PATTERN})(?=${WORD_PATTERN})|(?<!${WORD_PATTERN})(?!${WORD_PATTERN}))`;
477
+ } else {
478
+ out += `\\${next}`;
479
+ }
480
+ continue;
481
+ }
482
+ if (character === "[" && !inClass) inClass = true;
483
+ else if (character === "]" && inClass) inClass = false;
484
+ out += character;
485
+ }
486
+ return out;
487
+ }
488
+
303
489
  /**
304
490
  * The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
305
- * `\p{L}` means a letter and a character outside the basic plane is one character; without it for
306
- * a pattern that is only valid the old way (`[\w-.]`, `\-`).
491
+ * `\p{L}` means a letter, a character outside the basic plane is one character, and `\w` and `\b`
492
+ * know the letters of every script (see `unicodeWordPattern`); without it for a pattern that is
493
+ * only valid the old way (`[\w-.]`, `\-`). The pattern is composed (NFC) first, as the text is.
307
494
  */
308
- function compileRegex(pattern: string, flags: string): RegExp {
495
+ function compileRegex(given: string, flags: string): RegExp {
496
+ const pattern = composed(given);
497
+ const unicode = unicodeWordPattern(pattern);
498
+ if (unicode !== undefined) {
499
+ try {
500
+ return new RegExp(unicode, `${flags}u`);
501
+ } catch {
502
+ // Below: as it is.
503
+ }
504
+ }
309
505
  try {
310
506
  return new RegExp(pattern, `${flags}u`);
311
507
  } catch {
@@ -313,6 +509,28 @@ function compileRegex(pattern: string, flags: string): RegExp {
313
509
  }
314
510
  }
315
511
 
512
+ /** A letter, mark, digit or "_" of any script, but not a mark of a symbol: what a whole word is made of (see `WORD_PATTERN`). */
513
+ const WORD_CHARACTER = new RegExp(`^${WORD_PATTERN}`, "u");
514
+ /**
515
+ * A word character but "_", for the pattern a whole-word search finds its candidates with in the
516
+ * lowercased text, where "_" is "_": a candidate next to "_" is checked as written (`scanExact`).
517
+ */
518
+ const WORD_BUT_LOW_LINE = `(?:(?![${SYMBOL_MARKS}])[\\p{L}\\p{M}\\p{N}])`;
519
+
520
+ /** Whether the character that ends just before `at` is a word character. */
521
+ function wordBefore(text: string, at: number): boolean {
522
+ if (at <= 0) return false;
523
+ const low = text.charCodeAt(at - 1);
524
+ const from = low >= 0xdc00 && low <= 0xdfff && at >= 2 ? at - 2 : at - 1;
525
+ return WORD_CHARACTER.test(text.slice(from, at));
526
+ }
527
+
528
+ /** Whether the character that starts at `at` is a word character. */
529
+ function wordAt(text: string, at: number): boolean {
530
+ if (at >= text.length) return false;
531
+ return WORD_CHARACTER.test(String.fromCodePoint(text.codePointAt(at)!));
532
+ }
533
+
316
534
  const newlinesIn = (text: string) => text.split("\n").length - 1;
317
535
 
318
536
  /**
@@ -334,6 +552,13 @@ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, ke
334
552
  return [...recent, ...fresh].slice(-keep);
335
553
  }
336
554
 
555
+ /**
556
+ * An exact scan of one piece, as it goes: the text searched (lowercased, unless the search is
557
+ * case-sensitive), the same text as written, both with the lines carried from the piece before
558
+ * for a needle across lines, and where the next occurrence starts.
559
+ */
560
+ type ExactScan = { chunk: TextChunk; text: string; written: string; lines: LineIndex; firstLine: number; start: number; at: number };
561
+
337
562
  /**
338
563
  * Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
339
564
  * a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
@@ -370,6 +595,24 @@ class LineSearch {
370
595
  private unfinished?: { chunk: TextChunk; next: number };
371
596
  /** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
372
597
  private stuck?: number;
598
+ /** Regex mode: the lines of a piece found in a slice, before they are recorded, by line of the piece; their columns, and their groups with `groupBy`. */
599
+ private batch?: { lines: Int32Array; columns: Int32Array; keys: Array<string | undefined> };
600
+ /** Exact mode: the scan of the piece that stopped at the end of a time slice. */
601
+ private exactLeft?: ExactScan;
602
+ /** The lines looked at: matches outside them are neither counted nor shown. */
603
+ private readonly fromLine: number;
604
+ private readonly toLine: number;
605
+ /** `order: "last"`: the matches are the last ones, and this is the first. */
606
+ private readonly lastOnes: boolean;
607
+ private firstHit?: { line: number; column: number; text: string };
608
+ /** `order: "last"`: whether the lines around the matches kept have been put among the lines to show. */
609
+ private lastOnesShown = false;
610
+ private readonly groups?: GroupCounter;
611
+ /** Exact mode, `wholeWord`: whether the needle starts and ends with a word character, where a word must start and end. */
612
+ private readonly wordStart: boolean = false;
613
+ private readonly wordEnd: boolean = false;
614
+ /** Exact mode, `wholeWord`: the needle where no word character but "_" touches it, a pattern that finds the candidates (see `find`). */
615
+ private readonly wholeWords?: RegExp;
373
616
 
374
617
  constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
375
618
  if (!query) throw new Error("The search query is empty.");
@@ -378,33 +621,63 @@ class LineSearch {
378
621
  if (problem) throw new Error(problem);
379
622
  this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
380
623
  } else {
381
- this.needle = settings.caseSensitive ? query : foldCase(query);
624
+ // Composed, as the text is at ingest (`composed`): "café" typed either way finds both.
625
+ const needle = composed(query);
626
+ this.needle = settings.caseSensitive ? needle : foldCase(needle);
382
627
  this.newlines = newlinesIn(this.needle);
628
+ if (settings.wholeWord) {
629
+ // As written, as the text is checked (`scanExact`): lowercased, "_" is "_", a word character.
630
+ this.wordStart = wordAt(needle, 0);
631
+ this.wordEnd = wordBefore(needle, needle.length);
632
+ const pattern = this.needle.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
633
+ if (this.wordStart || this.wordEnd) this.wholeWords = new RegExp(`${this.wordStart ? `(?<!${WORD_BUT_LOW_LINE})` : ""}${pattern}${this.wordEnd ? `(?!${WORD_BUT_LOW_LINE})` : ""}`, "gu");
634
+ }
635
+ }
636
+ // A plain exact search runs to the end, in slices with pauses: its time follows the text, and its
637
+ // count must be whole. Only the work that grows with each occurrence (a whole-word check, a group
638
+ // key) has a limit, as a regex search does.
639
+ this.timeLeft = settings.timeLimitMs ?? (settings.regex ? REGEX_TIME_LIMIT_MS : settings.wholeWord || settings.groupBy ? EXACT_TIME_LIMIT_MS : Number.POSITIVE_INFINITY);
640
+ this.lastOnes = settings.order === "last";
641
+ if (settings.groupBy) {
642
+ if (settings.groupBy === "capture" && !settings.regex) throw new Error("group_by \"capture\" counts by the first group of a regex: use mode \"regex\" with a group, as in PAY-(\\d+).");
643
+ this.groups = new GroupCounter(settings.groupBy);
383
644
  }
384
- this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
385
- this.context = Math.max(0, Math.min(5, settings.contextLines));
645
+ // Lines around matches are not shown when no match is.
646
+ this.context = this.groups ? 0 : Math.max(0, Math.min(5, settings.contextLines));
386
647
  this.keep = this.context + this.newlines;
648
+ this.fromLine = Math.max(1, Math.trunc(settings.fromLine ?? 1));
649
+ this.toLine = Math.min(lineCount, Math.trunc(settings.toLine ?? lineCount));
650
+ if (this.toLine < this.fromLine) this.done = true;
387
651
  }
388
652
 
389
653
  /** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
390
654
  add(chunk: TextChunk): void {
391
655
  while (!this.addSome(chunk)) {
392
- // The next slice of a regex scan.
656
+ // The next slice of the scan.
393
657
  }
394
658
  }
395
659
 
396
660
  /**
397
- * Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
398
- * slice with lines of this piece still to look at: let other work run, then call this again with
399
- * the same piece. Exact search always finishes the piece.
661
+ * Scans a piece, or goes on scanning it. False means that the scan reached the end of a time
662
+ * slice with text of this piece still to look at: let other work run, then call this again with
663
+ * the same piece.
400
664
  */
401
665
  addSome(chunk: TextChunk): boolean {
402
666
  if (this.done) return true;
403
- if (this.pattern) {
404
- if (!this.scanRegex(chunk)) return false;
405
- } else {
406
- this.scanExact(chunk);
667
+ const chunkEnd = chunk.firstLine + chunk.lines.lineCount - 1;
668
+ // A needle across lines that starts on `toLine` ends in the piece after it, when `toLine` is the
669
+ // last line of a piece: that piece is scanned for it, with the lines carried before it.
670
+ if (chunk.firstLine - this.newlines > this.toLine) {
671
+ this.done = true;
672
+ return true;
673
+ }
674
+ // A piece that ends before the lines searched is not scanned; its last lines are still kept,
675
+ // for lines shown before a match and for a needle across lines.
676
+ if (chunkEnd < this.fromLine) {
677
+ this.recent = remember(this.recent, chunk, this.keep);
678
+ return true;
407
679
  }
680
+ if (!(this.pattern ? this.scanRegex(chunk) : this.scanExact(chunk))) return false;
408
681
  if (this.unfilled > 0) {
409
682
  const last = chunk.firstLine + chunk.lines.lineCount - 1;
410
683
  for (const [line, text] of this.shown) {
@@ -442,6 +715,10 @@ class LineSearch {
442
715
  * around the last match, which is known only once the scan is over. Read them and `fill` them.
443
716
  */
444
717
  missing(): number[] {
718
+ if (this.lastOnes && !this.lastOnesShown) {
719
+ this.lastOnesShown = true;
720
+ for (const hit of this.hits) this.showAround(hit.line);
721
+ }
445
722
  if (this.last && !this.lastShown && !this.stoppedEarly) {
446
723
  this.lastShown = true;
447
724
  this.showAround(this.last.line);
@@ -469,12 +746,37 @@ class LineSearch {
469
746
  }
470
747
  return match;
471
748
  };
749
+ if (this.groups) return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: [], groups: this.groups.result() };
750
+ if (this.lastOnes) {
751
+ const first = this.firstHit && this.firstHit.line < (this.hits[0]?.line ?? 0) ? { first: show(this.firstHit) } : {};
752
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...first };
753
+ }
472
754
  const last = this.last && !this.stoppedEarly ? { last: show(this.last) } : {};
473
755
  return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...last };
474
756
  }
475
757
 
476
- private record(line: number, column: number, text: string): void {
758
+ /**
759
+ * A matching line. Lines outside `fromLine`-`toLine` are left out, and the first past `toLine`
760
+ * ends the search. `key`: with `groupBy`, the line's group, from `GroupCounter.keyOf`.
761
+ */
762
+ private record(line: number, column: number, text: string, key?: string): void {
763
+ if (line < this.fromLine) return;
764
+ if (line > this.toLine) {
765
+ this.done = true;
766
+ return;
767
+ }
477
768
  this.total++;
769
+ if (this.groups) {
770
+ this.groups.addKey(line, key);
771
+ return;
772
+ }
773
+ if (this.lastOnes) {
774
+ // The last ones kept so far; the lines around them are known once the scan is over (`missing`).
775
+ this.firstHit ??= { line, column, text };
776
+ this.hits.push({ line, column, text });
777
+ if (this.hits.length > this.settings.maxResults) this.hits.shift();
778
+ return;
779
+ }
478
780
  if (this.hits.length >= this.settings.maxResults) {
479
781
  this.last = { line, column, text };
480
782
  return;
@@ -493,34 +795,99 @@ class LineSearch {
493
795
  }
494
796
  }
495
797
 
496
- private scanExact(chunk: TextChunk): void {
798
+ /** Ends the search before the end of the text: the counts are lower bounds. */
799
+ private stop(): true {
800
+ this.stoppedEarly = true;
801
+ this.done = true;
802
+ return true;
803
+ }
804
+
805
+ /**
806
+ * One time slice of an exact scan of a piece. True when the piece is finished, or the search is
807
+ * (out of time, or past `toLine`, or at the most matches counted); false when text of the piece
808
+ * is left for the next slice. The time spent counts against the search's time limit: lowercasing
809
+ * the piece, finding the occurrences, and recording the lines, by group too.
810
+ */
811
+ private scanExact(chunk: TextChunk): boolean {
812
+ if (this.timeLeft <= 0) return this.stop();
813
+ const slice = Math.min(this.timeLeft, EXACT_SLICE_MS);
814
+ const started = performance.now();
815
+ // Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
816
+ const scan = this.exactLeft?.chunk === chunk ? this.exactLeft : this.startExact(chunk);
817
+ this.exactLeft = undefined;
497
818
  const { needle } = this;
819
+ const { text, written, lines, firstLine, start } = scan;
820
+ let at = scan.at;
821
+ let steps = 0;
822
+ while (at !== -1) {
823
+ // A look at the clock now and then: a step can record a line, by group too, which takes microseconds.
824
+ if ((++steps & 63) === 0 && performance.now() - started >= slice) break;
825
+ // Words are checked as written: lowercased, "_" is "_", a word character, and "ID_2041"
826
+ // held no whole word "ID" for a search that ignores case, but did for one that does not.
827
+ if ((this.wordStart && wordBefore(written, at)) || (this.wordEnd && wordAt(written, at + needle.length))) {
828
+ // Part of a longer word: the next occurrence may be a whole one, on this line too. Past a
829
+ // whole character: in the middle of an emoji, the pattern would start at the emoji again.
830
+ at = this.find(text, at + (text.codePointAt(at)! > 0xffff ? 2 : 1));
831
+ continue;
832
+ }
833
+ const local = lines.lineAt(at);
834
+ const line = firstLine + local - 1;
835
+ // A line is counted once, where an occurrence starts: the search goes on at the start of the
836
+ // next line. Overlapping occurrences of a needle across lines ("a\na" in "a\na\na") each
837
+ // count on their own line, and further occurrences on a counted line cost nothing.
838
+ const next = lines.startOf(local + 1);
839
+ this.nextAllowed = start + next;
840
+ if (line > this.lastLine) {
841
+ this.lastLine = line;
842
+ const lineText = lines.line(local);
843
+ this.record(line, at - lines.startOf(local), lineText, this.groups?.keyOf(lineText, undefined));
844
+ if (this.done) break;
845
+ if (this.total >= MAX_EXACT_MATCHES) {
846
+ this.stop();
847
+ break;
848
+ }
849
+ }
850
+ at = next >= text.length ? -1 : this.find(text, next);
851
+ }
852
+ this.timeLeft -= performance.now() - started;
853
+ if (this.done || at === -1) return true;
854
+ if (this.timeLeft <= 0) return this.stop();
855
+ this.exactLeft = { ...scan, at };
856
+ return false;
857
+ }
858
+
859
+ /** The start of an exact scan of a piece: its text, with the lines before it that a needle across lines may start in, and the first occurrence. */
860
+ private startExact(chunk: TextChunk): ExactScan {
498
861
  const caseSensitive = this.settings.caseSensitive === true;
499
862
  let text = caseSensitive ? chunk.text : chunk.lower();
863
+ let written = chunk.text;
500
864
  let lines = chunk.lines;
501
865
  let firstLine = chunk.firstLine;
502
866
  let start = chunk.startCharacter;
503
- // A needle across lines can start in the lines before this piece.
504
867
  const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
505
868
  if (before) {
506
- text = (caseSensitive ? before.text : foldCase(before.text)) + text;
507
- lines = new LineIndex(before.text + chunk.text);
869
+ written = before.text + chunk.text;
870
+ text = caseSensitive ? written : foldCase(before.text) + text;
871
+ lines = new LineIndex(written);
508
872
  firstLine = before.firstLine;
509
873
  start = chunk.startCharacter - before.text.length;
510
874
  }
511
- for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
512
- this.nextAllowed = start + at + needle.length;
513
- const local = lines.lineAt(at);
514
- const line = firstLine + local - 1;
515
- if (line === this.lastLine) continue;
516
- this.lastLine = line;
517
- this.record(line, at - lines.startOf(local), lines.line(local));
518
- if (this.total >= MAX_EXACT_MATCHES) {
519
- this.stoppedEarly = true;
520
- this.done = true;
521
- return;
522
- }
523
- }
875
+ // An occurrence that starts before `fromLine` is not counted: the scan starts there.
876
+ const from = Math.max(0, this.nextAllowed - start, this.fromLine > firstLine ? lines.startOf(this.fromLine - firstLine + 1) : 0);
877
+ return { chunk, text, written, lines, firstLine, start, at: this.find(text, from) };
878
+ }
879
+
880
+ /**
881
+ * Where the next occurrence of the needle at or after `from` starts, or -1. With `wholeWord`,
882
+ * only one that no word character but "_" touches where the needle starts or ends with one: the
883
+ * pattern goes past those inside longer words at the speed of the regex engine. Looked at one by
884
+ * one, each cost a step, and a search for "a" in 100 MB of long words took 17 seconds.
885
+ */
886
+ private find(text: string, from: number): number {
887
+ const pattern = this.wholeWords;
888
+ if (!pattern) return text.indexOf(this.needle, from);
889
+ pattern.lastIndex = from;
890
+ return pattern.exec(text)?.index ?? -1;
524
891
  }
525
892
 
526
893
  /**
@@ -529,42 +896,68 @@ class LineSearch {
529
896
  * are left for the next slice.
530
897
  */
531
898
  private scanRegex(chunk: TextChunk): boolean {
532
- const stop = (): true => {
533
- this.stoppedEarly = true;
534
- this.done = true;
535
- return true;
536
- };
537
899
  // Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
538
900
  let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
539
901
  this.unfinished = undefined;
540
- if (this.timeLeft <= 0) return stop();
902
+ if (this.timeLeft <= 0) return this.stop();
541
903
  const pattern = this.pattern!;
542
904
  const { lines, firstLine } = chunk;
905
+ // Lines before those searched are not matched at all.
906
+ if (firstLine + next - 1 < this.fromLine) next = this.fromLine - firstLine + 1;
543
907
  const from = next;
544
908
  const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
545
909
  const started = performance.now();
546
- const finished = withinTimeLimit(() => {
547
- for (; next <= lines.lineCount; next++) {
548
- const line = firstLine + next - 1;
549
- const text = lines.line(next);
550
- const match = pattern.exec(text);
551
- // A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
552
- if (match && line > this.lastLine) {
553
- this.lastLine = line;
554
- this.record(line, match.index, text);
910
+ const last = Math.min(lines.lineCount, this.toLine - firstLine + 1);
911
+ // Only the matching runs inside the time limit, which can stop it anywhere: the lines found are
912
+ // kept in a batch there, with their groups (by shape or time, microseconds a line), and
913
+ // recorded after, so a stop never leaves a count or a list half done. A batch is a number of
914
+ // lines, kept in typed arrays: then they are recorded, at a fraction of a microsecond each, and
915
+ // the matching goes on within the slice. Kept as an object each for the whole slice, half a
916
+ // million lines a slice made a scan twice as slow, as the garbage collector copied them; and
917
+ // grouped after the slice, outside the time limit, they held the server for seconds. A line
918
+ // found twice (the slice ended after it was put in the batch, before it was passed) is
919
+ // recorded once.
920
+ const batch = (this.batch ??= { lines: new Int32Array(REGEX_BATCH), columns: new Int32Array(REGEX_BATCH), keys: [] });
921
+ const groups = this.groups;
922
+ let finished = true;
923
+ while (next <= last && !this.done) {
924
+ const left = slice - (performance.now() - started);
925
+ if (left <= 0) {
926
+ finished = false;
927
+ break;
928
+ }
929
+ let count = 0;
930
+ finished = withinTimeLimit(() => {
931
+ for (; next <= last && count < REGEX_BATCH; next++) {
932
+ const text = lines.line(next);
933
+ const match = pattern.exec(text);
934
+ if (match) {
935
+ batch.lines[count] = next;
936
+ batch.columns[count] = match.index;
937
+ if (groups) batch.keys[count] = groups.keyOf(text, match[1]);
938
+ count++;
939
+ }
555
940
  }
941
+ }, left);
942
+ for (let index = 0; index < count && !this.done; index++) {
943
+ const local = batch.lines[index]!;
944
+ const line = firstLine + local - 1;
945
+ if (line <= this.lastLine) continue;
946
+ this.lastLine = line;
947
+ this.record(line, batch.columns[index]!, lines.line(local), groups ? batch.keys[index] : undefined);
556
948
  }
557
- }, slice);
949
+ if (!finished) break;
950
+ }
558
951
  const spent = performance.now() - started;
559
952
  this.timeLeft -= spent;
560
953
  if (this.settings.regexClock) this.settings.regexClock.usedMs += spent;
561
- if (finished) return true;
562
- if (this.timeLeft <= 0) return stop();
563
- // The slice ended in the middle of line `next`. A whole slice without one line finished can be
564
- // a stall of the machine, once. Twice on the same line, it is the pattern.
954
+ if (finished || this.done) return true;
955
+ if (this.timeLeft <= 0) return this.stop();
956
+ // The slice ended before line `next`, or in the middle of it. A whole slice without one line
957
+ // finished can be a stall of the machine, once. Twice on the same line, it is the pattern.
565
958
  if (next === from && slice >= REGEX_SLICE_MS) {
566
959
  const line = firstLine + next - 1;
567
- if (this.stuck === line) return stop();
960
+ if (this.stuck === line) return this.stop();
568
961
  this.stuck = line;
569
962
  }
570
963
  this.unfinished = { chunk, next };
@@ -586,33 +979,175 @@ async function readSome(source: DocumentSource, lines: number[], use: (line: num
586
979
  /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
587
980
  export function grep(document: SearchableDocument, query: string, options: GrepOptions): GrepResult {
588
981
  const search = new LineSearch(query, options, document.lines.lineCount);
589
- search.add(document.wholeChunk());
982
+ for (const chunk of document.pieces()) {
983
+ if (search.done) break;
984
+ search.add(chunk);
985
+ }
590
986
  for (const line of search.missing()) search.fill(line, document.lines.line(line));
591
987
  return search.result();
592
988
  }
593
989
 
594
- /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
990
+ /**
991
+ * `grep` over any document: one held in memory, or one read from the store a piece at a time.
992
+ * Other work gets a turn between two pieces, and between two time slices of a piece.
993
+ */
595
994
  export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
596
995
  const search = new LineSearch(query, options, source.lineCount);
597
- if (source instanceof SearchableDocument) {
598
- const chunk = source.wholeChunk();
599
- // A regex scan runs a slice at a time, and other work gets a turn between two slices.
600
- while (!search.addSome(chunk)) {
601
- await pause();
602
- options.signal?.throwIfAborted();
603
- }
604
- for (const line of search.missing()) search.fill(line, source.lines.line(line));
605
- return search.result();
606
- }
607
996
  await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
608
997
  const missing = search.missing();
609
998
  if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
610
999
  return search.result();
611
1000
  }
612
1001
 
1002
+ /**
1003
+ * Hebrew points and cantillation marks, and the combining grapheme joiner that pointed texts put
1004
+ * between two points of a letter. Not the maqaf, paseq, sof pasuq or nun hafukha, which are
1005
+ * punctuation and split words.
1006
+ */
1007
+ const HEBREW_POINT = "\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u034f";
1008
+ const HEBREW_LETTER = "\\u05d0-\\u05ea";
1009
+ /**
1010
+ * What splits a query into words: anything but letters, marks, digits and "_" (a mark stays with
1011
+ * its letter: Hindi, Thai, pointed Hebrew), except a geresh or a gershayim between two Hebrew
1012
+ * letters, folded to ' and ", as in the acronyms עו״ד and ש״ח, or in ג׳ורג׳. Split there, ש״ח gave
1013
+ * no term, as each part has one letter, and עו״ד gave only עו, which most lines with עוד have.
1014
+ */
1015
+ const QUERY_SPLIT = new RegExp(`(?:(?!['"])[^\\p{L}\\p{M}\\p{N}_])+|(?<![${HEBREW_LETTER}][${HEBREW_POINT}]*)['"]|['"](?![${HEBREW_LETTER}])`, "u");
1016
+ /** Two gereshes between two Hebrew letters: a gershayim as many keyboards type it (ש''ח). */
1017
+ const DOUBLE_GERESH = new RegExp(`(?<=[${HEBREW_LETTER}][${HEBREW_POINT}]*)''(?=[${HEBREW_LETTER}])`, "gu");
1018
+ /** Scripts written without spaces between words: a word of them is split by `Intl.Segmenter`. */
1019
+ const WITHOUT_SPACES = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
1020
+ /** Han and kana: one character can be a word. */
1021
+ const IDEOGRAPHS = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+$/u;
1022
+ let wordSegmenter: Intl.Segmenter | undefined | null;
1023
+
1024
+ /** The words of a run of a script written without spaces, or the run itself where Node has no word segmenter. */
1025
+ function segmentWords(run: string): string[] {
1026
+ if (wordSegmenter === undefined) {
1027
+ try {
1028
+ wordSegmenter = new Intl.Segmenter("und", { granularity: "word" });
1029
+ } catch {
1030
+ wordSegmenter = null;
1031
+ }
1032
+ }
1033
+ if (!wordSegmenter) return [run];
1034
+ const words: string[] = [];
1035
+ for (const piece of wordSegmenter.segment(run)) if (piece.isWordLike) words.push(piece.segment);
1036
+ return words.length > 0 ? words : [run];
1037
+ }
1038
+
1039
+ const codePoints = (text: string) => {
1040
+ let count = 0;
1041
+ for (const _ of text) count++;
1042
+ return count;
1043
+ };
1044
+
1045
+ /** A word of Hebrew letters, with or without points, and with the geresh or gershayim of an acronym (folded to ' and "). */
1046
+ const HEBREW_WORD = new RegExp(`^[${HEBREW_LETTER}${HEBREW_POINT}'"]+$`, "u");
1047
+ const HEBREW_POINTS = new RegExp(`[${HEBREW_POINT}]`, "gu");
1048
+ const HAS_HEBREW_LETTER = new RegExp(`[${HEBREW_LETTER}]`, "u");
1049
+ /** Letters that Hebrew writes before a word: and, the, in, as, to, from, that (ו ה ב כ ל מ ש). */
1050
+ const HEBREW_PREFIXES = "והבכלמש";
1051
+ /** Final letters, and the form each takes inside a longer word: כסף, כספים. */
1052
+ const HEBREW_FINALS: Record<string, string> = { "ך": "כ", "ם": "מ", "ן": "נ", "ף": "פ", "ץ": "צ" };
1053
+
1054
+ /**
1055
+ * A query word, and the texts that count as hits of it. A Hebrew word loses its points (a model may
1056
+ * write them when the file does not), and is found with or without points in the text (`hebrew`);
1057
+ * one that ends in a final letter also matches with the plain form of that letter, as in a longer
1058
+ * word (כסף finds כספים). Search matches substrings, so other words need nothing more: "timeout"
1059
+ * finds "timeouts".
1060
+ */
1061
+ type QueryTerm = { term: string; variants: string[]; hebrew?: true };
1062
+
1063
+ function hebrewVariants(word: string): string[] {
1064
+ const final = HEBREW_FINALS[word.at(-1)!];
1065
+ return final ? [word, word.slice(0, -1) + final] : [word];
1066
+ }
1067
+
1068
+ /**
1069
+ * The terms of a keyword search: the words of the query, folded as the text is searched, without
1070
+ * stop words and words of one letter (a Han or kana word can be one character). A Hebrew word that
1071
+ * starts with prefix letters (בחוזה, והחוזה) also gives its stem without them (חוזה) as a term of its
1072
+ * own, while at least 3 letters are left: the stem finds the word with any prefix, and passages
1073
+ * with the word as written still rank first, as they hold both terms. The letter before the
1074
+ * geresh or gershayim of an acronym is never a prefix: בש״ח gives ש״ח, and ב״ש stays as it is.
1075
+ */
1076
+ export function searchTerms(query: string): QueryTerm[] {
1077
+ const terms = new Map<string, QueryTerm>();
1078
+ const add = (term: string, variants: string[], hebrew = false) => {
1079
+ if (!terms.has(term)) terms.set(term, { term, variants, ...(hebrew ? { hebrew } : {}) });
1080
+ };
1081
+ for (const word of foldCase(composed(query)).replace(DOUBLE_GERESH, "\"").split(QUERY_SPLIT)) {
1082
+ for (const piece of WITHOUT_SPACES.test(word) ? segmentWords(word) : [word]) {
1083
+ if (!piece || STOPWORDS.has(piece) || codePoints(piece) < (IDEOGRAPHS.test(piece) ? 1 : 2)) continue;
1084
+ if (!HEBREW_WORD.test(piece)) {
1085
+ add(piece, [piece]);
1086
+ continue;
1087
+ }
1088
+ const bare = piece.replace(HEBREW_POINTS, "");
1089
+ if (bare.length < 2 || STOPWORDS.has(bare)) continue;
1090
+ add(bare, hebrewVariants(bare), true);
1091
+ // Prefix letters before a quoted word (ה"ספק, ב"הסכם: a defined term of a contract): the word
1092
+ // itself is a term too, as the text may write it without the quote or the prefix.
1093
+ const quote = bare.search(/["']/);
1094
+ if (quote > 0 && quote <= 3 && [...bare.slice(0, quote)].every((letter) => HEBREW_PREFIXES.includes(letter)) && bare.length - quote - 1 >= 2) {
1095
+ const word = bare.slice(quote + 1);
1096
+ if (!/["']/.test(word)) add(word, hebrewVariants(word), true);
1097
+ }
1098
+ // Prefix letters are stripped while at least 3 letters are left (בש"ח gives ש"ח). An acronym
1099
+ // whose first letter is one (מע"מ) also gives a stem (ע"מ): its own term ranks its passages first.
1100
+ let stem = bare;
1101
+ for (let stripped = 0; stripped < 3 && stem.length > 3 && HEBREW_PREFIXES.includes(stem[0]!) && !"'\"".includes(stem[1]!); stripped++) stem = stem.slice(1);
1102
+ if (stem !== bare) add(stem, hebrewVariants(stem), true);
1103
+ }
1104
+ }
1105
+ return [...terms.values()].slice(0, 12);
1106
+ }
1107
+
1108
+ /**
1109
+ * A text to search for as a pattern that also finds it with points after its Hebrew letters, as a
1110
+ * pointed text writes them (a Bible, a prayer book, poetry, a book for children): the query loses
1111
+ * its points, and the text keeps them. A gershayim between two Hebrew letters is also found as two
1112
+ * gereshes.
1113
+ */
1114
+ function pointedPattern(text: string): string {
1115
+ const characters = [...text];
1116
+ const hebrew = (character: string | undefined) => character !== undefined && character >= "א" && character <= "ת";
1117
+ let out = "";
1118
+ characters.forEach((character, index) => {
1119
+ if (character === "\"" && hebrew(characters[index - 1]) && hebrew(characters[index + 1])) out += "(?:\"|'')";
1120
+ else out += character.replace(/[\\^$.*+?()[\]{}|/-]/g, "\\$&");
1121
+ if (hebrew(character) && index + 1 < characters.length) out += `[${HEBREW_POINT}]*`;
1122
+ });
1123
+ return out;
1124
+ }
1125
+
1126
+ /** Finds a text in a piece: as it is, or, given a pattern, by the pattern (see `pointedPattern`). */
1127
+ class Finder {
1128
+ /** The length of the occurrence found last. */
1129
+ length: number;
1130
+ private readonly pattern?: RegExp;
1131
+
1132
+ constructor(private readonly text: string, pattern?: string) {
1133
+ this.length = text.length;
1134
+ if (pattern !== undefined) this.pattern = new RegExp(pattern, "g");
1135
+ }
1136
+
1137
+ /** Where the first occurrence at or after `from` starts, or -1. */
1138
+ find(haystack: string, from: number): number {
1139
+ if (!this.pattern) return haystack.indexOf(this.text, from);
1140
+ this.pattern.lastIndex = from;
1141
+ const match = this.pattern.exec(haystack);
1142
+ if (!match) return -1;
1143
+ this.length = match[0].length;
1144
+ return match.index;
1145
+ }
1146
+ }
1147
+
1148
+ /** The terms of a keyword search, as text. See `searchTerms`. */
613
1149
  export function queryTerms(query: string): string[] {
614
- const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
615
- return [...new Set(terms)].slice(0, 12);
1150
+ return searchTerms(query).map(({ term }) => term);
616
1151
  }
617
1152
 
618
1153
  export type RankedPassage = { from: number; to: number; score: number };
@@ -623,54 +1158,102 @@ export type RankedPassage = { from: number; to: number; score: number };
623
1158
  * language, and a term also matches longer words ("timeout" → "timeouts").
624
1159
  */
625
1160
  class PassageRank {
626
- private readonly terms: Array<{ term: string; seen: number; frequency: Map<number, number> }>;
1161
+ private readonly terms: Array<{ finders: Finder[]; seen: number; frequency: Map<number, number> }>;
627
1162
  /** Passage lengths in characters, for the passages that have a hit. */
628
1163
  private readonly lengths = new Map<number, number>();
629
- private readonly phrase?: { needle: string; newlines: number; passages: Set<number>; nextAllowed: number };
1164
+ private readonly phrase?: { finder: Finder; newlines: number; passages: Set<number>; nextAllowed: number };
630
1165
  private recent: Array<readonly [number, string]> = [];
631
1166
 
632
- constructor(query: string, private readonly source: Pick<DocumentSource, "passageStarts" | "lineCount" | "characters">) {
633
- this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
634
- // Passages that contain the whole phrase rank above passages with scattered terms.
635
- const phrase = foldCase(query.trim());
636
- if (this.terms.length > 1 && phrase.length <= 200) this.phrase = { needle: phrase, newlines: newlinesIn(phrase), passages: new Set(), nextAllowed: 0 };
1167
+ /**
1168
+ * `range`: the lines to rank passages of; a passage that has none of them is left out, one that
1169
+ * has some keeps all its lines. Only the hits on its lines count, phrases included.
1170
+ */
1171
+ constructor(query: string, private readonly source: Pick<DocumentSource, "passageStarts" | "lineCount" | "characters">, private readonly range?: { from: number; to: number }) {
1172
+ this.terms = searchTerms(query).map(({ variants, hebrew }) => ({
1173
+ finders: variants.map((variant) => new Finder(variant, hebrew ? pointedPattern(variant) : undefined)),
1174
+ seen: 0,
1175
+ frequency: new Map(),
1176
+ }));
1177
+ // Passages that contain the whole phrase rank above passages with scattered terms. A phrase
1178
+ // with Hebrew loses its points, as its terms do, and is found with or without them.
1179
+ const phrase = foldCase(composed(query.trim()));
1180
+ if (this.terms.length > 1 && phrase.length <= 200) {
1181
+ const hebrew = HAS_HEBREW_LETTER.test(phrase);
1182
+ const bare = hebrew ? phrase.replace(HEBREW_POINTS, "") : phrase;
1183
+ this.phrase = { finder: new Finder(bare, hebrew ? pointedPattern(bare) : undefined), newlines: newlinesIn(bare), passages: new Set(), nextAllowed: 0 };
1184
+ }
637
1185
  }
638
1186
 
639
1187
  get empty(): boolean {
640
1188
  return this.terms.length === 0;
641
1189
  }
642
1190
 
643
- add(chunk: TextChunk): void {
644
- if (this.empty) return;
1191
+ /**
1192
+ * Counts the hits of a piece. True when the pieces after it have nothing to count: they are past
1193
+ * the lines ranked, and past the end of a phrase across lines that starts on one of them. Only
1194
+ * the lines ranked are looked at: a search of the last 100 lines of a file full of the terms
1195
+ * went through every occurrence of them in the file.
1196
+ */
1197
+ add(chunk: TextChunk): boolean {
1198
+ if (this.empty) return true;
1199
+ const range = this.range;
1200
+ const { lines, firstLine } = chunk;
1201
+ const chunkEnd = firstLine + lines.lineCount - 1;
1202
+ // The lines of this piece whose hits count.
1203
+ const first = range ? Math.max(1, range.from - firstLine + 1) : 1;
1204
+ const last = range ? Math.min(lines.lineCount, range.to - firstLine + 1) : lines.lineCount;
1205
+ if (first <= last) this.countTerms(chunk, lines.startOf(first), lines.endOf(last));
1206
+ const phrase = this.phrase;
1207
+ const phraseOpen = phrase !== undefined && phrase.passages.size < MAX_PHRASE_PASSAGES;
1208
+ if (phraseOpen && (!range || (chunkEnd >= range.from && firstLine - phrase.newlines <= range.to))) this.findPhrase(chunk);
1209
+ return range !== undefined && chunkEnd >= range.to + (phraseOpen ? phrase.newlines : 0);
1210
+ }
1211
+
1212
+ /** Counts the occurrences of the terms in a piece that start from `from` to before `to`, up to the cap of each. */
1213
+ private countTerms(chunk: TextChunk, from: number, to: number): void {
645
1214
  const haystack = chunk.lower();
646
1215
  for (const entry of this.terms) {
647
- const { term } = entry;
648
- for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
649
- entry.seen++;
650
- const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
651
- entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
652
- if (!this.lengths.has(passage)) this.lengths.set(passage, this.lengthOf(passage, chunk));
1216
+ for (const finder of entry.finders) {
1217
+ for (let at = finder.find(haystack, from); at !== -1 && at < to && entry.seen < MAX_OCCURRENCES_PER_TERM; at = finder.find(haystack, at + finder.length)) {
1218
+ entry.seen++;
1219
+ const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
1220
+ entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
1221
+ if (!this.lengths.has(passage)) this.lengths.set(passage, this.lengthOf(passage, chunk));
1222
+ }
653
1223
  }
654
1224
  }
655
- const phrase = this.phrase;
656
- if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
657
- let text = haystack;
658
- let lines = chunk.lines;
659
- let firstLine = chunk.firstLine;
660
- let start = chunk.startCharacter;
661
- const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
662
- if (before) {
663
- text = foldCase(before.text) + haystack;
664
- lines = new LineIndex(before.text + chunk.text);
665
- firstLine = before.firstLine;
666
- start = chunk.startCharacter - before.text.length;
667
- }
668
- for (let at = text.indexOf(phrase.needle, Math.max(0, phrase.nextAllowed - start)); at !== -1 && phrase.passages.size < MAX_PHRASE_PASSAGES; at = text.indexOf(phrase.needle, at + phrase.needle.length)) {
669
- phrase.nextAllowed = start + at + phrase.needle.length;
1225
+ }
1226
+
1227
+ /**
1228
+ * Finds the passages of a piece where the whole phrase starts, on a line ranked. A phrase across
1229
+ * lines may start in the lines carried from the piece before. Hits before the range no longer
1230
+ * fill the cap on passages, so that one in it still gets its boost.
1231
+ */
1232
+ private findPhrase(chunk: TextChunk): void {
1233
+ const phrase = this.phrase!;
1234
+ const range = this.range;
1235
+ let text = chunk.lower();
1236
+ let lines = chunk.lines;
1237
+ let firstLine = chunk.firstLine;
1238
+ let start = chunk.startCharacter;
1239
+ const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
1240
+ if (before) {
1241
+ text = foldCase(before.text) + text;
1242
+ lines = new LineIndex(before.text + chunk.text);
1243
+ firstLine = before.firstLine;
1244
+ start = chunk.startCharacter - before.text.length;
1245
+ }
1246
+ const lastLine = range ? Math.min(lines.lineCount, range.to - firstLine + 1) : lines.lineCount;
1247
+ if (lastLine >= 1) {
1248
+ const from = range && range.from > firstLine ? lines.startOf(range.from - firstLine + 1) : 0;
1249
+ const to = lines.endOf(lastLine);
1250
+ const { finder } = phrase;
1251
+ for (let at = finder.find(text, Math.max(from, phrase.nextAllowed - start)); at !== -1 && at <= to && phrase.passages.size < MAX_PHRASE_PASSAGES; at = finder.find(text, at + finder.length)) {
1252
+ phrase.nextAllowed = start + at + finder.length;
670
1253
  phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
671
1254
  }
672
- this.recent = remember(this.recent, chunk, phrase.newlines);
673
1255
  }
1256
+ this.recent = remember(this.recent, chunk, phrase.newlines);
674
1257
  }
675
1258
 
676
1259
  result(topK: number): RankedPassage[] {
@@ -678,9 +1261,12 @@ class PassageRank {
678
1261
  const passageCount = this.source.passageStarts.length;
679
1262
  const averageLength = Math.max(1, this.source.characters / passageCount);
680
1263
  const scores = new Map<number, number>();
681
- for (const { frequency } of this.terms) {
1264
+ for (const { frequency, seen } of this.terms) {
682
1265
  const df = frequency.size;
683
- if (df === 0) continue;
1266
+ // A term found this often is in a large share of the passages, and tells little about any of
1267
+ // them; and it was counted only up to the cap, in the passages before it. Scored, it pushed
1268
+ // passages from the start of the file above better ones.
1269
+ if (df === 0 || seen >= MAX_OCCURRENCES_PER_TERM) continue;
684
1270
  const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
685
1271
  for (const [passage, tf] of frequency) {
686
1272
  const length = this.lengths.get(passage)!;
@@ -689,23 +1275,29 @@ class PassageRank {
689
1275
  }
690
1276
  }
691
1277
  if (this.phrase) for (const passage of this.phrase.passages) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
1278
+ const range = this.range;
692
1279
  return [...scores.entries()]
1280
+ .filter(([passage]) => {
1281
+ if (!range) return true;
1282
+ const { from, to } = this.rangeOf(passage);
1283
+ return to >= range.from && from <= range.to;
1284
+ })
693
1285
  .sort((left, right) => right[1] - left[1])
694
1286
  .slice(0, topK)
695
- .map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
1287
+ .map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
696
1288
  }
697
1289
 
698
1290
  private passageOf(line: number): number {
699
1291
  return positionOf(this.source.passageStarts, line) - 1;
700
1292
  }
701
1293
 
702
- private range(passage: number): { from: number; to: number } {
1294
+ private rangeOf(passage: number): { from: number; to: number } {
703
1295
  const starts = this.source.passageStarts;
704
1296
  return { from: starts[passage]!, to: (passage + 1 < starts.length ? starts[passage + 1]! : this.source.lineCount + 1) - 1 };
705
1297
  }
706
1298
 
707
1299
  private lengthOf(passage: number, chunk: TextChunk): number {
708
- const { from, to } = this.range(passage);
1300
+ const { from, to } = this.rangeOf(passage);
709
1301
  const first = from - chunk.firstLine + 1;
710
1302
  const last = to - chunk.firstLine + 1;
711
1303
  if (first < 1 || last > chunk.lines.lineCount) throw new Error("A piece of the text does not hold whole passages.");
@@ -713,20 +1305,20 @@ class PassageRank {
713
1305
  }
714
1306
  }
715
1307
 
716
- /** BM25 passage ranking over a document held in memory. */
717
- export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
718
- const rank = new PassageRank(query, document);
719
- rank.add(document.wholeChunk());
1308
+ /** BM25 passage ranking over a document held in memory. `range`: only passages with lines in it. */
1309
+ export function rankPassages(document: SearchableDocument, query: string, topK: number, range?: { from: number; to: number }): RankedPassage[] {
1310
+ const rank = new PassageRank(query, document, range);
1311
+ for (const chunk of document.pieces()) if (rank.add(chunk)) break;
720
1312
  return rank.result(topK);
721
1313
  }
722
1314
 
723
- /** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
724
- export async function rankSource(source: DocumentSource, query: string, topK: number, signal?: AbortSignal): Promise<RankedPassage[]> {
725
- if (source instanceof SearchableDocument) return rankPassages(source, query, topK);
726
- const rank = new PassageRank(query, source);
1315
+ /**
1316
+ * `rankPassages` over any document: one held in memory, or one read from the store a piece at a
1317
+ * time. Other work gets a turn between two pieces, and nothing past the lines ranked is read.
1318
+ */
1319
+ export async function rankSource(source: DocumentSource, query: string, topK: number, signal?: AbortSignal, range?: { from: number; to: number }): Promise<RankedPassage[]> {
1320
+ const rank = new PassageRank(query, source, range);
727
1321
  if (rank.empty) return [];
728
- await scanSource(source, (chunk) => {
729
- rank.add(chunk);
730
- }, signal);
1322
+ await scanSource(source, (chunk) => rank.add(chunk), signal);
731
1323
  return rank.result(topK);
732
1324
  }