@waswrongassembled/pii-shield 0.0.0-stage → 0.1.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 +29 -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,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Building blocks that make JavaScript regexes behave like the PHP package's PCRE patterns.
|
|
3
|
+
*
|
|
4
|
+
* PHP's /u modifier turns on PCRE2_UTF and PCRE2_UCP, so \d, \w, \s and \b are Unicode-aware there,
|
|
5
|
+
* while JavaScript's are ASCII (\d, \w, \b) or a different Unicode set (\s). Patterns ported from a
|
|
6
|
+
* PHP /u regex use these classes instead. They were checked code point by code point against PHP 8.5
|
|
7
|
+
* (PCRE2 10.49) and Node 24 (Unicode 17).
|
|
8
|
+
*
|
|
9
|
+
* Without /u PHP matches bytes: \d, \w and \s are ASCII there, which JavaScript's \d and \w already are.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
/** PCRE UCP \w as the inside of a character class. */
|
|
14
|
+
export const WORD_CHARS = String.raw `\p{L}\p{N}\p{Mn}\p{Pc}`;
|
|
15
|
+
/** PCRE UCP \w. */
|
|
16
|
+
export const WORD = `[${WORD_CHARS}]`;
|
|
17
|
+
/** PCRE UCP \s as the inside of a character class: JS \s lacks U+0085 and U+180E and adds U+FEFF. */
|
|
18
|
+
export const SPACE_CHARS = String.raw `\t-\r \x85\xA0\u{1680}\u{180E}\u{2000}-\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}`;
|
|
19
|
+
/** PCRE UCP \s. */
|
|
20
|
+
export const SPACE = `[${SPACE_CHARS}]`;
|
|
21
|
+
/** PCRE UCP \d. */
|
|
22
|
+
export const DIGIT = String.raw `\p{Nd}`;
|
|
23
|
+
/** PCRE \b at a position followed by a word character (e.g. `\bAmt`). */
|
|
24
|
+
export const WORD_START = `(?<!${WORD})`;
|
|
25
|
+
/** PCRE \b at a position preceded by a word character (e.g. `Amt\b`). */
|
|
26
|
+
export const WORD_END = `(?!${WORD})`;
|
|
27
|
+
/** PCRE ^ with /m: PHP's PCRE only treats "\n" as a newline, JavaScript also "\r", U+2028 and U+2029. */
|
|
28
|
+
export const LINE_START = String.raw `(?<![^\n])`;
|
|
29
|
+
/** PCRE $ with /m (see LINE_START). */
|
|
30
|
+
export const LINE_END = String.raw `(?![^\n])`;
|
|
31
|
+
const ND = /\p{Nd}/u;
|
|
32
|
+
const NON_ASCII_ND = /(?![0-9])\p{Nd}/gu;
|
|
33
|
+
/**
|
|
34
|
+
* Replaces every decimal digit (\p{Nd}: fullwidth, Arabic-Indic, Devanagari, ...) with its ASCII digit.
|
|
35
|
+
* Detectors match such digits via \d under PHP's /u; PHP's validators then count ASCII digits only and
|
|
36
|
+
* reject the match (docs/DEVIATIONS.md). Unicode assigns \p{Nd} in contiguous runs of whole 0-9 blocks,
|
|
37
|
+
* so a digit's value is its distance from the start of its run, modulo 10.
|
|
38
|
+
*/
|
|
39
|
+
export function asciiDigits(text) {
|
|
40
|
+
return text.replace(NON_ASCII_ND, (digit) => {
|
|
41
|
+
const codePoint = digit.codePointAt(0) ?? 0;
|
|
42
|
+
let start = codePoint;
|
|
43
|
+
while (ND.test(String.fromCodePoint(start - 1))) {
|
|
44
|
+
start--;
|
|
45
|
+
}
|
|
46
|
+
return String((codePoint - start) % 10);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* All matches of a global regex in text order, like PHP's preg_match_all(). With a group name, the regex
|
|
51
|
+
* needs the "d" flag; matches where the group is unmatched or empty are skipped (as RegexMatcher does).
|
|
52
|
+
*/
|
|
53
|
+
export function matchAll(regex, text, group) {
|
|
54
|
+
const result = [];
|
|
55
|
+
for (const match of text.matchAll(regex)) {
|
|
56
|
+
if (group === undefined) {
|
|
57
|
+
if (match[0] !== '') {
|
|
58
|
+
result.push({ value: match[0], offset: match.index });
|
|
59
|
+
}
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const value = match.groups?.[group];
|
|
63
|
+
const span = match.indices?.groups?.[group];
|
|
64
|
+
if (value !== undefined && value !== '' && span !== undefined) {
|
|
65
|
+
result.push({ value, offset: span[0] });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
/** Number of code points, as PHP's mb_strlen() counts. */
|
|
71
|
+
export function codePointLength(text) {
|
|
72
|
+
let length = 0;
|
|
73
|
+
for (let i = 0; i < text.length; i++) {
|
|
74
|
+
const unit = text.charCodeAt(i);
|
|
75
|
+
if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length) {
|
|
76
|
+
const next = text.charCodeAt(i + 1);
|
|
77
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
78
|
+
i++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
length++;
|
|
82
|
+
}
|
|
83
|
+
return length;
|
|
84
|
+
}
|
|
85
|
+
/** PHP's intval() for decimal strings: leading " \t\n\r\v\f", optional sign, ASCII digits; anything else ends it. */
|
|
86
|
+
export function phpIntval(text) {
|
|
87
|
+
const match = /^[ \t\n\r\v\f]*([+-]?[0-9]+)/.exec(text);
|
|
88
|
+
return match?.[1] === undefined ? 0 : Number.parseInt(match[1], 10);
|
|
89
|
+
}
|
|
90
|
+
/** PHP's checkdate(). */
|
|
91
|
+
export function checkdate(month, day, year) {
|
|
92
|
+
if (month < 1 || month > 12 || day < 1 || year < 1 || year > 32767) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
96
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
|
|
97
|
+
return day <= days;
|
|
98
|
+
}
|
|
99
|
+
/** PHP's trim() without a character list: ASCII whitespace and NUL only. */
|
|
100
|
+
export function phpTrim(text) {
|
|
101
|
+
return text.replace(/^[ \t\n\r\0\v]+|[ \t\n\r\0\v]+$/g, '');
|
|
102
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PHP's `json_encode()` with default flags, for a placeholder mapping. The vault plaintext must match PHP
|
|
3
|
+
* byte for byte so payloads are identical for the same nonce:
|
|
4
|
+
*
|
|
5
|
+
* - an empty mapping is `[]` (an empty PHP array is a list);
|
|
6
|
+
* - `/` is escaped as `\/`;
|
|
7
|
+
* - every non-ASCII UTF-16 code unit becomes a lowercase `\u` escape (astral characters as surrogate pairs);
|
|
8
|
+
* - `\b \f \n \r \t` use their short forms, other control characters `\u00xx`; DEL (0x7f) stays raw.
|
|
9
|
+
*
|
|
10
|
+
* A lone surrogate is escaped like any other code unit. PHP cannot produce one (its strings are UTF-8)
|
|
11
|
+
* and its json_decode() rejects it, see docs/DEVIATIONS.md.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
export declare function encodePhpJson(mapping: Readonly<Record<string, string>>): string;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PHP's `json_encode()` with default flags, for a placeholder mapping. The vault plaintext must match PHP
|
|
3
|
+
* byte for byte so payloads are identical for the same nonce:
|
|
4
|
+
*
|
|
5
|
+
* - an empty mapping is `[]` (an empty PHP array is a list);
|
|
6
|
+
* - `/` is escaped as `\/`;
|
|
7
|
+
* - every non-ASCII UTF-16 code unit becomes a lowercase `\u` escape (astral characters as surrogate pairs);
|
|
8
|
+
* - `\b \f \n \r \t` use their short forms, other control characters `\u00xx`; DEL (0x7f) stays raw.
|
|
9
|
+
*
|
|
10
|
+
* A lone surrogate is escaped like any other code unit. PHP cannot produce one (its strings are UTF-8)
|
|
11
|
+
* and its json_decode() rejects it, see docs/DEVIATIONS.md.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
export function encodePhpJson(mapping) {
|
|
16
|
+
const entries = Object.entries(mapping);
|
|
17
|
+
if (entries.length === 0) {
|
|
18
|
+
return '[]';
|
|
19
|
+
}
|
|
20
|
+
return `{${entries.map(([key, value]) => `${encodeString(key)}:${encodeString(value)}`).join(',')}}`;
|
|
21
|
+
}
|
|
22
|
+
const SHORT_ESCAPES = {
|
|
23
|
+
0x08: '\\b',
|
|
24
|
+
0x09: '\\t',
|
|
25
|
+
0x0a: '\\n',
|
|
26
|
+
0x0c: '\\f',
|
|
27
|
+
0x0d: '\\r',
|
|
28
|
+
0x22: '\\"',
|
|
29
|
+
0x2f: '\\/',
|
|
30
|
+
0x5c: '\\\\',
|
|
31
|
+
};
|
|
32
|
+
function encodeString(value) {
|
|
33
|
+
let result = '"';
|
|
34
|
+
for (let i = 0; i < value.length; i++) {
|
|
35
|
+
const unit = value.charCodeAt(i);
|
|
36
|
+
const short = SHORT_ESCAPES[unit];
|
|
37
|
+
if (short !== undefined) {
|
|
38
|
+
result += short;
|
|
39
|
+
}
|
|
40
|
+
else if (unit < 0x20 || unit > 0x7f) {
|
|
41
|
+
result += `\\u${unit.toString(16).padStart(4, '0')}`;
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
result += value.charAt(i);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return `${result}"`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Default of `maxPending`: far longer than any placeholder a model writes. */
|
|
2
|
+
export declare const DEFAULT_MAX_PENDING = 1024;
|
|
3
|
+
/**
|
|
4
|
+
* Restores placeholders in a text that arrives in chunks (a streamed model answer).
|
|
5
|
+
*
|
|
6
|
+
* `push()` returns the restored text that is safe to emit; a possible placeholder at the end of the
|
|
7
|
+
* chunks so far (`⟦PERS`, `[[iban`, a single trailing `[`, `⟦TAX\`) is held back until it is complete
|
|
8
|
+
* or can no longer become one. The concatenated output equals `restore(whole text)`, however the text is
|
|
9
|
+
* split, so a partial placeholder is never emitted.
|
|
10
|
+
*
|
|
11
|
+
* A held candidate longer than `maxPending` UTF-16 units is given up and emitted as it is, so a stray
|
|
12
|
+
* `[[` followed by endless whitespace cannot hold the stream forever. Each chunk costs time linear in its
|
|
13
|
+
* length (plus the held text when a candidate ends).
|
|
14
|
+
*
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
export declare class PlaceholderStreamRestorer {
|
|
18
|
+
#private;
|
|
19
|
+
constructor(restore: (text: string) => string, maxPending?: number);
|
|
20
|
+
/** Adds a chunk; returns the restored text that can be emitted now (may be empty). */
|
|
21
|
+
push(chunk: string): string;
|
|
22
|
+
/** Ends the text: returns whatever is held, restored (an unfinished placeholder stays as it is). */
|
|
23
|
+
flush(): string;
|
|
24
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { isPlaceholderPrefix, PLACEHOLDER_PREFIX_DONE, placeholderLengthAt, placeholderPrefixState, stepPlaceholderPrefix, } from '../placeholder.js';
|
|
2
|
+
/** Default of `maxPending`: far longer than any placeholder a model writes. */
|
|
3
|
+
export const DEFAULT_MAX_PENDING = 1024;
|
|
4
|
+
/**
|
|
5
|
+
* Restores placeholders in a text that arrives in chunks (a streamed model answer).
|
|
6
|
+
*
|
|
7
|
+
* `push()` returns the restored text that is safe to emit; a possible placeholder at the end of the
|
|
8
|
+
* chunks so far (`⟦PERS`, `[[iban`, a single trailing `[`, `⟦TAX\`) is held back until it is complete
|
|
9
|
+
* or can no longer become one. The concatenated output equals `restore(whole text)`, however the text is
|
|
10
|
+
* split, so a partial placeholder is never emitted.
|
|
11
|
+
*
|
|
12
|
+
* A held candidate longer than `maxPending` UTF-16 units is given up and emitted as it is, so a stray
|
|
13
|
+
* `[[` followed by endless whitespace cannot hold the stream forever. Each chunk costs time linear in its
|
|
14
|
+
* length (plus the held text when a candidate ends).
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export class PlaceholderStreamRestorer {
|
|
19
|
+
/** Held text: empty, or a possible placeholder from its first character on. */
|
|
20
|
+
#pending = '';
|
|
21
|
+
/** Automaton state of `#pending` (see stepPlaceholderPrefix()). */
|
|
22
|
+
#state = 0;
|
|
23
|
+
/** A high surrogate at the end of the last chunk, waiting for its pair. */
|
|
24
|
+
#highSurrogate = '';
|
|
25
|
+
#restore;
|
|
26
|
+
#maxPending;
|
|
27
|
+
constructor(restore, maxPending = DEFAULT_MAX_PENDING) {
|
|
28
|
+
this.#restore = restore;
|
|
29
|
+
this.#maxPending = maxPending;
|
|
30
|
+
}
|
|
31
|
+
/** Adds a chunk; returns the restored text that can be emitted now (may be empty). */
|
|
32
|
+
push(chunk) {
|
|
33
|
+
let input = this.#highSurrogate + chunk;
|
|
34
|
+
this.#highSurrogate = '';
|
|
35
|
+
const last = input.charCodeAt(input.length - 1);
|
|
36
|
+
if (last >= 0xd800 && last <= 0xdbff) {
|
|
37
|
+
this.#highSurrogate = input.slice(-1);
|
|
38
|
+
input = input.slice(0, -1);
|
|
39
|
+
}
|
|
40
|
+
if (this.#pending !== '' && this.#pending.length + input.length <= this.#maxPending) {
|
|
41
|
+
const state = this.#advance(input);
|
|
42
|
+
if (state !== 0 && (state & PLACEHOLDER_PREFIX_DONE) === 0) {
|
|
43
|
+
this.#pending += input;
|
|
44
|
+
this.#state = state;
|
|
45
|
+
return '';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const text = this.#pending + input;
|
|
49
|
+
let cut = heldFrom(text, 0);
|
|
50
|
+
while (text.length - cut > this.#maxPending) {
|
|
51
|
+
cut = heldFrom(text, cut + 1);
|
|
52
|
+
}
|
|
53
|
+
this.#pending = text.slice(cut);
|
|
54
|
+
this.#state = this.#pending === '' ? 0 : placeholderPrefixState(this.#pending, 0);
|
|
55
|
+
return cut === 0 ? '' : this.#restore(text.slice(0, cut));
|
|
56
|
+
}
|
|
57
|
+
/** Ends the text: returns whatever is held, restored (an unfinished placeholder stays as it is). */
|
|
58
|
+
flush() {
|
|
59
|
+
const text = this.#pending + this.#highSurrogate;
|
|
60
|
+
this.#pending = '';
|
|
61
|
+
this.#state = 0;
|
|
62
|
+
this.#highSurrogate = '';
|
|
63
|
+
return text === '' ? '' : this.#restore(text);
|
|
64
|
+
}
|
|
65
|
+
/** State of the held candidate after `input`; stops early at 0 or a complete placeholder. */
|
|
66
|
+
#advance(input) {
|
|
67
|
+
let state = this.#state;
|
|
68
|
+
for (let i = 0; i < input.length;) {
|
|
69
|
+
const c = String.fromCodePoint(input.codePointAt(i) ?? 0);
|
|
70
|
+
state = stepPlaceholderPrefix(state, c);
|
|
71
|
+
if (state === 0 || (state & PLACEHOLDER_PREFIX_DONE) !== 0) {
|
|
72
|
+
return state;
|
|
73
|
+
}
|
|
74
|
+
i += c.length;
|
|
75
|
+
}
|
|
76
|
+
return state;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Start of the first possible, unfinished placeholder at or after `from`, or `text.length`. Complete
|
|
81
|
+
* placeholders are skipped like the restore regex skips them, so the text before the result restores
|
|
82
|
+
* exactly as it does inside the whole text.
|
|
83
|
+
*/
|
|
84
|
+
function heldFrom(text, from) {
|
|
85
|
+
const nextOpener = openerFinder(text);
|
|
86
|
+
let i = from;
|
|
87
|
+
for (;;) {
|
|
88
|
+
const j = nextOpener(i);
|
|
89
|
+
if (j === -1) {
|
|
90
|
+
return text.length;
|
|
91
|
+
}
|
|
92
|
+
const length = placeholderLengthAt(text, j);
|
|
93
|
+
if (length !== -1) {
|
|
94
|
+
i = j + length;
|
|
95
|
+
}
|
|
96
|
+
else if (isPlaceholderPrefix(text, j)) {
|
|
97
|
+
return j;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
i = j + 1;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Finds the next `⟦` or `[` at or after a growing position; remembers each search, so a scan is linear. */
|
|
105
|
+
function openerFinder(text) {
|
|
106
|
+
let bracket = -2;
|
|
107
|
+
let square = -2;
|
|
108
|
+
return (from) => {
|
|
109
|
+
if (bracket !== -1 && bracket < from)
|
|
110
|
+
bracket = text.indexOf('⟦', from);
|
|
111
|
+
if (square !== -1 && square < from)
|
|
112
|
+
square = text.indexOf('[', from);
|
|
113
|
+
if (bracket === -1) {
|
|
114
|
+
return square;
|
|
115
|
+
}
|
|
116
|
+
return square === -1 ? bracket : Math.min(bracket, square);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Entity } from '../entity.js';
|
|
2
|
+
/**
|
|
3
|
+
* Replaces entity spans in one pass (PHP's TextSpans). Offsets are UTF-16 indices.
|
|
4
|
+
*
|
|
5
|
+
* @param entities sorted by offset, not overlapping (as EntityExtractor returns them)
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export declare function replaceSpans(text: string, entities: readonly Entity[], replacement: (entity: Entity) => string): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replaces entity spans in one pass (PHP's TextSpans). Offsets are UTF-16 indices.
|
|
3
|
+
*
|
|
4
|
+
* @param entities sorted by offset, not overlapping (as EntityExtractor returns them)
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
export function replaceSpans(text, entities, replacement) {
|
|
8
|
+
let result = '';
|
|
9
|
+
let cursor = 0;
|
|
10
|
+
for (const entity of entities) {
|
|
11
|
+
result += text.slice(cursor, entity.offset) + replacement(entity);
|
|
12
|
+
cursor = entity.offset + entity.value.length;
|
|
13
|
+
}
|
|
14
|
+
return result + text.slice(cursor);
|
|
15
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets of code points as sorted, merged [lo, hi] range lists, with the PCRE2 UCP meaning of \d, \w and \s.
|
|
3
|
+
*
|
|
4
|
+
* Learned patterns are matched by our own engine (see learned-pattern.ts), so the classes are plain data
|
|
5
|
+
* here instead of JavaScript regex syntax. The Unicode tables are derived once from the runtime's
|
|
6
|
+
* property escapes (the same ones src/internal/pcre.ts uses).
|
|
7
|
+
*
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export declare const MAX_CODE_POINT = 1114111;
|
|
11
|
+
/** Flat [lo0, hi0, lo1, hi1, ...], sorted and merged, inclusive bounds. */
|
|
12
|
+
export type Ranges = readonly number[];
|
|
13
|
+
export declare function rangesFrom(pairs: readonly (readonly [number, number])[]): Ranges;
|
|
14
|
+
export declare function union(...sets: Ranges[]): Ranges;
|
|
15
|
+
export declare function complement(set: Ranges): Ranges;
|
|
16
|
+
export declare function intersects(a: Ranges, b: Ranges): boolean;
|
|
17
|
+
export declare function isSubset(a: Ranges, b: Ranges): boolean;
|
|
18
|
+
/** Fast membership test: ASCII bitmap plus binary search. */
|
|
19
|
+
export declare function membership(set: Ranges): (cp: number) => boolean;
|
|
20
|
+
/** PCRE UCP \d. */
|
|
21
|
+
export declare const digit: () => Ranges;
|
|
22
|
+
/** PCRE UCP \w: letters, numbers, non-spacing marks, connector punctuation. */
|
|
23
|
+
export declare const word: () => Ranges;
|
|
24
|
+
/** Letters and numbers: the boundary class of learned patterns (`(?<![\p{L}\p{N}])`). */
|
|
25
|
+
export declare const letterOrNumber: () => Ranges;
|
|
26
|
+
/** PCRE UCP \s (see SPACE_CHARS in src/internal/pcre.ts). */
|
|
27
|
+
export declare const space: () => Ranges;
|
|
28
|
+
/** PCRE "." without /s: everything except "\n". */
|
|
29
|
+
export declare const dot: () => Ranges;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets of code points as sorted, merged [lo, hi] range lists, with the PCRE2 UCP meaning of \d, \w and \s.
|
|
3
|
+
*
|
|
4
|
+
* Learned patterns are matched by our own engine (see learned-pattern.ts), so the classes are plain data
|
|
5
|
+
* here instead of JavaScript regex syntax. The Unicode tables are derived once from the runtime's
|
|
6
|
+
* property escapes (the same ones src/internal/pcre.ts uses).
|
|
7
|
+
*
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export const MAX_CODE_POINT = 0x10ffff;
|
|
11
|
+
export function rangesFrom(pairs) {
|
|
12
|
+
const sorted = [...pairs].sort((a, b) => a[0] - b[0]);
|
|
13
|
+
const out = [];
|
|
14
|
+
for (const [lo, hi] of sorted) {
|
|
15
|
+
const last = out.length - 1;
|
|
16
|
+
if (last > 0 && lo <= (out[last] ?? 0) + 1) {
|
|
17
|
+
out[last] = Math.max(out[last] ?? 0, hi);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
out.push(lo, hi);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
export function union(...sets) {
|
|
26
|
+
const pairs = [];
|
|
27
|
+
for (const set of sets) {
|
|
28
|
+
for (let i = 0; i < set.length; i += 2) {
|
|
29
|
+
pairs.push([set[i] ?? 0, set[i + 1] ?? 0]);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return rangesFrom(pairs);
|
|
33
|
+
}
|
|
34
|
+
export function complement(set) {
|
|
35
|
+
const out = [];
|
|
36
|
+
let next = 0;
|
|
37
|
+
for (let i = 0; i < set.length; i += 2) {
|
|
38
|
+
const lo = set[i] ?? 0;
|
|
39
|
+
const hi = set[i + 1] ?? 0;
|
|
40
|
+
if (lo > next) {
|
|
41
|
+
out.push(next, lo - 1);
|
|
42
|
+
}
|
|
43
|
+
next = hi + 1;
|
|
44
|
+
}
|
|
45
|
+
if (next <= MAX_CODE_POINT) {
|
|
46
|
+
out.push(next, MAX_CODE_POINT);
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
export function intersects(a, b) {
|
|
51
|
+
let i = 0;
|
|
52
|
+
let j = 0;
|
|
53
|
+
while (i < a.length && j < b.length) {
|
|
54
|
+
const aLo = a[i] ?? 0;
|
|
55
|
+
const aHi = a[i + 1] ?? 0;
|
|
56
|
+
const bLo = b[j] ?? 0;
|
|
57
|
+
const bHi = b[j + 1] ?? 0;
|
|
58
|
+
if (aLo <= bHi && bLo <= aHi) {
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
if (aHi < bHi) {
|
|
62
|
+
i += 2;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
j += 2;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
export function isSubset(a, b) {
|
|
71
|
+
return !intersects(a, complement(b));
|
|
72
|
+
}
|
|
73
|
+
/** Fast membership test: ASCII bitmap plus binary search. */
|
|
74
|
+
export function membership(set) {
|
|
75
|
+
const ascii = new Uint8Array(128);
|
|
76
|
+
for (let cp = 0; cp < 128; cp++) {
|
|
77
|
+
ascii[cp] = contains(set, cp) ? 1 : 0;
|
|
78
|
+
}
|
|
79
|
+
const flat = Int32Array.from(set);
|
|
80
|
+
return (cp) => (cp < 128 ? ascii[cp] === 1 : contains(flat, cp));
|
|
81
|
+
}
|
|
82
|
+
function contains(set, cp) {
|
|
83
|
+
let lo = 0;
|
|
84
|
+
let hi = set.length / 2 - 1;
|
|
85
|
+
while (lo <= hi) {
|
|
86
|
+
const mid = (lo + hi) >> 1;
|
|
87
|
+
if (cp < (set[mid * 2] ?? 0)) {
|
|
88
|
+
hi = mid - 1;
|
|
89
|
+
}
|
|
90
|
+
else if (cp > (set[mid * 2 + 1] ?? 0)) {
|
|
91
|
+
lo = mid + 1;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
let allCodePoints;
|
|
100
|
+
/** Ranges of all code points a single-character Unicode regex matches. */
|
|
101
|
+
function tableOf(regex) {
|
|
102
|
+
if (allCodePoints === undefined) {
|
|
103
|
+
// Every scalar value in order; surrogates are in no property class used here.
|
|
104
|
+
const parts = [];
|
|
105
|
+
for (let cp = 0; cp <= MAX_CODE_POINT; cp += 0x1000) {
|
|
106
|
+
const chunk = [];
|
|
107
|
+
for (let c = cp; c < cp + 0x1000; c++) {
|
|
108
|
+
if (c < 0xd800 || c > 0xdfff) {
|
|
109
|
+
chunk.push(c);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
parts.push(String.fromCodePoint(...chunk));
|
|
113
|
+
}
|
|
114
|
+
allCodePoints = parts.join('');
|
|
115
|
+
}
|
|
116
|
+
const runs = new RegExp(`(?:${regex.source})+`, 'gu');
|
|
117
|
+
const pairs = [];
|
|
118
|
+
for (const match of allCodePoints.matchAll(runs)) {
|
|
119
|
+
const run = match[0];
|
|
120
|
+
const first = run.codePointAt(0) ?? 0;
|
|
121
|
+
const lastUnit = run.charCodeAt(run.length - 1);
|
|
122
|
+
const last = run.codePointAt(lastUnit >= 0xdc00 && lastUnit <= 0xdfff ? run.length - 2 : run.length - 1) ?? first;
|
|
123
|
+
// Runs never cross the surrogate gap (U+D7FC..U+D7FF and U+E000 are in none of these classes).
|
|
124
|
+
pairs.push([first, last]);
|
|
125
|
+
}
|
|
126
|
+
return rangesFrom(pairs);
|
|
127
|
+
}
|
|
128
|
+
const cache = new Map();
|
|
129
|
+
function lazy(key, build) {
|
|
130
|
+
let set = cache.get(key);
|
|
131
|
+
if (set === undefined) {
|
|
132
|
+
set = build();
|
|
133
|
+
cache.set(key, set);
|
|
134
|
+
}
|
|
135
|
+
return set;
|
|
136
|
+
}
|
|
137
|
+
/** PCRE UCP \d. */
|
|
138
|
+
export const digit = () => lazy('d', () => tableOf(/\p{Nd}/u));
|
|
139
|
+
/** PCRE UCP \w: letters, numbers, non-spacing marks, connector punctuation. */
|
|
140
|
+
export const word = () => lazy('w', () => tableOf(/[\p{L}\p{N}\p{Mn}\p{Pc}]/u));
|
|
141
|
+
/** Letters and numbers: the boundary class of learned patterns (`(?<![\p{L}\p{N}])`). */
|
|
142
|
+
export const letterOrNumber = () => lazy('ln', () => tableOf(/[\p{L}\p{N}]/u));
|
|
143
|
+
/** PCRE UCP \s (see SPACE_CHARS in src/internal/pcre.ts). */
|
|
144
|
+
export const space = () => lazy('s', () => rangesFrom([
|
|
145
|
+
[0x09, 0x0d],
|
|
146
|
+
[0x20, 0x20],
|
|
147
|
+
[0x85, 0x85],
|
|
148
|
+
[0xa0, 0xa0],
|
|
149
|
+
[0x1680, 0x1680],
|
|
150
|
+
[0x180e, 0x180e],
|
|
151
|
+
[0x2000, 0x200a],
|
|
152
|
+
[0x2028, 0x2029],
|
|
153
|
+
[0x202f, 0x202f],
|
|
154
|
+
[0x205f, 0x205f],
|
|
155
|
+
[0x3000, 0x3000],
|
|
156
|
+
]));
|
|
157
|
+
/** PCRE "." without /s: everything except "\n". */
|
|
158
|
+
export const dot = () => lazy('.', () => complement([0x0a, 0x0a]));
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Detector } from '../detector.js';
|
|
2
|
+
import { type Entity } from '../entity.js';
|
|
3
|
+
import { type CustomEntityType } from './custom-entity-type.js';
|
|
4
|
+
/**
|
|
5
|
+
* Finds a learned type by its pattern, as a whole word (not preceded or followed by a letter or number).
|
|
6
|
+
* Types without a pattern are left to the model detector.
|
|
7
|
+
*
|
|
8
|
+
* Like PHP, every search has a backtracking budget; exceeding it throws (fail closed) instead of
|
|
9
|
+
* hanging or returning partial results.
|
|
10
|
+
*/
|
|
11
|
+
export declare class CustomEntityDetector implements Detector {
|
|
12
|
+
#private;
|
|
13
|
+
readonly name = "custom";
|
|
14
|
+
constructor(type: CustomEntityType);
|
|
15
|
+
detect(text: string): Entity[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Runs the patterns of all types `source` returns at the time of each call, so types learned later
|
|
19
|
+
* take effect on the next text. See EntityLearner.detector().
|
|
20
|
+
*/
|
|
21
|
+
export declare class LearnedTypesDetector implements Detector {
|
|
22
|
+
#private;
|
|
23
|
+
readonly name = "learned-types";
|
|
24
|
+
constructor(source: Iterable<CustomEntityType> | (() => Iterable<CustomEntityType>));
|
|
25
|
+
detect(text: string): Entity[];
|
|
26
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createEntity } from '../entity.js';
|
|
2
|
+
import { EntityType } from '../entity-type.js';
|
|
3
|
+
import { PiiShieldError } from '../errors.js';
|
|
4
|
+
import { compiledPattern } from './custom-entity-type.js';
|
|
5
|
+
import { BacktrackLimitExceeded } from './learned-pattern.js';
|
|
6
|
+
const CONFIDENCE = 0.75;
|
|
7
|
+
/**
|
|
8
|
+
* Finds a learned type by its pattern, as a whole word (not preceded or followed by a letter or number).
|
|
9
|
+
* Types without a pattern are left to the model detector.
|
|
10
|
+
*
|
|
11
|
+
* Like PHP, every search has a backtracking budget; exceeding it throws (fail closed) instead of
|
|
12
|
+
* hanging or returning partial results.
|
|
13
|
+
*/
|
|
14
|
+
export class CustomEntityDetector {
|
|
15
|
+
name = 'custom';
|
|
16
|
+
#type;
|
|
17
|
+
constructor(type) {
|
|
18
|
+
// Validates types that did not come from defineCustomEntityType().
|
|
19
|
+
compiledPattern(type);
|
|
20
|
+
this.#type = type;
|
|
21
|
+
}
|
|
22
|
+
detect(text) {
|
|
23
|
+
const pattern = compiledPattern(this.#type);
|
|
24
|
+
if (pattern === null) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
let matches;
|
|
28
|
+
try {
|
|
29
|
+
matches = pattern.matchAll(text);
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
if (e instanceof BacktrackLimitExceeded) {
|
|
33
|
+
throw new PiiShieldError('Regex failed: Backtrack limit exhausted', 'DETECTION_BACKTRACK_LIMIT');
|
|
34
|
+
}
|
|
35
|
+
throw e;
|
|
36
|
+
}
|
|
37
|
+
return matches.map(({ value, offset }) => createEntity({
|
|
38
|
+
type: EntityType.Other,
|
|
39
|
+
value,
|
|
40
|
+
offset,
|
|
41
|
+
confidence: CONFIDENCE,
|
|
42
|
+
detector: 'custom',
|
|
43
|
+
label: this.#type.name,
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Runs the patterns of all types `source` returns at the time of each call, so types learned later
|
|
49
|
+
* take effect on the next text. See EntityLearner.detector().
|
|
50
|
+
*/
|
|
51
|
+
export class LearnedTypesDetector {
|
|
52
|
+
name = 'learned-types';
|
|
53
|
+
#source;
|
|
54
|
+
#detectors = new WeakMap();
|
|
55
|
+
constructor(source) {
|
|
56
|
+
this.#source = typeof source === 'function' ? source : () => source;
|
|
57
|
+
}
|
|
58
|
+
detect(text) {
|
|
59
|
+
const entities = [];
|
|
60
|
+
for (const type of this.#source()) {
|
|
61
|
+
let detector = this.#detectors.get(type);
|
|
62
|
+
if (detector === undefined) {
|
|
63
|
+
detector = new CustomEntityDetector(type);
|
|
64
|
+
this.#detectors.set(type, detector);
|
|
65
|
+
}
|
|
66
|
+
entities.push(...detector.detect(text));
|
|
67
|
+
}
|
|
68
|
+
return entities;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { LearnedPattern } from './learned-pattern.js';
|
|
2
|
+
/** Limits of a learned type; lengths count code points (PHP's mb_strlen). */
|
|
3
|
+
export declare const CUSTOM_ENTITY_TYPE_LIMITS: Readonly<{
|
|
4
|
+
maxDescriptionLength: 300;
|
|
5
|
+
maxExamples: 20;
|
|
6
|
+
maxExampleLength: 100;
|
|
7
|
+
maxPatternLength: 200;
|
|
8
|
+
}>;
|
|
9
|
+
/**
|
|
10
|
+
* A learned entity type: a name, a description, examples and optionally a pattern.
|
|
11
|
+
*
|
|
12
|
+
* Validated, frozen data; its JSON form is exactly PHP's `CustomEntityType::toArray()`, so
|
|
13
|
+
* `JSON.stringify(type)` gives the stored shape. Create it with `defineCustomEntityType()` or
|
|
14
|
+
* `customEntityTypeFromJSON()`. Examples are stored, so they must be synthetic or anonymised.
|
|
15
|
+
*/
|
|
16
|
+
export interface CustomEntityType {
|
|
17
|
+
/** UPPER_SNAKE_CASE, becomes the placeholder name (⟦NAME_1⟧). */
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly description: string;
|
|
20
|
+
/** Values that are this type. */
|
|
21
|
+
readonly examples: readonly string[];
|
|
22
|
+
/** Similar values that are not. */
|
|
23
|
+
readonly counterExamples: readonly string[];
|
|
24
|
+
/** Regular expression in PCRE syntax without delimiters (see PatternGrammar), or null for model-only types. */
|
|
25
|
+
readonly pattern: string | null;
|
|
26
|
+
}
|
|
27
|
+
export interface CustomEntityTypeInit {
|
|
28
|
+
name: string;
|
|
29
|
+
description: string;
|
|
30
|
+
examples: readonly string[];
|
|
31
|
+
counterExamples?: readonly string[];
|
|
32
|
+
pattern?: string | null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Validates and freezes a learned type, with PHP's checks and messages.
|
|
36
|
+
*
|
|
37
|
+
* @throws LearningError
|
|
38
|
+
*/
|
|
39
|
+
export declare function defineCustomEntityType(init: CustomEntityTypeInit): CustomEntityType;
|
|
40
|
+
/**
|
|
41
|
+
* Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
|
|
42
|
+
* fields become empty, non-string list entries are dropped, unknown keys are ignored, an empty pattern
|
|
43
|
+
* means model-only. Every field is then validated.
|
|
44
|
+
*
|
|
45
|
+
* @throws LearningError
|
|
46
|
+
*/
|
|
47
|
+
export declare function customEntityTypeFromJSON(data: unknown): CustomEntityType;
|
|
48
|
+
/** The compiled pattern of a type (validating it first if it did not come from defineCustomEntityType()). */
|
|
49
|
+
export declare function compiledPattern(type: CustomEntityType): LearnedPattern | null;
|