@guhttps/veu 0.0.0-stage → 0.5.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/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # @guhttps/veu
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Véu para JavaScript e TypeScript.** Esconde dados pessoais brasileiros e segredos (CPF, CNPJ, nomes, telefones, endereços, chaves de API, senhas) antes de o texto chegar a um modelo de IA, e devolve os dados reais na resposta.
4
+
5
+ ```
6
+ Você escreve: "Cliente Maria Souza, CPF 529.982.247-25, chave sk-proj-..."
7
+ A IA recebe: "Cliente [PESSOA_1], CPF [CPF_1], chave [CHAVE_API_1]"
8
+ A IA responde: "Olá [PESSOA_1], ..."
9
+ Você recebe: "Olá Maria Souza, ..."
10
+ ```
11
+
12
+ - **Sem dependências e sem servidor:** roda no Node, no Deno, no Bun, no navegador e em edge functions.
13
+ - **Mesma detecção da versão em Python:** um teste de conformidade com 235 casos garante resultados idênticos.
14
+ - **Funciona com o que você já usa:** SDKs da OpenAI e da Anthropic, AI SDK da Vercel e qualquer código que aceite um `fetch`.
15
+
16
+ ```bash
17
+ npm install @guhttps/veu
18
+ ```
19
+
20
+ ## Uso básico
21
+
22
+ ```ts
23
+ import { Veu } from "@guhttps/veu";
24
+
25
+ const veu = new Veu();
26
+ const resultado = veu.anonymize("Cliente Maria Souza, CPF 529.982.247-25");
27
+ resultado.text; // "Cliente [PESSOA_1], CPF [CPF_1]"
28
+ resultado.restore("Olá [PESSOA_1]!"); // "Olá Maria Souza!"
29
+ veu.analyze("chave sk-proj-..."); // [{ label: "CHAVE_API", start, end, score, text }]
30
+ ```
31
+
32
+ Numa conversa com várias mensagens, use uma sessão: o mesmo CPF vira o mesmo marcador em todas elas.
33
+
34
+ ```ts
35
+ const sessao = veu.session();
36
+ const mensagens = sessao.anonymizeData([{ role: "user", content: "Meu CPF é 529.982.247-25" }]);
37
+ const resposta = sessao.restore(textoDaIA);
38
+ for await (const pedaco of sessao.restoreStream(streamDeTexto)) process.stdout.write(pedaco);
39
+ ```
40
+
41
+ ## SDK da OpenAI, da Anthropic e outros (sem proxy)
42
+
43
+ ```ts
44
+ import OpenAI from "openai";
45
+ import Anthropic from "@anthropic-ai/sdk";
46
+ import { createFetch } from "@guhttps/veu/fetch";
47
+
48
+ const openai = new OpenAI({ fetch: createFetch() });
49
+ const anthropic = new Anthropic({ fetch: createFetch() });
50
+ ```
51
+
52
+ O `createFetch` entende Chat Completions, Responses, Embeddings, Anthropic Messages, Gemini e a API nativa do Ollama, inclusive em streaming. Requisições que não são de IA passam sem mudança.
53
+
54
+ Opções:
55
+
56
+ - `session`: compartilha o cofre entre chamadas.
57
+ - `block: ["CHAVE_PRIVADA"]`: recusa a requisição em vez de esconder o dado.
58
+ - `onMask: ({ counts }) => ...`: avisa quantos dados foram escondidos (só contagens, nunca os valores).
59
+ - `veu: new Veu({...})`: usa uma configuração própria.
60
+
61
+ ## AI SDK da Vercel
62
+
63
+ ```ts
64
+ import { generateText, wrapLanguageModel } from "ai";
65
+ import { openai } from "@ai-sdk/openai";
66
+ import { veuMiddleware } from "@guhttps/veu/ai-sdk";
67
+
68
+ const model = wrapLanguageModel({ model: openai("gpt-5-mini"), middleware: veuMiddleware() });
69
+ const { text } = await generateText({ model, prompt: "Resuma o caso da cliente Maria Souza, CPF 529.982.247-25" });
70
+ ```
71
+
72
+ Protege textos, argumentos de ferramentas e resultados de ferramentas, em `generateText` e `streamText`. Para o AI SDK 6, use `veuMiddleware({ version: "v3" })`; para o 5, `version: "v2"`.
73
+
74
+ ## No navegador
75
+
76
+ ```html
77
+ <script src="https://cdn.jsdelivr.net/npm/@guhttps/veu@0.5.1/dist/veu.global.js"></script>
78
+ <script>
79
+ const resultado = new veu.Veu().anonymize(document.querySelector("textarea").value);
80
+ </script>
81
+ ```
82
+
83
+ ## Configuração
84
+
85
+ ```ts
86
+ new Veu({
87
+ threshold: 0.6, // exige valores válidos (dígitos verificadores)
88
+ labels: ["CPF", "CNPJ", "CHAVE_API"], // só estes tipos
89
+ allowlist: ["contato@minhaempresa.com.br"],
90
+ allowPatterns: ["@minhaempresa\\.com\\.br$"],
91
+ detectors: ["padroes", "segredos"], // sem nomes e endereços
92
+ operator: "mascara", // token (padrão), mascara, remover ou hash
93
+ operators: { CARTAO_CREDITO: "remover" },
94
+ customPatterns: [{ entidade: "MATRICULA", padrao: "MAT-\\d{6}" }],
95
+ });
96
+ ```
97
+
98
+ O operador `sintetico` (outro CPF válido no lugar do original) ainda só existe na versão em Python.
99
+
100
+ ## O que é detectado
101
+
102
+ - **Documentos:** CPF, CNPJ (inclusive o alfanumérico de 2026), RG, CNH, título de eleitor, PIS, CNS e passaporte.
103
+ - **Contatos:** nomes, telefones (brasileiros e internacionais), e-mails e endereços.
104
+ - **Dados financeiros e outros:** CEP, placa, RENAVAM, cartões, contas, IBAN, chave Pix, IP, data de nascimento e processo judicial.
105
+ - **Segredos:**
106
+ - chaves de API da OpenAI, Anthropic, AWS, Google, GitHub, Stripe, Mercado Pago, Asaas, Notion e mais 20 serviços;
107
+ - JWT e tokens Bearer;
108
+ - senhas;
109
+ - chaves privadas;
110
+ - URLs de conexão com senha.
111
+
112
+ Nenhuma detecção automática é perfeita: o Véu reduz muito o risco, mas não o elimina. Veja o [benchmark](https://github.com/guhttps/veu#benchmark).
113
+
114
+ Licença MIT. Repositório: https://github.com/guhttps/veu
@@ -0,0 +1,7 @@
1
+ import type { Candidate, Recognizer } from "./entities.ts";
2
+ export declare class AddressRecognizer implements Recognizer {
3
+ name: string;
4
+ labels: ReadonlySet<string>;
5
+ private context;
6
+ find(text: string): Iterable<Candidate>;
7
+ }
@@ -0,0 +1,43 @@
1
+ import { caseless, contextWindow, wordsRegex } from "./text.js";
2
+ const KEYWORD_ANY_CASE = caseless("Rua|R\\.|Avenida|Av\\.?|Travessa|Trav\\.|Tv\\.|Alameda|Al\\.|Pra[çc]a|P[çc]a\\.|Rodovia|Rod\\.|Estrada|" +
3
+ "Estr\\.|Viela|Beco|Ladeira|Servid[ãa]o");
4
+ const KEYWORD = `(?:(?:${KEYWORD_ANY_CASE})|Largo|Passagem|Vila|Via)`;
5
+ const ABBREVIATION = "(?:Dr|Dra|Prof|Profa|Gen|Cel|Mal|Pres|Eng|Sen|Dep|Gov|Cap|Ten|Sta|Sto|Pe|Frei|Dom|S)\\.";
6
+ const WORD = "[A-ZÀ-Ý][\\p{L}\\p{N}_À-ÿ'’-]*";
7
+ const NAME_PART = `(?:${ABBREVIATION}|${WORD})`;
8
+ const FIRST = `(?:(?:d[aeo]s?\\s+)?(?:\\d{1,3}\\s+(?:de\\s+)?${WORD}|${NAME_PART}))`;
9
+ const NEXT = `(?:\\s+(?:(?:d[aeo]s?|e)\\s+)?${NAME_PART})`;
10
+ const NUMBER = "(?:\\s*,\\s*|\\s+)(?:(?:n[º°o]\\.?|n\\.|número)\\s*)?(?:\\d{1,6}[A-Za-z]?|[Ss]/[Nn])(?![\\p{L}\\p{N}_/])";
11
+ const COMPLEMENT_WORDS = caseless("apto?\\.?|apartamento|ap\\.|bloco|bl\\.|casa|cs\\.|sala|sl\\.|lote|lt\\.|quadra|qd\\.|" +
12
+ "conjunto|cj\\.|andar|loja|torre|fundos|frente");
13
+ const COMPLEMENT = `(?:\\s*[,–-]?\\s*(?:${COMPLEMENT_WORDS})(?:\\s*[\\p{L}\\p{N}_-]{1,6})?(?![\\p{L}\\p{N}_]))`;
14
+ const CAPITALIZED = new RegExp(`(?<![\\p{L}\\p{N}_])${KEYWORD}\\s+${FIRST}${NEXT}{0,6}(?<number>${NUMBER})?(?:${COMPLEMENT}){0,3}`, "gu");
15
+ const LOWERCASE = new RegExp("(?<![\\p{L}\\p{N}_])(?:rua|avenida|av\\.?|travessa|alameda|pra[çc]a|estrada)\\s+(?:[a-zà-ÿ]+\\s+){1,5}?" +
16
+ `(?:n[º°o]\\.?\\s*)?\\d{1,6}(?![\\p{L}\\p{N}_])(?:${COMPLEMENT}){0,3}`, "gu");
17
+ const ADDRESS_CONTEXT = [
18
+ "moro", "mora", "moramos", "resido", "reside", "residente", "domiciliado", "domiciliada", "endereco",
19
+ "entrega", "entregar", "enviar para", "envio para", "localizado", "localizada", "situado", "situada",
20
+ "sede", "fica na", "fica no", "cobranca", "imovel",
21
+ ];
22
+ export class AddressRecognizer {
23
+ name = "enderecos";
24
+ labels = new Set(["ENDERECO"]);
25
+ context = wordsRegex(ADDRESS_CONTEXT);
26
+ *find(text) {
27
+ for (const match of text.matchAll(CAPITALIZED)) {
28
+ const start = match.index;
29
+ let end = start + match[0].length;
30
+ while (end > start && (text[end - 1] === " " || text[end - 1] === ","))
31
+ end -= 1;
32
+ let score;
33
+ if (match.groups?.number)
34
+ score = 0.9;
35
+ else
36
+ score = this.context.test(contextWindow(text, start, end, 40, 0)) ? 0.75 : 0.45;
37
+ yield { label: "ENDERECO", start, end, score, recognizer: this.name };
38
+ }
39
+ for (const match of text.matchAll(LOWERCASE)) {
40
+ yield { label: "ENDERECO", start: match.index, end: match.index + match[0].length, score: 0.7, recognizer: this.name };
41
+ }
42
+ }
43
+ }
@@ -0,0 +1,28 @@
1
+ import type { Candidate, Entity, Recognizer } from "./entities.ts";
2
+ export declare const DEFAULT_THRESHOLD = 0.5;
3
+ export declare function defaultRecognizers(): Recognizer[];
4
+ export interface AnalyzerOptions {
5
+ /** Pontuação mínima de 0 a 1 (padrão 0,5). */
6
+ threshold?: number;
7
+ /** Limita a detecção a alguns tipos (por padrão, todos). */
8
+ labels?: Iterable<string>;
9
+ /** Valores que nunca são escondidos (dados da própria empresa, contatos públicos). */
10
+ allowlist?: Iterable<string>;
11
+ /** Expressões regulares: valores que casarem nunca são escondidos. */
12
+ allowPatterns?: Iterable<string | RegExp>;
13
+ }
14
+ export declare class Analyzer {
15
+ recognizers: Recognizer[];
16
+ threshold: number;
17
+ labels: Set<string> | null;
18
+ private allowText;
19
+ private allowCodes;
20
+ private allowPatterns;
21
+ private hasAllowlist;
22
+ constructor(recognizers?: Recognizer[], options?: AnalyzerOptions);
23
+ private allowed;
24
+ candidates(text: string, threshold?: number): Candidate[];
25
+ analyze(text: string, threshold?: number): Entity[];
26
+ }
27
+ /** Um candidato por trecho: o contido em outro maior sai; nas sobreposições vence a maior pontuação. */
28
+ export declare function resolveOverlaps(candidates: Candidate[]): Candidate[];
@@ -0,0 +1,94 @@
1
+ // Junta os detectores, filtra pela pontuação e resolve sobreposições (equivalente a veu/analyzer.py).
2
+ import { AddressRecognizer } from "./addresses.js";
3
+ import { PatternRecognizer } from "./patterns.js";
4
+ import { PersonRecognizer } from "./persons.js";
5
+ import { SecretRecognizer } from "./secrets.js";
6
+ import { bisectLeft, fold, onlyDigits } from "./text.js";
7
+ import { normalizeCnpj } from "./validators.js";
8
+ export const DEFAULT_THRESHOLD = 0.5;
9
+ export function defaultRecognizers() {
10
+ return [new PatternRecognizer(), new PersonRecognizer(), new AddressRecognizer(), new SecretRecognizer()];
11
+ }
12
+ export class Analyzer {
13
+ recognizers;
14
+ threshold;
15
+ labels;
16
+ allowText;
17
+ allowCodes;
18
+ allowPatterns;
19
+ hasAllowlist;
20
+ constructor(recognizers, options = {}) {
21
+ this.recognizers = recognizers ?? defaultRecognizers();
22
+ this.threshold = options.threshold ?? DEFAULT_THRESHOLD;
23
+ const labels = options.labels ? [...options.labels] : [];
24
+ this.labels = labels.length ? new Set(labels.map((label) => label.toUpperCase())) : null;
25
+ const allowlist = [...(options.allowlist ?? [])];
26
+ this.allowText = new Set(allowlist.map(fold));
27
+ this.allowCodes = new Set(allowlist.map(onlyDigits).filter((digits) => digits.length >= 6));
28
+ for (const value of allowlist) {
29
+ const cnpj = normalizeCnpj(value);
30
+ if (cnpj.length === 14)
31
+ this.allowCodes.add(cnpj);
32
+ }
33
+ this.allowPatterns = [...(options.allowPatterns ?? [])].map((p) => (typeof p === "string" ? new RegExp(p, "iu") : p));
34
+ this.hasAllowlist = this.allowText.size > 0 || this.allowCodes.size > 0 || this.allowPatterns.length > 0;
35
+ }
36
+ allowed(value) {
37
+ if (this.allowText.has(fold(value)))
38
+ return true;
39
+ if (this.allowPatterns.some((pattern) => pattern.test(value)))
40
+ return true;
41
+ const digits = onlyDigits(value);
42
+ return (digits.length >= 6 && this.allowCodes.has(digits)) || this.allowCodes.has(normalizeCnpj(value));
43
+ }
44
+ candidates(text, threshold) {
45
+ const minimum = threshold ?? this.threshold;
46
+ const found = [];
47
+ for (const recognizer of this.recognizers) {
48
+ for (const candidate of recognizer.find(text)) {
49
+ if (candidate.score < minimum)
50
+ continue;
51
+ if (this.labels !== null && !this.labels.has(candidate.label))
52
+ continue;
53
+ if (this.hasAllowlist && this.allowed(text.slice(candidate.start, candidate.end)))
54
+ continue;
55
+ found.push(candidate);
56
+ }
57
+ }
58
+ return found;
59
+ }
60
+ analyze(text, threshold) {
61
+ if (!text)
62
+ return [];
63
+ return resolveOverlaps(this.candidates(text, threshold)).map((c) => ({ ...c, text: text.slice(c.start, c.end) }));
64
+ }
65
+ }
66
+ /** Um candidato por trecho: o contido em outro maior sai; nas sobreposições vence a maior pontuação. */
67
+ export function resolveOverlaps(candidates) {
68
+ const ordered = [...candidates].sort((a, b) => a.start - b.start || b.end - a.end || b.score - a.score);
69
+ const uncontained = [];
70
+ let container = null;
71
+ for (const candidate of ordered) {
72
+ if (container !== null && candidate.end <= container.end
73
+ && !(candidate.start === container.start && candidate.end === container.end))
74
+ continue;
75
+ uncontained.push(candidate);
76
+ if (container === null || candidate.end > container.end)
77
+ container = candidate;
78
+ }
79
+ const starts = [];
80
+ const ends = [];
81
+ const chosen = [];
82
+ const byPriority = [...uncontained].sort((a, b) => b.score - a.score || (b.end - b.start) - (a.end - a.start) || a.start - b.start);
83
+ for (const candidate of byPriority) {
84
+ const position = bisectLeft(starts, candidate.start);
85
+ if (position > 0 && ends[position - 1] > candidate.start)
86
+ continue;
87
+ if (position < starts.length && starts[position] < candidate.end)
88
+ continue;
89
+ starts.splice(position, 0, candidate.start);
90
+ ends.splice(position, 0, candidate.end);
91
+ chosen.push(candidate);
92
+ }
93
+ return chosen.sort((a, b) => a.start - b.start);
94
+ }
@@ -0,0 +1,43 @@
1
+ import type { Analyzer } from "./analyzer.ts";
2
+ import { type Entity } from "./entities.ts";
3
+ import { Vault } from "./vault.ts";
4
+ export declare const OPERATORS: Record<string, string>;
5
+ export type Operator = "token" | "mascara" | "remover" | "hash";
6
+ export declare function normalizeOperator(name: string): Operator;
7
+ export declare function maskValue(label: string, value: string): string;
8
+ export interface Replacement {
9
+ entity: Entity;
10
+ replacement: string;
11
+ operator: Operator;
12
+ }
13
+ export declare class AnonymizationResult {
14
+ readonly text: string;
15
+ readonly replacements: Replacement[];
16
+ readonly vault: Vault;
17
+ constructor(text: string, replacements: Replacement[], vault: Vault);
18
+ get entities(): Entity[];
19
+ counts(): Record<string, number>;
20
+ /** Restaura um texto produzido a partir deste resultado (por exemplo, a resposta do modelo). */
21
+ restore(text: string): string;
22
+ }
23
+ export interface AnonymizerOptions {
24
+ operator?: string;
25
+ operators?: Record<string, string>;
26
+ linkNames?: boolean;
27
+ secret?: Uint8Array | string;
28
+ }
29
+ export declare class Anonymizer {
30
+ readonly analyzer: Analyzer;
31
+ readonly operator: Operator;
32
+ readonly operators: Record<string, Operator>;
33
+ readonly linkNames: boolean;
34
+ readonly secret?: Uint8Array | string;
35
+ constructor(analyzer: Analyzer, options?: AnonymizerOptions);
36
+ newVault(): Vault;
37
+ anonymize(text: string, vault?: Vault): AnonymizationResult;
38
+ /** Substitui um valor inteiro já sabido ser de um tipo (ex.: toda a coluna "cpf" de uma planilha). */
39
+ replaceValue(label: string, value: string, vault: Vault): string;
40
+ private replace;
41
+ /** Menções soltas ao primeiro nome ou ao sobrenome de uma pessoa já detectada usam o mesmo marcador. */
42
+ private linkPartialNames;
43
+ }
@@ -0,0 +1,173 @@
1
+ import { SECRET_LABELS } from "./entities.js";
2
+ import { CONNECTORS, ambiguousNames } from "./persons.js";
3
+ import { secretPrefix } from "./secrets.js";
4
+ import { bisectRight, counter, escapeRegex, fold } from "./text.js";
5
+ import { Vault } from "./vault.js";
6
+ export const OPERATORS = {
7
+ token: "marcador reversível, como [CPF_1] (padrão)",
8
+ mascara: "mascara parte do valor, como ***.982.247-**; não é reversível",
9
+ remover: "troca pelo tipo, como [CPF]; não é reversível",
10
+ hash: "marcador estável entre requisições, como [CPF_3fa2c1d9]; reversível com o mesmo cofre",
11
+ };
12
+ const ALIASES = { marcador: "token", "máscara": "mascara", mask: "mascara", redact: "remover" };
13
+ export function normalizeOperator(name) {
14
+ const key = name.trim().toLowerCase();
15
+ const resolved = ALIASES[key] ?? key;
16
+ if (resolved === "sintetico" || resolved === "sintético" || resolved === "synthetic") {
17
+ throw new Error('O operador "sintetico" ainda não está disponível na versão JavaScript. Use token, mascara, remover ou hash.');
18
+ }
19
+ if (!(resolved in OPERATORS)) {
20
+ throw new Error(`Operador desconhecido: "${name}". Use um destes: ${Object.keys(OPERATORS).join(", ")}.`);
21
+ }
22
+ return resolved;
23
+ }
24
+ export function maskValue(label, value) {
25
+ if (label === "CPF") {
26
+ const digits = [...value].filter((char) => /\d/.test(char));
27
+ if (digits.length === 11) {
28
+ let index = 0;
29
+ return [...value].map((char) => {
30
+ if (!/\d/.test(char))
31
+ return char;
32
+ const visible = index >= 3 && index < 9;
33
+ index += 1;
34
+ return visible ? char : "*";
35
+ }).join("");
36
+ }
37
+ }
38
+ if (label === "EMAIL" && value.includes("@")) {
39
+ const at = value.lastIndexOf("@");
40
+ return `${value.slice(0, 1)}***@${value.slice(at + 1)}`;
41
+ }
42
+ if (label === "PESSOA") {
43
+ return value.split(/\s+/).filter(Boolean).map((word) => (CONNECTORS.has(fold(word)) ? word : `${word.slice(0, 1)}***`)).join(" ");
44
+ }
45
+ if (label === "SENHA" || label === "CHAVE_PRIVADA")
46
+ return "********";
47
+ if (label === "URL_CONEXAO" && value.includes("://"))
48
+ return `${value.split("://")[0]}://****`;
49
+ if (SECRET_LABELS.has(label))
50
+ return `${secretPrefix(value)}****`;
51
+ const alnum = /[\p{L}\p{N}]/u;
52
+ const positions = [...value].map((char, i) => (alnum.test(char) ? i : -1)).filter((i) => i >= 0);
53
+ const keep = new Set(positions.length > 4 ? positions.slice(-2) : []);
54
+ return [...value].map((char, i) => (!alnum.test(char) || keep.has(i) ? char : "*")).join("");
55
+ }
56
+ export class AnonymizationResult {
57
+ text;
58
+ replacements;
59
+ vault;
60
+ constructor(text, replacements, vault) {
61
+ this.text = text;
62
+ this.replacements = replacements;
63
+ this.vault = vault;
64
+ }
65
+ get entities() {
66
+ return this.replacements.map((item) => item.entity);
67
+ }
68
+ counts() {
69
+ return counter(this.replacements.map((item) => item.entity.label));
70
+ }
71
+ /** Restaura um texto produzido a partir deste resultado (por exemplo, a resposta do modelo). */
72
+ restore(text) {
73
+ return this.vault.restore(text);
74
+ }
75
+ }
76
+ export class Anonymizer {
77
+ analyzer;
78
+ operator;
79
+ operators;
80
+ linkNames;
81
+ secret;
82
+ constructor(analyzer, options = {}) {
83
+ this.analyzer = analyzer;
84
+ this.operator = normalizeOperator(options.operator ?? "token");
85
+ this.operators = Object.fromEntries(Object.entries(options.operators ?? {}).map(([label, op]) => [label.toUpperCase(), normalizeOperator(op)]));
86
+ this.linkNames = options.linkNames ?? true;
87
+ this.secret = options.secret;
88
+ }
89
+ newVault() {
90
+ return new Vault(this.secret);
91
+ }
92
+ anonymize(text, vault = this.newVault()) {
93
+ let entities = this.analyzer.analyze(text);
94
+ let canonical = new Map();
95
+ if (this.linkNames && entities.length)
96
+ [entities, canonical] = this.linkPartialNames(text, entities);
97
+ const output = [];
98
+ const replacements = [];
99
+ let position = 0;
100
+ for (const entity of entities) {
101
+ const operator = this.operators[entity.label] ?? this.operator;
102
+ const replacement = this.replace(entity, operator, vault, canonical.get(entity.start));
103
+ output.push(text.slice(position, entity.start), replacement);
104
+ replacements.push({ entity, replacement, operator });
105
+ position = entity.end;
106
+ }
107
+ output.push(text.slice(position));
108
+ return new AnonymizationResult(output.join(""), replacements, vault);
109
+ }
110
+ /** Substitui um valor inteiro já sabido ser de um tipo (ex.: toda a coluna "cpf" de uma planilha). */
111
+ replaceValue(label, value, vault) {
112
+ const upper = label.toUpperCase();
113
+ const entity = { label: upper, start: 0, end: value.length, score: 1, recognizer: "forcado", text: value };
114
+ return this.replace(entity, this.operators[upper] ?? this.operator, vault, undefined);
115
+ }
116
+ replace(entity, operator, vault, canonical) {
117
+ if (canonical !== undefined && (operator === "token" || operator === "hash")) {
118
+ const replacement = this.replace({ ...entity, text: canonical }, operator, vault, undefined);
119
+ vault.alias(entity.label, entity.text, replacement);
120
+ return replacement;
121
+ }
122
+ if (operator === "token")
123
+ return vault.placeholder(entity.label, entity.text);
124
+ if (operator === "hash")
125
+ return vault.placeholder(entity.label, entity.text, true);
126
+ if (operator === "mascara")
127
+ return maskValue(entity.label, entity.text);
128
+ return `[${entity.label}]`;
129
+ }
130
+ /** Menções soltas ao primeiro nome ou ao sobrenome de uma pessoa já detectada usam o mesmo marcador. */
131
+ linkPartialNames(text, entities) {
132
+ const ambiguous = ambiguousNames();
133
+ const parts = new Map();
134
+ for (const entity of entities) {
135
+ if (entity.label !== "PESSOA")
136
+ continue;
137
+ const words = entity.text.split(/\s+/).filter((word) => word && !CONNECTORS.has(fold(word)));
138
+ if (words.length < 2)
139
+ continue;
140
+ for (const word of [words[0], words[words.length - 1]]) {
141
+ if (word.length >= 3 && !ambiguous.has(fold(word)) && word[0] !== word[0].toLowerCase() && !parts.has(word)) {
142
+ parts.set(word, entity.text);
143
+ }
144
+ }
145
+ }
146
+ const canonical = new Map();
147
+ if (!parts.size)
148
+ return [entities, canonical];
149
+ const alternatives = [...parts.keys()].sort((a, b) => b.length - a.length).map(escapeRegex).join("|");
150
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives})(?![\\p{L}\\p{N}_])`, "gu");
151
+ const added = [];
152
+ const starts = entities.map((e) => e.start);
153
+ const ends = entities.map((e) => e.end);
154
+ for (const match of text.matchAll(pattern)) {
155
+ const start = match.index;
156
+ const end = start + match[0].length;
157
+ const position = bisectRight(starts, start);
158
+ if (position > 0 && ends[position - 1] > start)
159
+ continue;
160
+ if (position < starts.length && starts[position] < end)
161
+ continue;
162
+ added.push({ label: "PESSOA", start, end, score: 0.7, recognizer: "vinculo", text: match[0] });
163
+ canonical.set(start, parts.get(match[0]));
164
+ }
165
+ const byFolded = new Map([...parts.entries()].map(([word, full]) => [fold(word), full]));
166
+ for (const entity of entities) {
167
+ if (entity.label === "PESSOA" && entity.text.split(/\s+/).filter(Boolean).length === 1 && byFolded.has(fold(entity.text))) {
168
+ canonical.set(entity.start, byFolded.get(fold(entity.text)));
169
+ }
170
+ }
171
+ return [[...entities, ...added].sort((a, b) => a.start - b.start), canonical];
172
+ }
173
+ }
package/dist/data.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export declare const firstNames: readonly string[];
2
+ export declare const surnames: readonly string[];
3
+ export declare const ambiguous: readonly string[];
4
+ export declare const stopwords: readonly string[];
5
+ export declare const places: readonly string[];
6
+ export declare const organizations: readonly string[];
7
+ export interface SecretRuleData {
8
+ id: string;
9
+ entidade: string;
10
+ padrao: string;
11
+ pontuacao: number;
12
+ grupo?: number;
13
+ filtro?: string;
14
+ aparar?: string;
15
+ }
16
+ export declare const secretRules: readonly SecretRuleData[];