llm-large-files 0.5.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/search.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { createContext, Script, type Context } from "node:vm";
2
+ import { GroupCounter, type GroupBy, type GroupResult } from "./groups.js";
3
+ import { pause } from "./pause.js";
2
4
  import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
3
- import { foldCase, LineIndex } from "./text.js";
5
+ import { composed, foldCase, LineIndex, sliceWhole } from "./text.js";
4
6
  import type { DocumentMeta, StoredDocument } from "./types.js";
5
7
 
6
8
  const MAX_OCCURRENCES_PER_TERM = 200_000;
@@ -8,12 +10,30 @@ const MAX_EXACT_MATCHES = 1_000_000;
8
10
  const MAX_PHRASE_PASSAGES = 10_000;
9
11
  /** The most time one regex search may spend matching. */
10
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;
11
20
  /**
12
21
  * A regex scan runs in slices of this length, and other work gets a turn between two slices. A
13
22
  * line that takes two whole slices is a pattern that backtracks without end on it: the search
14
23
  * stops there, long before its time limit.
15
24
  */
16
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;
17
37
  const SHOWN_LINE_CHARACTERS = 400;
18
38
 
19
39
  const STOPWORDS = new Set([
@@ -23,8 +43,8 @@ const STOPWORDS = new Set([
23
43
  ]);
24
44
 
25
45
  /**
26
- * A piece of a document's text: whole lines, in order. A document read by range is scanned in
27
- * 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.
28
48
  */
29
49
  export type TextChunk = {
30
50
  /** The document line of the piece's first line. */
@@ -70,8 +90,7 @@ export interface DocumentSource {
70
90
  */
71
91
  export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
72
92
 
73
- /** Lets other work on the server run (an answer streaming to another user) before going on. */
74
- export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
93
+ export { pause };
75
94
 
76
95
  /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
77
96
  export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
@@ -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,9 +294,19 @@ 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;
299
+ /** The first `maxResults` matching lines. */
230
300
  matches: LineMatch[];
301
+ /**
302
+ * The last matching line of the document, when it is not among `matches`. Undefined when the
303
+ * scan stopped early: the last line it found need not be the last of the document.
304
+ */
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;
231
310
  };
232
311
 
233
312
  export type GrepOptions = {
@@ -235,16 +314,30 @@ export type GrepOptions = {
235
314
  caseSensitive?: boolean;
236
315
  maxResults: number;
237
316
  contextLines: number;
238
- /** 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. */
239
318
  timeLimitMs?: number;
240
319
  /** Regex mode only: the time spent matching is added to `usedMs`, for a caller that keeps a budget over several searches. */
241
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;
242
331
  };
243
332
 
244
333
  function clip(line: string, column: number): string {
245
334
  if (line.length <= SHOWN_LINE_CHARACTERS) return line;
246
- const start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
247
- return `${start > 0 ? "…" : ""}${line.slice(start, start + SHOWN_LINE_CHARACTERS)}${start + SHOWN_LINE_CHARACTERS < line.length ? "…" : ""}`;
335
+ let start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
336
+ // Never inside a character outside the basic plane (an emoji): half of one is refused by Claude's API.
337
+ const code = line.charCodeAt(start);
338
+ if (start > 0 && code >= 0xdc00 && code <= 0xdfff) start++;
339
+ const end = start + SHOWN_LINE_CHARACTERS;
340
+ return `${start > 0 ? "…" : ""}${sliceWhole(line, end).slice(start)}${end < line.length ? "…" : ""}`;
248
341
  }
249
342
 
250
343
  const RUN_SCAN = new Script("scan()");
@@ -273,14 +366,62 @@ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
273
366
  }
274
367
  }
275
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
+
276
409
  /**
277
410
  * A quick refusal for the most common catastrophic shape, a nested quantifier such as (a+)+.
278
- * 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.
279
414
  */
280
- export function unsafeRegexReason(pattern: string): string | null {
281
- if (pattern.length > 300) return "Regex is longer than 300 characters.";
282
- if (/\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/.test(pattern)) {
283
- 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.";
284
425
  }
285
426
  try {
286
427
  new RegExp(pattern);
@@ -290,12 +431,77 @@ export function unsafeRegexReason(pattern: string): string | null {
290
431
  return null;
291
432
  }
292
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
+
293
489
  /**
294
490
  * The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
295
- * `\p{L}` means a letter and a character outside the basic plane is one character; without it for
296
- * 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.
297
494
  */
298
- 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
+ }
299
505
  try {
300
506
  return new RegExp(pattern, `${flags}u`);
301
507
  } catch {
@@ -303,6 +509,28 @@ function compileRegex(pattern: string, flags: string): RegExp {
303
509
  }
304
510
  }
305
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
+
306
534
  const newlinesIn = (text: string) => text.split("\n").length - 1;
307
535
 
308
536
  /**
@@ -324,6 +552,13 @@ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, ke
324
552
  return [...recent, ...fresh].slice(-keep);
325
553
  }
326
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
+
327
562
  /**
328
563
  * Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
329
564
  * a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
@@ -331,6 +566,14 @@ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, ke
331
566
  */
332
567
  class LineSearch {
333
568
  private readonly hits: Array<{ line: number; column: number; text: string }> = [];
569
+ /** The latest matching line past the first `maxResults`: the last one of the document, once the scan is over. */
570
+ private last?: { line: number; column: number; text: string };
571
+ /** The lines around `last`, by number, kept from the pieces as they are read: they need not be read again. */
572
+ private readonly aroundLast = new Map<number, string>();
573
+ /** The line of the match whose lines `aroundLast` holds. */
574
+ private aroundLine = 0;
575
+ /** True once the lines around `last` are among the lines to show. */
576
+ private lastShown = false;
334
577
  private total = 0;
335
578
  stoppedEarly = false;
336
579
  /** True once nothing more is to be found or counted: the rest of the text need not be read. */
@@ -352,6 +595,24 @@ class LineSearch {
352
595
  private unfinished?: { chunk: TextChunk; next: number };
353
596
  /** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
354
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;
355
616
 
356
617
  constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
357
618
  if (!query) throw new Error("The search query is empty.");
@@ -360,33 +621,63 @@ class LineSearch {
360
621
  if (problem) throw new Error(problem);
361
622
  this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
362
623
  } else {
363
- 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);
364
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);
365
644
  }
366
- this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
367
- 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));
368
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;
369
651
  }
370
652
 
371
653
  /** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
372
654
  add(chunk: TextChunk): void {
373
655
  while (!this.addSome(chunk)) {
374
- // The next slice of a regex scan.
656
+ // The next slice of the scan.
375
657
  }
376
658
  }
377
659
 
378
660
  /**
379
- * Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
380
- * slice with lines of this piece still to look at: let other work run, then call this again with
381
- * 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.
382
664
  */
383
665
  addSome(chunk: TextChunk): boolean {
384
666
  if (this.done) return true;
385
- if (this.pattern) {
386
- if (!this.scanRegex(chunk)) return false;
387
- } else {
388
- 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;
389
679
  }
680
+ if (!(this.pattern ? this.scanRegex(chunk) : this.scanExact(chunk))) return false;
390
681
  if (this.unfilled > 0) {
391
682
  const last = chunk.firstLine + chunk.lines.lineCount - 1;
392
683
  for (const [line, text] of this.shown) {
@@ -397,12 +688,42 @@ class LineSearch {
397
688
  if (found !== undefined) this.fill(line, found);
398
689
  }
399
690
  }
691
+ if (this.last && this.context > 0) this.keepAroundLast(chunk);
400
692
  this.recent = remember(this.recent, chunk, this.keep);
401
693
  return true;
402
694
  }
403
695
 
404
- /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
696
+ /** Keeps the lines around `last` that are in this piece or in the lines read just before it. */
697
+ private keepAroundLast(chunk: TextChunk): void {
698
+ const { line } = this.last!;
699
+ if (this.aroundLine !== line) {
700
+ this.aroundLast.clear();
701
+ this.aroundLine = line;
702
+ }
703
+ const end = chunk.firstLine + chunk.lines.lineCount - 1;
704
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
705
+ if (other === line || this.aroundLast.has(other)) continue;
706
+ const found = other >= chunk.firstLine && other <= end
707
+ ? chunk.lines.line(other - chunk.firstLine + 1)
708
+ : this.recent.find(([number]) => number === other)?.[1];
709
+ if (found !== undefined) this.aroundLast.set(other, found);
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Lines to show that were not in the pieces read: those of a scan that stopped early, and those
715
+ * around the last match, which is known only once the scan is over. Read them and `fill` them.
716
+ */
405
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
+ }
722
+ if (this.last && !this.lastShown && !this.stoppedEarly) {
723
+ this.lastShown = true;
724
+ this.showAround(this.last.line);
725
+ if (this.aroundLine === this.last.line) for (const [line, text] of this.aroundLast) this.fill(line, text);
726
+ }
406
727
  if (this.unfilled === 0) return [];
407
728
  return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
408
729
  }
@@ -415,7 +736,7 @@ class LineSearch {
415
736
 
416
737
  result(): GrepResult {
417
738
  const lineText = (line: number) => this.shown.get(line) ?? "";
418
- const matches = this.hits.map(({ line, column, text }): LineMatch => {
739
+ const show = ({ line, column, text }: { line: number; column: number; text: string }): LineMatch => {
419
740
  const match: LineMatch = { line, text: clip(text, column) };
420
741
  if (this.context > 0) {
421
742
  match.before = [];
@@ -424,14 +745,48 @@ class LineSearch {
424
745
  for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++) match.after.push(`${other}| ${clip(lineText(other), 0)}`);
425
746
  }
426
747
  return match;
427
- });
428
- return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
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
+ }
754
+ const last = this.last && !this.stoppedEarly ? { last: show(this.last) } : {};
755
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...last };
429
756
  }
430
757
 
431
- 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
+ }
432
768
  this.total++;
433
- if (this.hits.length >= this.settings.maxResults) return;
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
+ }
780
+ if (this.hits.length >= this.settings.maxResults) {
781
+ this.last = { line, column, text };
782
+ return;
783
+ }
434
784
  this.hits.push({ line, column, text });
785
+ this.showAround(line);
786
+ }
787
+
788
+ /** Puts the lines around a match among the lines to show. */
789
+ private showAround(line: number): void {
435
790
  for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
436
791
  if (other !== line && !this.shown.has(other)) {
437
792
  this.shown.set(other, undefined);
@@ -440,34 +795,99 @@ class LineSearch {
440
795
  }
441
796
  }
442
797
 
443
- 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;
444
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 {
445
861
  const caseSensitive = this.settings.caseSensitive === true;
446
862
  let text = caseSensitive ? chunk.text : chunk.lower();
863
+ let written = chunk.text;
447
864
  let lines = chunk.lines;
448
865
  let firstLine = chunk.firstLine;
449
866
  let start = chunk.startCharacter;
450
- // A needle across lines can start in the lines before this piece.
451
867
  const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
452
868
  if (before) {
453
- text = (caseSensitive ? before.text : foldCase(before.text)) + text;
454
- 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);
455
872
  firstLine = before.firstLine;
456
873
  start = chunk.startCharacter - before.text.length;
457
874
  }
458
- for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
459
- this.nextAllowed = start + at + needle.length;
460
- const local = lines.lineAt(at);
461
- const line = firstLine + local - 1;
462
- if (line === this.lastLine) continue;
463
- this.lastLine = line;
464
- this.record(line, at - lines.startOf(local), lines.line(local));
465
- if (this.total >= MAX_EXACT_MATCHES) {
466
- this.stoppedEarly = true;
467
- this.done = true;
468
- return;
469
- }
470
- }
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;
471
891
  }
472
892
 
473
893
  /**
@@ -476,42 +896,68 @@ class LineSearch {
476
896
  * are left for the next slice.
477
897
  */
478
898
  private scanRegex(chunk: TextChunk): boolean {
479
- const stop = (): true => {
480
- this.stoppedEarly = true;
481
- this.done = true;
482
- return true;
483
- };
484
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.
485
900
  let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
486
901
  this.unfinished = undefined;
487
- if (this.timeLeft <= 0) return stop();
902
+ if (this.timeLeft <= 0) return this.stop();
488
903
  const pattern = this.pattern!;
489
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;
490
907
  const from = next;
491
908
  const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
492
909
  const started = performance.now();
493
- const finished = withinTimeLimit(() => {
494
- for (; next <= lines.lineCount; next++) {
495
- const line = firstLine + next - 1;
496
- const text = lines.line(next);
497
- const match = pattern.exec(text);
498
- // A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
499
- if (match && line > this.lastLine) {
500
- this.lastLine = line;
501
- 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
+ }
502
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);
503
948
  }
504
- }, slice);
949
+ if (!finished) break;
950
+ }
505
951
  const spent = performance.now() - started;
506
952
  this.timeLeft -= spent;
507
953
  if (this.settings.regexClock) this.settings.regexClock.usedMs += spent;
508
- if (finished) return true;
509
- if (this.timeLeft <= 0) return stop();
510
- // The slice ended in the middle of line `next`. A whole slice without one line finished can be
511
- // 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.
512
958
  if (next === from && slice >= REGEX_SLICE_MS) {
513
959
  const line = firstLine + next - 1;
514
- if (this.stuck === line) return stop();
960
+ if (this.stuck === line) return this.stop();
515
961
  this.stuck = line;
516
962
  }
517
963
  this.unfinished = { chunk, next };
@@ -533,33 +979,175 @@ async function readSome(source: DocumentSource, lines: number[], use: (line: num
533
979
  /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
534
980
  export function grep(document: SearchableDocument, query: string, options: GrepOptions): GrepResult {
535
981
  const search = new LineSearch(query, options, document.lines.lineCount);
536
- search.add(document.wholeChunk());
982
+ for (const chunk of document.pieces()) {
983
+ if (search.done) break;
984
+ search.add(chunk);
985
+ }
537
986
  for (const line of search.missing()) search.fill(line, document.lines.line(line));
538
987
  return search.result();
539
988
  }
540
989
 
541
- /** `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
+ */
542
994
  export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
543
995
  const search = new LineSearch(query, options, source.lineCount);
544
- if (source instanceof SearchableDocument) {
545
- const chunk = source.wholeChunk();
546
- // A regex scan runs a slice at a time, and other work gets a turn between two slices.
547
- while (!search.addSome(chunk)) {
548
- await pause();
549
- options.signal?.throwIfAborted();
550
- }
551
- for (const line of search.missing()) search.fill(line, source.lines.line(line));
552
- return search.result();
553
- }
554
996
  await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
555
997
  const missing = search.missing();
556
998
  if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
557
999
  return search.result();
558
1000
  }
559
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`. */
560
1149
  export function queryTerms(query: string): string[] {
561
- const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
562
- return [...new Set(terms)].slice(0, 12);
1150
+ return searchTerms(query).map(({ term }) => term);
563
1151
  }
564
1152
 
565
1153
  export type RankedPassage = { from: number; to: number; score: number };
@@ -570,54 +1158,102 @@ export type RankedPassage = { from: number; to: number; score: number };
570
1158
  * language, and a term also matches longer words ("timeout" → "timeouts").
571
1159
  */
572
1160
  class PassageRank {
573
- 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> }>;
574
1162
  /** Passage lengths in characters, for the passages that have a hit. */
575
1163
  private readonly lengths = new Map<number, number>();
576
- 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 };
577
1165
  private recent: Array<readonly [number, string]> = [];
578
1166
 
579
- constructor(query: string, private readonly source: Pick<DocumentSource, "passageStarts" | "lineCount" | "characters">) {
580
- this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
581
- // Passages that contain the whole phrase rank above passages with scattered terms.
582
- const phrase = foldCase(query.trim());
583
- 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
+ }
584
1185
  }
585
1186
 
586
1187
  get empty(): boolean {
587
1188
  return this.terms.length === 0;
588
1189
  }
589
1190
 
590
- add(chunk: TextChunk): void {
591
- 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 {
592
1214
  const haystack = chunk.lower();
593
1215
  for (const entry of this.terms) {
594
- const { term } = entry;
595
- for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
596
- entry.seen++;
597
- const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
598
- entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
599
- 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
+ }
600
1223
  }
601
1224
  }
602
- const phrase = this.phrase;
603
- if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
604
- let text = haystack;
605
- let lines = chunk.lines;
606
- let firstLine = chunk.firstLine;
607
- let start = chunk.startCharacter;
608
- const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
609
- if (before) {
610
- text = foldCase(before.text) + haystack;
611
- lines = new LineIndex(before.text + chunk.text);
612
- firstLine = before.firstLine;
613
- start = chunk.startCharacter - before.text.length;
614
- }
615
- 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)) {
616
- 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;
617
1253
  phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
618
1254
  }
619
- this.recent = remember(this.recent, chunk, phrase.newlines);
620
1255
  }
1256
+ this.recent = remember(this.recent, chunk, phrase.newlines);
621
1257
  }
622
1258
 
623
1259
  result(topK: number): RankedPassage[] {
@@ -625,9 +1261,12 @@ class PassageRank {
625
1261
  const passageCount = this.source.passageStarts.length;
626
1262
  const averageLength = Math.max(1, this.source.characters / passageCount);
627
1263
  const scores = new Map<number, number>();
628
- for (const { frequency } of this.terms) {
1264
+ for (const { frequency, seen } of this.terms) {
629
1265
  const df = frequency.size;
630
- 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;
631
1270
  const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
632
1271
  for (const [passage, tf] of frequency) {
633
1272
  const length = this.lengths.get(passage)!;
@@ -636,23 +1275,29 @@ class PassageRank {
636
1275
  }
637
1276
  }
638
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;
639
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
+ })
640
1285
  .sort((left, right) => right[1] - left[1])
641
1286
  .slice(0, topK)
642
- .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 }));
643
1288
  }
644
1289
 
645
1290
  private passageOf(line: number): number {
646
1291
  return positionOf(this.source.passageStarts, line) - 1;
647
1292
  }
648
1293
 
649
- private range(passage: number): { from: number; to: number } {
1294
+ private rangeOf(passage: number): { from: number; to: number } {
650
1295
  const starts = this.source.passageStarts;
651
1296
  return { from: starts[passage]!, to: (passage + 1 < starts.length ? starts[passage + 1]! : this.source.lineCount + 1) - 1 };
652
1297
  }
653
1298
 
654
1299
  private lengthOf(passage: number, chunk: TextChunk): number {
655
- const { from, to } = this.range(passage);
1300
+ const { from, to } = this.rangeOf(passage);
656
1301
  const first = from - chunk.firstLine + 1;
657
1302
  const last = to - chunk.firstLine + 1;
658
1303
  if (first < 1 || last > chunk.lines.lineCount) throw new Error("A piece of the text does not hold whole passages.");
@@ -660,20 +1305,20 @@ class PassageRank {
660
1305
  }
661
1306
  }
662
1307
 
663
- /** BM25 passage ranking over a document held in memory. */
664
- export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
665
- const rank = new PassageRank(query, document);
666
- 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;
667
1312
  return rank.result(topK);
668
1313
  }
669
1314
 
670
- /** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
671
- export async function rankSource(source: DocumentSource, query: string, topK: number, signal?: AbortSignal): Promise<RankedPassage[]> {
672
- if (source instanceof SearchableDocument) return rankPassages(source, query, topK);
673
- 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);
674
1321
  if (rank.empty) return [];
675
- await scanSource(source, (chunk) => {
676
- rank.add(chunk);
677
- }, signal);
1322
+ await scanSource(source, (chunk) => rank.add(chunk), signal);
678
1323
  return rank.result(topK);
679
1324
  }