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