@waswrongassembled/pii-shield 0.0.0-stage → 0.1.1
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 +38 -0
- package/LICENSE +22 -0
- package/README.md +276 -2
- package/dist/ai-sdk/index.d.ts +19 -0
- package/dist/ai-sdk/index.js +30 -0
- package/dist/ai-sdk/middleware.d.ts +63 -0
- package/dist/ai-sdk/middleware.js +388 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +124 -0
- package/dist/detector.d.ts +28 -0
- package/dist/detector.js +3 -0
- package/dist/detectors/at-svnr.d.ts +14 -0
- package/dist/detectors/at-svnr.js +31 -0
- package/dist/detectors/authority-context.d.ts +22 -0
- package/dist/detectors/authority-context.js +278 -0
- package/dist/detectors/birth-date.d.ts +10 -0
- package/dist/detectors/birth-date.js +21 -0
- package/dist/detectors/email.d.ts +15 -0
- package/dist/detectors/email.js +29 -0
- package/dist/detectors/file-number.d.ts +16 -0
- package/dist/detectors/file-number.js +20 -0
- package/dist/detectors/iban.d.ts +10 -0
- package/dist/detectors/iban.js +41 -0
- package/dist/detectors/license-plate.d.ts +9 -0
- package/dist/detectors/license-plate.js +13 -0
- package/dist/detectors/phone.d.ts +13 -0
- package/dist/detectors/phone.js +38 -0
- package/dist/detectors/postal-address.d.ts +14 -0
- package/dist/detectors/postal-address.js +19 -0
- package/dist/detectors/salutation-person.d.ts +18 -0
- package/dist/detectors/salutation-person.js +37 -0
- package/dist/detectors/tax-number.d.ts +14 -0
- package/dist/detectors/tax-number.js +33 -0
- package/dist/entity-extractor.d.ts +47 -0
- package/dist/entity-extractor.js +245 -0
- package/dist/entity-type.d.ts +24 -0
- package/dist/entity-type.js +26 -0
- package/dist/entity.d.ts +28 -0
- package/dist/entity.js +11 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +49 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +40 -0
- package/dist/internal/pcre.d.ts +55 -0
- package/dist/internal/pcre.js +102 -0
- package/dist/internal/php-json.d.ts +15 -0
- package/dist/internal/php-json.js +48 -0
- package/dist/internal/placeholder-stream.d.ts +24 -0
- package/dist/internal/placeholder-stream.js +118 -0
- package/dist/internal/text-spans.d.ts +8 -0
- package/dist/internal/text-spans.js +15 -0
- package/dist/learning/char-set.d.ts +29 -0
- package/dist/learning/char-set.js +158 -0
- package/dist/learning/custom-entity-detector.d.ts +26 -0
- package/dist/learning/custom-entity-detector.js +70 -0
- package/dist/learning/custom-entity-type.d.ts +49 -0
- package/dist/learning/custom-entity-type.js +150 -0
- package/dist/learning/entity-learner.d.ts +50 -0
- package/dist/learning/entity-learner.js +87 -0
- package/dist/learning/json-file-store.d.ts +36 -0
- package/dist/learning/json-file-store.js +132 -0
- package/dist/learning/learned-pattern.d.ts +48 -0
- package/dist/learning/learned-pattern.js +640 -0
- package/dist/learning/pattern-grammar.d.ts +12 -0
- package/dist/learning/pattern-grammar.js +148 -0
- package/dist/learning/pattern-learner.d.ts +10 -0
- package/dist/learning/pattern-learner.js +116 -0
- package/dist/learning/store.d.ts +51 -0
- package/dist/learning/store.js +84 -0
- package/dist/masking/partial-mask.d.ts +23 -0
- package/dist/masking/partial-mask.js +43 -0
- package/dist/masking/strategy.d.ts +10 -0
- package/dist/masking/strategy.js +1 -0
- package/dist/masking/type-label-mask.d.ts +17 -0
- package/dist/masking/type-label-mask.js +28 -0
- package/dist/mcp/index.d.ts +33 -0
- package/dist/mcp/index.js +146 -0
- package/dist/mcp/tools.d.ts +63 -0
- package/dist/mcp/tools.js +183 -0
- package/dist/model/chunks.d.ts +13 -0
- package/dist/model/chunks.js +74 -0
- package/dist/model/model-detector.d.ts +110 -0
- package/dist/model/model-detector.js +420 -0
- package/dist/model/prompt.d.ts +16 -0
- package/dist/model/prompt.js +192 -0
- package/dist/pii-masker.d.ts +27 -0
- package/dist/pii-masker.js +56 -0
- package/dist/pii-shield.d.ts +40 -0
- package/dist/pii-shield.js +142 -0
- package/dist/placeholder.d.ts +48 -0
- package/dist/placeholder.js +138 -0
- package/dist/redaction.d.ts +76 -0
- package/dist/redaction.js +52 -0
- package/dist/server/config.d.ts +23 -0
- package/dist/server/config.js +187 -0
- package/dist/server/http-server.d.ts +63 -0
- package/dist/server/http-server.js +241 -0
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.js +9 -0
- package/dist/server/model-providers.d.ts +31 -0
- package/dist/server/model-providers.js +158 -0
- package/dist/service/json-body.d.ts +14 -0
- package/dist/service/json-body.js +35 -0
- package/dist/service/local-peer.d.ts +16 -0
- package/dist/service/local-peer.js +83 -0
- package/dist/service/service-api.d.ts +75 -0
- package/dist/service/service-api.js +305 -0
- package/dist/validators/at-svnr.d.ts +8 -0
- package/dist/validators/at-svnr.js +21 -0
- package/dist/validators/de-tax-id.d.ts +8 -0
- package/dist/validators/de-tax-id.js +35 -0
- package/dist/validators/iban.d.ts +5 -0
- package/dist/validators/iban.js +24 -0
- package/dist/vault/encrypted-vault.d.ts +37 -0
- package/dist/vault/encrypted-vault.js +152 -0
- package/dist/vault/in-memory-vault.d.ts +17 -0
- package/dist/vault/in-memory-vault.js +39 -0
- package/dist/vault/memory-vault-storage.d.ts +16 -0
- package/dist/vault/memory-vault-storage.js +37 -0
- package/dist/vault/vault.d.ts +38 -0
- package/dist/vault/vault.js +16 -0
- package/dist/vault-redis/index.d.ts +28 -0
- package/dist/vault-redis/index.js +33 -0
- package/docs/openapi.yaml +422 -0
- package/package.json +122 -4
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles and runs learned patterns with PCRE semantics, without JavaScript's regex engine.
|
|
3
|
+
*
|
|
4
|
+
* Patterns are stored in PHP/PCRE syntax (`~(?:…)~u`, i.e. UTF + UCP), so they must mean the same here.
|
|
5
|
+
* Rather than translating them to a JavaScript RegExp, which has no backtracking limit and differs in
|
|
6
|
+
* details (empty matches, `[]a]`, `\s`, `.`), they run on a small backtracking matcher for the
|
|
7
|
+
* PatternGrammar subset: single-character sets with greedy quantifiers, alternation and plain groups.
|
|
8
|
+
*
|
|
9
|
+
* Like PCRE with `pcre.backtrack_limit`, every match attempt has a budget. The engine counts each
|
|
10
|
+
* choice point it creates and each time it backtracks into one, per start position; PHP's limit of
|
|
11
|
+
* 100000 was calibrated against PCRE2's JIT (e.g. `.{0,45}` three times passes, `.{0,46}` three times
|
|
12
|
+
* does not). Exceeding it makes a search fail, the same way preg_match() returns false. Greedy runs
|
|
13
|
+
* reuse a per-instruction cache and runs that cannot give characters back create no choice point
|
|
14
|
+
* (PCRE's auto-possessification). matchAll() also has an overall budget linear in the text length.
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
import { complement, digit, dot, intersects, letterOrNumber, membership, space, union, word, } from './char-set.js';
|
|
19
|
+
/** pcre.backtrack_limit used by PHP's CustomEntityType and CustomEntityDetector. */
|
|
20
|
+
export const BACKTRACK_LIMIT = 100_000;
|
|
21
|
+
/** Overall budget of one matchAll(): PHP has none, but JavaScript must not run quadratic on adversarial text. */
|
|
22
|
+
const TOTAL_BASE = 1_000_000;
|
|
23
|
+
const TOTAL_PER_CHARACTER = 50;
|
|
24
|
+
/** Thrown inside the parser: "invalid" = PCRE would not compile it; "unsupported" = outside the grammar subset. */
|
|
25
|
+
class ParseFailure extends Error {
|
|
26
|
+
reason;
|
|
27
|
+
constructor(reason) {
|
|
28
|
+
super(reason);
|
|
29
|
+
this.reason = reason;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const SHORTHANDS = {
|
|
33
|
+
d: digit,
|
|
34
|
+
D: () => complement(digit()),
|
|
35
|
+
w: word,
|
|
36
|
+
W: () => complement(word()),
|
|
37
|
+
s: space,
|
|
38
|
+
S: () => complement(space()),
|
|
39
|
+
};
|
|
40
|
+
const isAsciiAlnum = (c) => /^[A-Za-z0-9]$/.test(c);
|
|
41
|
+
function single(c) {
|
|
42
|
+
const cp = c.codePointAt(0) ?? 0;
|
|
43
|
+
return [cp, cp];
|
|
44
|
+
}
|
|
45
|
+
class Parser {
|
|
46
|
+
#chars;
|
|
47
|
+
#i = 0;
|
|
48
|
+
constructor(pattern) {
|
|
49
|
+
this.#chars = Array.from(pattern);
|
|
50
|
+
}
|
|
51
|
+
parse() {
|
|
52
|
+
const alternatives = this.#alternation(0);
|
|
53
|
+
if (this.#i < this.#chars.length) {
|
|
54
|
+
throw new ParseFailure('invalid'); // unmatched ")"
|
|
55
|
+
}
|
|
56
|
+
return alternatives;
|
|
57
|
+
}
|
|
58
|
+
#alternation(depth) {
|
|
59
|
+
const alternatives = [[]];
|
|
60
|
+
for (;;) {
|
|
61
|
+
const c = this.#chars[this.#i];
|
|
62
|
+
const sequence = alternatives[alternatives.length - 1] ?? [];
|
|
63
|
+
if (c === undefined) {
|
|
64
|
+
if (depth > 0) {
|
|
65
|
+
throw new ParseFailure('invalid'); // missing ")"
|
|
66
|
+
}
|
|
67
|
+
return alternatives;
|
|
68
|
+
}
|
|
69
|
+
this.#i++;
|
|
70
|
+
switch (c) {
|
|
71
|
+
case '|':
|
|
72
|
+
alternatives.push([]);
|
|
73
|
+
break;
|
|
74
|
+
case ')':
|
|
75
|
+
if (depth === 0) {
|
|
76
|
+
throw new ParseFailure('invalid');
|
|
77
|
+
}
|
|
78
|
+
return alternatives;
|
|
79
|
+
case '(':
|
|
80
|
+
if (this.#chars[this.#i] === '?') {
|
|
81
|
+
if (this.#chars[this.#i + 1] !== ':') {
|
|
82
|
+
throw new ParseFailure('unsupported');
|
|
83
|
+
}
|
|
84
|
+
this.#i += 2;
|
|
85
|
+
}
|
|
86
|
+
sequence.push({ kind: 'group', alternatives: this.#alternation(depth + 1) });
|
|
87
|
+
break;
|
|
88
|
+
case '*':
|
|
89
|
+
case '+':
|
|
90
|
+
case '?':
|
|
91
|
+
this.#quantify(sequence, c === '+' ? 1 : 0, c === '?' ? 1 : Infinity);
|
|
92
|
+
break;
|
|
93
|
+
case '{':
|
|
94
|
+
this.#brace(sequence);
|
|
95
|
+
break;
|
|
96
|
+
case '[':
|
|
97
|
+
sequence.push(setItem(this.#class()));
|
|
98
|
+
break;
|
|
99
|
+
case '\\':
|
|
100
|
+
sequence.push(setItem(this.#escape()));
|
|
101
|
+
break;
|
|
102
|
+
case '.':
|
|
103
|
+
sequence.push(setItem(dot()));
|
|
104
|
+
break;
|
|
105
|
+
case '^':
|
|
106
|
+
case '$':
|
|
107
|
+
throw new ParseFailure('unsupported');
|
|
108
|
+
case '~':
|
|
109
|
+
throw new ParseFailure('invalid'); // ends PHP's "~…~u" delimiters
|
|
110
|
+
default:
|
|
111
|
+
sequence.push(setItem(single(c)));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
#brace(sequence) {
|
|
116
|
+
const rest = this.#chars.slice(this.#i, this.#i + 16).join('');
|
|
117
|
+
const m = /^([0-9]+)(?:,([0-9]*))?\}/.exec(rest);
|
|
118
|
+
if (m === null) {
|
|
119
|
+
if (/^\s*,?\s*[0-9]/.test(rest)) {
|
|
120
|
+
throw new ParseFailure('unsupported'); // {,n} or spaces: newer PCRE2 syntax
|
|
121
|
+
}
|
|
122
|
+
sequence.push(setItem(single('{')));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const min = Number(m[1]);
|
|
126
|
+
const max = m[2] === undefined ? min : m[2] === '' ? Infinity : Number(m[2]);
|
|
127
|
+
if (min > 65535 || max < min || (max !== Infinity && max > 65535)) {
|
|
128
|
+
throw new ParseFailure('invalid');
|
|
129
|
+
}
|
|
130
|
+
this.#i += m[0].length;
|
|
131
|
+
this.#quantify(sequence, min, max);
|
|
132
|
+
}
|
|
133
|
+
#quantify(sequence, min, max) {
|
|
134
|
+
const last = sequence[sequence.length - 1];
|
|
135
|
+
if (last === undefined) {
|
|
136
|
+
throw new ParseFailure('invalid'); // nothing to repeat
|
|
137
|
+
}
|
|
138
|
+
if (last.kind === 'group' || last.quantified) {
|
|
139
|
+
throw new ParseFailure('unsupported');
|
|
140
|
+
}
|
|
141
|
+
const next = this.#chars[this.#i];
|
|
142
|
+
if (next === '?' || next === '+') {
|
|
143
|
+
throw new ParseFailure('unsupported');
|
|
144
|
+
}
|
|
145
|
+
last.min = min;
|
|
146
|
+
last.max = max;
|
|
147
|
+
last.quantified = true;
|
|
148
|
+
}
|
|
149
|
+
/** After a backslash. */
|
|
150
|
+
#escape() {
|
|
151
|
+
const next = this.#chars[this.#i++];
|
|
152
|
+
if (next === undefined) {
|
|
153
|
+
throw new ParseFailure('invalid');
|
|
154
|
+
}
|
|
155
|
+
const shorthand = SHORTHANDS[next];
|
|
156
|
+
if (shorthand !== undefined) {
|
|
157
|
+
return shorthand();
|
|
158
|
+
}
|
|
159
|
+
if (isAsciiAlnum(next)) {
|
|
160
|
+
throw new ParseFailure('unsupported'); // \b, \n, \x41, \p{L}, backreferences, ...
|
|
161
|
+
}
|
|
162
|
+
return single(next);
|
|
163
|
+
}
|
|
164
|
+
/** After "[". PCRE rules: "]" first is literal, "-" at either end is literal, no shorthand in a range. */
|
|
165
|
+
#class() {
|
|
166
|
+
let negated = false;
|
|
167
|
+
if (this.#chars[this.#i] === '^') {
|
|
168
|
+
negated = true;
|
|
169
|
+
this.#i++;
|
|
170
|
+
}
|
|
171
|
+
const parts = [];
|
|
172
|
+
for (let first = true;; first = false) {
|
|
173
|
+
const c = this.#chars[this.#i];
|
|
174
|
+
if (c === undefined) {
|
|
175
|
+
throw new ParseFailure('invalid');
|
|
176
|
+
}
|
|
177
|
+
if (c === ']' && !first) {
|
|
178
|
+
this.#i++;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
const atom = this.#classAtom();
|
|
182
|
+
if (this.#chars[this.#i] === '-' && this.#chars[this.#i + 1] !== undefined && this.#chars[this.#i + 1] !== ']') {
|
|
183
|
+
if (atom.shorthand) {
|
|
184
|
+
throw new ParseFailure('invalid');
|
|
185
|
+
}
|
|
186
|
+
this.#i++;
|
|
187
|
+
const end = this.#classAtom();
|
|
188
|
+
if (end.shorthand) {
|
|
189
|
+
throw new ParseFailure('invalid');
|
|
190
|
+
}
|
|
191
|
+
const lo = atom.set[0] ?? 0;
|
|
192
|
+
const hi = end.set[0] ?? 0;
|
|
193
|
+
if (lo > hi) {
|
|
194
|
+
throw new ParseFailure('invalid');
|
|
195
|
+
}
|
|
196
|
+
parts.push([lo, hi]);
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
parts.push(atom.set);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const set = union(...parts);
|
|
203
|
+
return negated ? complement(set) : set;
|
|
204
|
+
}
|
|
205
|
+
#classAtom() {
|
|
206
|
+
const c = this.#chars[this.#i++] ?? '';
|
|
207
|
+
if (c === '[') {
|
|
208
|
+
throw new ParseFailure('unsupported'); // POSIX classes and nesting are outside the grammar
|
|
209
|
+
}
|
|
210
|
+
if (c === '~') {
|
|
211
|
+
throw new ParseFailure('invalid');
|
|
212
|
+
}
|
|
213
|
+
if (c === '\\') {
|
|
214
|
+
const next = this.#chars[this.#i];
|
|
215
|
+
const set = this.#escape();
|
|
216
|
+
return { set, shorthand: next !== undefined && next in SHORTHANDS };
|
|
217
|
+
}
|
|
218
|
+
return { set: single(c), shorthand: false };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function setItem(set) {
|
|
222
|
+
return { kind: 'set', set, min: 1, max: 1, quantified: false };
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Best guess whether PCRE compiles a pattern that lies outside the grammar subset. Only decides which of
|
|
226
|
+
* two rejection messages the caller shows: such patterns are rejected by the grammar anyway.
|
|
227
|
+
*/
|
|
228
|
+
function pcreLikelyCompiles(pattern) {
|
|
229
|
+
const chars = Array.from(pattern);
|
|
230
|
+
let depth = 0;
|
|
231
|
+
let canRepeat = false;
|
|
232
|
+
for (let i = 0; i < chars.length; i++) {
|
|
233
|
+
const c = chars[i];
|
|
234
|
+
if (c === '~') {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
if (c === '\\') {
|
|
238
|
+
if (chars[i + 1] === undefined) {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
i++;
|
|
242
|
+
canRepeat = true;
|
|
243
|
+
}
|
|
244
|
+
else if (c === '[') {
|
|
245
|
+
let j = i + 1;
|
|
246
|
+
if (chars[j] === '^') {
|
|
247
|
+
j++;
|
|
248
|
+
}
|
|
249
|
+
if (chars[j] === ']') {
|
|
250
|
+
j++;
|
|
251
|
+
}
|
|
252
|
+
for (; j < chars.length && chars[j] !== ']'; j++) {
|
|
253
|
+
if (chars[j] === '\\') {
|
|
254
|
+
j++;
|
|
255
|
+
}
|
|
256
|
+
else if (chars[j] === '~') {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
else if (chars[j] === '[' && chars[j + 1] === ':') {
|
|
260
|
+
const close = chars.indexOf(']', j);
|
|
261
|
+
j = close === -1 ? chars.length : close;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (j >= chars.length) {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
i = j;
|
|
268
|
+
canRepeat = true;
|
|
269
|
+
}
|
|
270
|
+
else if (c === '(') {
|
|
271
|
+
depth++;
|
|
272
|
+
canRepeat = false;
|
|
273
|
+
if (chars[i + 1] === '?') {
|
|
274
|
+
i++;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (c === ')') {
|
|
278
|
+
if (depth-- === 0) {
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
canRepeat = true;
|
|
282
|
+
}
|
|
283
|
+
else if (c === '|') {
|
|
284
|
+
canRepeat = false;
|
|
285
|
+
}
|
|
286
|
+
else if (c === '*' || c === '+' || c === '?') {
|
|
287
|
+
if (!canRepeat) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
canRepeat = false;
|
|
291
|
+
if (chars[i + 1] === '?' || chars[i + 1] === '+') {
|
|
292
|
+
i++;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
else if (c === '{' && /^\{[0-9]+(?:,[0-9]*)?\}/.test(chars.slice(i, i + 16).join(''))) {
|
|
296
|
+
if (!canRepeat) {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
canRepeat = false;
|
|
300
|
+
i = chars.indexOf('}', i);
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
canRepeat = true;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return depth === 0;
|
|
307
|
+
}
|
|
308
|
+
function compile(alternatives) {
|
|
309
|
+
const program = [{ op: 'match' }];
|
|
310
|
+
const emit = (instruction) => program.push(instruction) - 1;
|
|
311
|
+
const sequence = (items, next) => {
|
|
312
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
313
|
+
const item = items[i];
|
|
314
|
+
if (item === undefined) {
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (item.kind === 'set') {
|
|
318
|
+
next = emit({
|
|
319
|
+
op: 'set',
|
|
320
|
+
set: item.set,
|
|
321
|
+
has: membership(item.set),
|
|
322
|
+
min: item.min,
|
|
323
|
+
max: item.max,
|
|
324
|
+
next,
|
|
325
|
+
possessive: false,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
else {
|
|
329
|
+
next = alternation(item.alternatives, next);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return next;
|
|
333
|
+
};
|
|
334
|
+
const alternation = (alts, next) => {
|
|
335
|
+
if (alts.length === 1) {
|
|
336
|
+
return sequence(alts[0] ?? [], next);
|
|
337
|
+
}
|
|
338
|
+
return emit({ op: 'split', alternatives: alts.map((alt) => sequence(alt, next)) });
|
|
339
|
+
};
|
|
340
|
+
const start = alternation(alternatives, 0);
|
|
341
|
+
// The entry point goes last; move it to a known index.
|
|
342
|
+
program.push({ op: 'split', alternatives: [start] });
|
|
343
|
+
// FIRST set of each continuation, and whether it can reach the end without consuming.
|
|
344
|
+
const firsts = new Map();
|
|
345
|
+
const first = (pc) => {
|
|
346
|
+
const known = firsts.get(pc);
|
|
347
|
+
if (known !== undefined) {
|
|
348
|
+
return known;
|
|
349
|
+
}
|
|
350
|
+
const instruction = program[pc];
|
|
351
|
+
let result;
|
|
352
|
+
if (instruction === undefined || instruction.op === 'match') {
|
|
353
|
+
result = { set: [], end: true };
|
|
354
|
+
}
|
|
355
|
+
else if (instruction.op === 'set') {
|
|
356
|
+
const rest = instruction.min > 0 ? { set: [], end: false } : first(instruction.next);
|
|
357
|
+
result = { set: union(instruction.set, rest.set), end: rest.end };
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
const parts = instruction.alternatives.map(first);
|
|
361
|
+
result = { set: union(...parts.map((p) => p.set)), end: parts.some((p) => p.end) };
|
|
362
|
+
}
|
|
363
|
+
firsts.set(pc, result);
|
|
364
|
+
return result;
|
|
365
|
+
};
|
|
366
|
+
for (const instruction of program) {
|
|
367
|
+
if (instruction.op === 'set' && instruction.max > instruction.min) {
|
|
368
|
+
const follow = first(instruction.next);
|
|
369
|
+
instruction.possessive = !follow.end && !intersects(instruction.set, follow.set);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return program;
|
|
373
|
+
}
|
|
374
|
+
// ---------------------------------------------------------------------------------------------
|
|
375
|
+
// Matching
|
|
376
|
+
// ---------------------------------------------------------------------------------------------
|
|
377
|
+
/** The search or match ran over its backtracking budget (PHP: preg_match() returns false). */
|
|
378
|
+
export class BacktrackLimitExceeded extends Error {
|
|
379
|
+
}
|
|
380
|
+
/** A text prepared for matching: code points plus their UTF-16 offsets. */
|
|
381
|
+
export class Subject {
|
|
382
|
+
text;
|
|
383
|
+
codePoints;
|
|
384
|
+
offsets;
|
|
385
|
+
/** Run caches of the programs that searched this text. */
|
|
386
|
+
runs = new WeakMap();
|
|
387
|
+
constructor(text) {
|
|
388
|
+
this.text = text;
|
|
389
|
+
const cps = [];
|
|
390
|
+
const offsets = [];
|
|
391
|
+
for (let i = 0; i < text.length;) {
|
|
392
|
+
const cp = text.codePointAt(i) ?? 0;
|
|
393
|
+
cps.push(cp);
|
|
394
|
+
offsets.push(i);
|
|
395
|
+
i += cp > 0xffff ? 2 : 1;
|
|
396
|
+
}
|
|
397
|
+
offsets.push(text.length);
|
|
398
|
+
this.codePoints = Int32Array.from(cps);
|
|
399
|
+
this.offsets = Int32Array.from(offsets);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
let isLetterOrNumber;
|
|
403
|
+
/** A compiled learned pattern. */
|
|
404
|
+
export class LearnedPattern {
|
|
405
|
+
#program;
|
|
406
|
+
#entry;
|
|
407
|
+
constructor(program) {
|
|
408
|
+
this.#program = program;
|
|
409
|
+
this.#entry = program.length - 1;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Compiles a pattern, or says why not: "invalid" (PCRE would not compile it either) or "unsupported"
|
|
413
|
+
* (outside the grammar subset; `compiles` then guesses what PCRE says).
|
|
414
|
+
*/
|
|
415
|
+
static compile(pattern) {
|
|
416
|
+
try {
|
|
417
|
+
return new LearnedPattern(compile(new Parser(pattern).parse()));
|
|
418
|
+
}
|
|
419
|
+
catch (e) {
|
|
420
|
+
if (e instanceof ParseFailure) {
|
|
421
|
+
return { error: e.reason, compiles: e.reason === 'unsupported' && pcreLikelyCompiles(pattern) };
|
|
422
|
+
}
|
|
423
|
+
throw e;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/** `preg_match('~^(?:…)$~u', $text)`; false also when the budget runs out. */
|
|
427
|
+
matchesWhole(text, limit = Infinity) {
|
|
428
|
+
try {
|
|
429
|
+
return this.#exec(new Subject(text), 0, { whole: true, anchored: true, notEmptyAtStart: false, limit }) !== null;
|
|
430
|
+
}
|
|
431
|
+
catch (e) {
|
|
432
|
+
if (e instanceof BacktrackLimitExceeded) {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
throw e;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* `preg_match('~(?<![\p{L}\p{N}])(?:…)(?![\p{L}\p{N}])~u', $text)` within the budget: `limit` per start
|
|
440
|
+
* position like PCRE, and optionally a `total` shared across calls (see runsInBoundedTime()).
|
|
441
|
+
*/
|
|
442
|
+
searchesWithin(text, limit, total) {
|
|
443
|
+
try {
|
|
444
|
+
this.#exec(new Subject(text), 0, {
|
|
445
|
+
whole: false,
|
|
446
|
+
anchored: false,
|
|
447
|
+
notEmptyAtStart: false,
|
|
448
|
+
limit,
|
|
449
|
+
...(total === undefined ? {} : { total }),
|
|
450
|
+
});
|
|
451
|
+
return true;
|
|
452
|
+
}
|
|
453
|
+
catch (e) {
|
|
454
|
+
if (e instanceof BacktrackLimitExceeded) {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
throw e;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* All whole-word matches like preg_match_all(), with UTF-16 offsets; empty matches are dropped (as
|
|
462
|
+
* RegexMatcher does). Throws BacktrackLimitExceeded when one search exceeds the budget.
|
|
463
|
+
*/
|
|
464
|
+
matchAll(text, limit = BACKTRACK_LIMIT) {
|
|
465
|
+
const subject = new Subject(text);
|
|
466
|
+
const n = subject.codePoints.length;
|
|
467
|
+
const result = [];
|
|
468
|
+
let position = 0;
|
|
469
|
+
let notEmpty = false;
|
|
470
|
+
const total = { steps: 0, max: TOTAL_BASE + TOTAL_PER_CHARACTER * n };
|
|
471
|
+
while (position <= n) {
|
|
472
|
+
const match = this.#exec(subject, position, {
|
|
473
|
+
whole: false,
|
|
474
|
+
anchored: notEmpty,
|
|
475
|
+
notEmptyAtStart: notEmpty,
|
|
476
|
+
limit,
|
|
477
|
+
total,
|
|
478
|
+
});
|
|
479
|
+
if (match === null) {
|
|
480
|
+
if (!notEmpty || position >= n) {
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
// After an empty match PCRE retries non-empty at the same place, then moves on by one character.
|
|
484
|
+
notEmpty = false;
|
|
485
|
+
position++;
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
const [start, end] = match;
|
|
489
|
+
if (end > start) {
|
|
490
|
+
const from = subject.offsets[start] ?? 0;
|
|
491
|
+
result.push({ value: text.slice(from, subject.offsets[end]), offset: from });
|
|
492
|
+
}
|
|
493
|
+
position = end;
|
|
494
|
+
notEmpty = end === start;
|
|
495
|
+
}
|
|
496
|
+
return result;
|
|
497
|
+
}
|
|
498
|
+
#exec(subject, from, options) {
|
|
499
|
+
isLetterOrNumber ??= membership(letterOrNumber());
|
|
500
|
+
const isLN = isLetterOrNumber;
|
|
501
|
+
const program = this.#program;
|
|
502
|
+
const cps = subject.codePoints;
|
|
503
|
+
const n = cps.length;
|
|
504
|
+
// Per set instruction: a known run [runFrom, runEnd) of members followed by a non-member (or the end).
|
|
505
|
+
// Kept on the subject, so the searches of one matchAll() share it.
|
|
506
|
+
let runs = subject.runs.get(program);
|
|
507
|
+
if (runs === undefined) {
|
|
508
|
+
runs = { from: new Int32Array(program.length).fill(-1), end: new Int32Array(program.length) };
|
|
509
|
+
subject.runs.set(program, runs);
|
|
510
|
+
}
|
|
511
|
+
const { from: runFrom, end: runEnd } = runs;
|
|
512
|
+
const stackPc = [];
|
|
513
|
+
const stackPos = [];
|
|
514
|
+
const stackK = [];
|
|
515
|
+
let steps;
|
|
516
|
+
const total = options.total ?? { steps: 0, max: Infinity };
|
|
517
|
+
const runLength = (pc, instruction, pos) => {
|
|
518
|
+
const cachedFrom = runFrom[pc] ?? -1;
|
|
519
|
+
const cachedEnd = runEnd[pc] ?? 0;
|
|
520
|
+
let end;
|
|
521
|
+
if (cachedFrom !== -1 && pos >= cachedFrom && pos <= cachedEnd) {
|
|
522
|
+
end = cachedEnd;
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
end = pos;
|
|
526
|
+
while (end < n && instruction.has(cps[end] ?? 0)) {
|
|
527
|
+
end++;
|
|
528
|
+
if (end === cachedFrom && cachedFrom !== -1) {
|
|
529
|
+
end = cachedEnd;
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
runFrom[pc] = pos;
|
|
534
|
+
runEnd[pc] = end;
|
|
535
|
+
}
|
|
536
|
+
return Math.min(end - pos, instruction.max);
|
|
537
|
+
};
|
|
538
|
+
for (let start = from; start <= n; start++) {
|
|
539
|
+
if (!options.whole && start > 0 && isLN(cps[start - 1] ?? 0)) {
|
|
540
|
+
if (options.anchored) {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
let pc = this.#entry;
|
|
546
|
+
let pos = start;
|
|
547
|
+
steps = 0;
|
|
548
|
+
stackPc.length = 0;
|
|
549
|
+
stackPos.length = 0;
|
|
550
|
+
stackK.length = 0;
|
|
551
|
+
for (;;) {
|
|
552
|
+
const instruction = program[pc];
|
|
553
|
+
let failed = false;
|
|
554
|
+
if (instruction === undefined || instruction.op === 'match') {
|
|
555
|
+
const atEnd = options.whole
|
|
556
|
+
? pos === n || (pos === n - 1 && cps[pos] === 0x0a)
|
|
557
|
+
: pos === n || !isLN(cps[pos] ?? 0);
|
|
558
|
+
if (atEnd && !(options.notEmptyAtStart && pos === start)) {
|
|
559
|
+
return [start, pos];
|
|
560
|
+
}
|
|
561
|
+
failed = true;
|
|
562
|
+
}
|
|
563
|
+
else if (instruction.op === 'set') {
|
|
564
|
+
const k = runLength(pc, instruction, pos);
|
|
565
|
+
if (k < instruction.min) {
|
|
566
|
+
failed = true;
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
if (k > instruction.min && !instruction.possessive) {
|
|
570
|
+
stackPc.push(pc);
|
|
571
|
+
stackPos.push(pos);
|
|
572
|
+
stackK.push(k);
|
|
573
|
+
if (++steps > options.limit || ++total.steps > total.max) {
|
|
574
|
+
throw new BacktrackLimitExceeded();
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
pos += k;
|
|
578
|
+
pc = instruction.next;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
if (instruction.alternatives.length > 1) {
|
|
583
|
+
stackPc.push(pc);
|
|
584
|
+
stackPos.push(pos);
|
|
585
|
+
stackK.push(0);
|
|
586
|
+
if (++steps > options.limit || ++total.steps > total.max) {
|
|
587
|
+
throw new BacktrackLimitExceeded();
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
pc = instruction.alternatives[0] ?? 0;
|
|
591
|
+
}
|
|
592
|
+
if (!failed) {
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
// Backtrack into the most recent choice point.
|
|
596
|
+
const top = stackPc.length - 1;
|
|
597
|
+
if (top < 0) {
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
if (++steps > options.limit || ++total.steps > total.max) {
|
|
601
|
+
throw new BacktrackLimitExceeded();
|
|
602
|
+
}
|
|
603
|
+
const framePc = stackPc[top] ?? 0;
|
|
604
|
+
const framePos = stackPos[top] ?? 0;
|
|
605
|
+
const frameK = stackK[top] ?? 0;
|
|
606
|
+
const frame = program[framePc];
|
|
607
|
+
if (frame?.op === 'set') {
|
|
608
|
+
const k = frameK - 1;
|
|
609
|
+
if (k > frame.min) {
|
|
610
|
+
stackK[top] = k;
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
stackPc.pop();
|
|
614
|
+
stackPos.pop();
|
|
615
|
+
stackK.pop();
|
|
616
|
+
}
|
|
617
|
+
pos = framePos + k;
|
|
618
|
+
pc = frame.next;
|
|
619
|
+
}
|
|
620
|
+
else if (frame?.op === 'split') {
|
|
621
|
+
const index = frameK + 1;
|
|
622
|
+
if (index < frame.alternatives.length - 1) {
|
|
623
|
+
stackK[top] = index;
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
stackPc.pop();
|
|
627
|
+
stackPos.pop();
|
|
628
|
+
stackK.pop();
|
|
629
|
+
}
|
|
630
|
+
pos = framePos;
|
|
631
|
+
pc = frame.alternatives[index] ?? 0;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (options.anchored) {
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whitelist grammar for hand-written patterns, parsed left to right (port of PHP's PatternGrammar).
|
|
3
|
+
*
|
|
4
|
+
* Allowed: literals, escaped metacharacters, \d \D \w \W \s \S, ".", character classes "[...]"
|
|
5
|
+
* (literals, ranges, the same escapes), alternation "|", groups "(...)" and "(?:...)" WITHOUT a
|
|
6
|
+
* quantifier, and quantifiers * + ? {n} {n,} {n,m} directly after a single atom.
|
|
7
|
+
* The messages are part of the service API and identical to PHP.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
/** Why the pattern is not allowed, or null if it is. */
|
|
12
|
+
export declare function patternViolation(pattern: string): string | null;
|