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.
- package/CHANGELOG.md +319 -1
- package/README.md +10 -8
- package/dist/analyze.d.ts +3 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +109 -14
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +4 -1
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +3 -3
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +72 -17
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +65 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +6 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +5 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +6 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +7 -20
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +49 -751
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +9 -5
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +20 -3
- package/dist/gemini/generate.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +48 -12
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +8 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +69 -15
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +15 -1
- package/dist/openai/adapter.js.map +1 -1
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +2 -6
- package/dist/pdf-pages.js.map +1 -1
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +1 -1
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +99 -22
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +744 -140
- package/dist/search.js.map +1 -1
- package/dist/text-index.d.ts +3 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +3 -1
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +27 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +225 -23
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +200 -12
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/docs/README.md +8 -8
- package/docs/getting-started.md +1 -1
- package/docs/guides/costs-and-limits.md +7 -5
- package/docs/guides/deployment.md +95 -29
- package/docs/guides/errors-and-reliability.md +23 -10
- package/docs/guides/pdfs.md +127 -74
- package/docs/guides/storage.md +1 -1
- package/docs/guides/testing.md +5 -1
- package/docs/guides/web-app.md +10 -9
- package/docs/how-it-works.md +73 -50
- package/docs/reference/ask.md +26 -8
- package/docs/reference/errors-and-retries.md +5 -3
- package/docs/reference/events.md +14 -6
- package/docs/reference/gemini.md +6 -2
- package/docs/reference/library.md +205 -74
- package/docs/reference/node.md +200 -22
- package/docs/reference/openai.md +1 -1
- package/docs/reference/tools.md +170 -22
- package/docs/security.md +114 -69
- package/docs/troubleshooting.md +40 -20
- package/package.json +6 -2
- package/src/analyze.ts +117 -13
- package/src/anthropic/adapter.ts +4 -1
- package/src/ask.ts +73 -17
- package/src/decode.ts +89 -0
- package/src/errors.ts +108 -0
- package/src/events.ts +10 -1
- package/src/evidence.ts +6 -0
- package/src/extract.ts +52 -709
- package/src/gemini/adapter.ts +9 -5
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/generate.ts +19 -3
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/index.ts +2 -1
- package/src/library.ts +43 -12
- package/src/limiter.ts +6 -1
- package/src/model.ts +8 -1
- package/src/node/handlers.ts +66 -16
- package/src/node/index.ts +2 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +14 -1
- package/src/pdf-pages.ts +2 -5
- package/src/peers.ts +29 -0
- package/src/plan.ts +2 -0
- package/src/ranged.ts +4 -2
- package/src/search.ts +738 -146
- package/src/text-index.ts +4 -2
- package/src/text.ts +214 -23
- package/src/tools.ts +192 -12
- package/src/types.ts +3 -3
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- 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
|
|
28
|
-
*
|
|
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
|
|
129
|
-
* line index. A text of ASCII only is held at
|
|
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 *
|
|
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
|
-
/**
|
|
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.
|
|
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.
|
|
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
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
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(
|
|
291
|
-
if (
|
|
292
|
-
|
|
293
|
-
|
|
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
|
|
306
|
-
*
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
398
|
-
* slice with
|
|
399
|
-
* the same 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
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
507
|
-
|
|
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
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
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
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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<{
|
|
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?: {
|
|
1164
|
+
private readonly phrase?: { finder: Finder; newlines: number; passages: Set<number>; nextAllowed: number };
|
|
630
1165
|
private recent: Array<readonly [number, string]> = [];
|
|
631
1166
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
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
|
-
|
|
644
|
-
|
|
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
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
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
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
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.
|
|
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
|
-
|
|
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
|
-
/**
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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
|
}
|