@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.
@@ -0,0 +1,90 @@
1
+ import { Analyzer, type AnalyzerOptions } from "./analyzer.ts";
2
+ import { AnonymizationResult, Anonymizer, type AnonymizerOptions } from "./anonymizer.ts";
3
+ import type { Entity, Recognizer } from "./entities.ts";
4
+ import { StreamRestorer, Vault } from "./vault.ts";
5
+ export { Analyzer, resolveOverlaps, defaultRecognizers } from "./analyzer.ts";
6
+ export { AnonymizationResult, Anonymizer, maskValue, normalizeOperator, OPERATORS } from "./anonymizer.ts";
7
+ export type { Operator, Replacement } from "./anonymizer.ts";
8
+ export { LABELS, SECRET_LABELS } from "./entities.ts";
9
+ export type { Candidate, Entity, Recognizer } from "./entities.ts";
10
+ export { AddressRecognizer } from "./addresses.ts";
11
+ export { PatternRecognizer, customPattern, DEFAULT_SPECS } from "./patterns.ts";
12
+ export { PersonRecognizer } from "./persons.ts";
13
+ export { SecretRecognizer, keyKind, looksRandom, secretPrefix } from "./secrets.ts";
14
+ export { StreamRestorer, Vault, normalizeValue } from "./vault.ts";
15
+ export type { VaultData, VaultEntry } from "./vault.ts";
16
+ export * as validators from "./validators.ts";
17
+ export declare const VERSION = "0.5.1";
18
+ export declare const DETECTORS: readonly ["padroes", "nomes", "enderecos", "segredos"];
19
+ export type Detector = (typeof DETECTORS)[number];
20
+ /** Padrão próprio, como no [[deteccao.personalizados]] do veu.toml. */
21
+ export interface CustomPatternOptions {
22
+ entidade: string;
23
+ padrao: string;
24
+ pontuacao?: number;
25
+ contexto?: string[];
26
+ exigeContexto?: boolean;
27
+ }
28
+ export interface VeuOptions extends AnalyzerOptions, AnonymizerOptions {
29
+ /** Detectores ligados (padrão: todos). */
30
+ detectors?: Detector[];
31
+ /** Padrões próprios. */
32
+ customPatterns?: CustomPatternOptions[];
33
+ /** Detectores extras, somados aos padrões. */
34
+ extraRecognizers?: Recognizer[];
35
+ /** Avisa o modelo para repetir os marcadores (usado pelas integrações). */
36
+ instructModel?: boolean;
37
+ /** Tipos que fazem a requisição ser recusada em vez de escondida (usado pelas integrações). */
38
+ block?: string[];
39
+ }
40
+ /**
41
+ * Ponto de entrada da biblioteca.
42
+ *
43
+ * ```ts
44
+ * const veu = new Veu();
45
+ * const resultado = veu.anonymize("CPF 529.982.247-25");
46
+ * resultado.text; // "CPF [CPF_1]"
47
+ * veu.restore("Seu CPF é [CPF_1]", resultado.vault); // "Seu CPF é 529.982.247-25"
48
+ * ```
49
+ */
50
+ export declare class Veu {
51
+ readonly options: VeuOptions;
52
+ readonly analyzer: Analyzer;
53
+ readonly anonymizer: Anonymizer;
54
+ constructor(options?: VeuOptions);
55
+ analyze(text: string): Entity[];
56
+ anonymize(text: string, vault?: Vault): AnonymizationResult;
57
+ restore(text: string, vault: Vault): string;
58
+ newVault(): Vault;
59
+ /** Sessão com um cofre compartilhado por várias chamadas. */
60
+ session(vault?: Vault): Session;
61
+ /** Outra instância com os mesmos detectores e outro operador. */
62
+ withOperator(operator: string): Veu;
63
+ }
64
+ /** Um cofre compartilhado por várias chamadas: o mesmo CPF vira o mesmo [CPF_1] na conversa inteira. */
65
+ export declare class Session {
66
+ readonly veu: Veu;
67
+ readonly vault: Vault;
68
+ private totals;
69
+ constructor(veu?: Veu, vault?: Vault);
70
+ anonymize(text: string): string;
71
+ /** Anonimiza todos os textos de um objeto ou lista (por exemplo, uma lista de mensagens). */
72
+ anonymizeData<T>(value: T): T;
73
+ restore(text: string): string;
74
+ restoreData<T>(value: T): T;
75
+ restorer(): StreamRestorer;
76
+ /** Restaura um stream de pedaços de texto (por exemplo, a resposta de um modelo em streaming). */
77
+ restoreStream(chunks: AsyncIterable<string> | Iterable<string>): AsyncGenerator<string>;
78
+ counts(): Record<string, number>;
79
+ }
80
+ export declare function mapStrings(value: unknown, transform: (text: string) => string): unknown;
81
+ /** Acha os dados pessoais e segredos de um texto. */
82
+ export declare function analyze(text: string): Entity[];
83
+ /** Anonimiza um texto com a configuração padrão. */
84
+ export declare function anonymize(text: string, vault?: Vault): AnonymizationResult;
85
+ /** Restaura um texto com o cofre de uma anonimização anterior. */
86
+ export declare function restore(text: string, vault: Vault): string;
87
+ /** Uma sessão com a configuração padrão. */
88
+ export declare function session(vault?: Vault): Session;
89
+ /** Quantos dados de cada tipo há no texto (sem mostrar os valores). */
90
+ export declare function summarize(text: string): Record<string, number>;
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ // Véu para JavaScript e TypeScript: esconde dados pessoais e segredos antes de o texto chegar a um modelo de IA.
2
+ import { AddressRecognizer } from "./addresses.js";
3
+ import { Analyzer } from "./analyzer.js";
4
+ import { AnonymizationResult, Anonymizer } from "./anonymizer.js";
5
+ import { PatternRecognizer, customPattern, DEFAULT_SPECS } from "./patterns.js";
6
+ import { PersonRecognizer } from "./persons.js";
7
+ import { SecretRecognizer } from "./secrets.js";
8
+ import { counter } from "./text.js";
9
+ import { StreamRestorer, Vault } from "./vault.js";
10
+ export { Analyzer, resolveOverlaps, defaultRecognizers } from "./analyzer.js";
11
+ export { AnonymizationResult, Anonymizer, maskValue, normalizeOperator, OPERATORS } from "./anonymizer.js";
12
+ export { LABELS, SECRET_LABELS } from "./entities.js";
13
+ export { AddressRecognizer } from "./addresses.js";
14
+ export { PatternRecognizer, customPattern, DEFAULT_SPECS } from "./patterns.js";
15
+ export { PersonRecognizer } from "./persons.js";
16
+ export { SecretRecognizer, keyKind, looksRandom, secretPrefix } from "./secrets.js";
17
+ export { StreamRestorer, Vault, normalizeValue } from "./vault.js";
18
+ export * as validators from "./validators.js";
19
+ export const VERSION = "0.5.1";
20
+ export const DETECTORS = ["padroes", "nomes", "enderecos", "segredos"];
21
+ function buildRecognizers(options) {
22
+ const detectors = options.detectors ?? [...DETECTORS];
23
+ const custom = (options.customPatterns ?? []).map((p) => customPattern(p.entidade, p.padrao, p.pontuacao ?? 0.9, p.contexto ?? [], p.exigeContexto ?? false));
24
+ const recognizers = [];
25
+ for (const name of detectors) {
26
+ if (name === "padroes")
27
+ recognizers.push(new PatternRecognizer([...DEFAULT_SPECS, ...custom]));
28
+ else if (name === "nomes")
29
+ recognizers.push(new PersonRecognizer());
30
+ else if (name === "enderecos")
31
+ recognizers.push(new AddressRecognizer());
32
+ else if (name === "segredos")
33
+ recognizers.push(new SecretRecognizer());
34
+ else
35
+ throw new Error(`Detector desconhecido: "${name}". Use um de ${DETECTORS.join(", ")}.`);
36
+ }
37
+ if (custom.length && !detectors.includes("padroes"))
38
+ recognizers.push(new PatternRecognizer(custom));
39
+ return [...recognizers, ...(options.extraRecognizers ?? [])];
40
+ }
41
+ /**
42
+ * Ponto de entrada da biblioteca.
43
+ *
44
+ * ```ts
45
+ * const veu = new Veu();
46
+ * const resultado = veu.anonymize("CPF 529.982.247-25");
47
+ * resultado.text; // "CPF [CPF_1]"
48
+ * veu.restore("Seu CPF é [CPF_1]", resultado.vault); // "Seu CPF é 529.982.247-25"
49
+ * ```
50
+ */
51
+ export class Veu {
52
+ options;
53
+ analyzer;
54
+ anonymizer;
55
+ constructor(options = {}) {
56
+ this.options = { instructModel: true, ...options };
57
+ this.analyzer = new Analyzer(buildRecognizers(options), options);
58
+ this.anonymizer = new Anonymizer(this.analyzer, options);
59
+ }
60
+ analyze(text) {
61
+ return this.analyzer.analyze(text);
62
+ }
63
+ anonymize(text, vault) {
64
+ return this.anonymizer.anonymize(text, vault);
65
+ }
66
+ restore(text, vault) {
67
+ return vault.restore(text);
68
+ }
69
+ newVault() {
70
+ return this.anonymizer.newVault();
71
+ }
72
+ /** Sessão com um cofre compartilhado por várias chamadas. */
73
+ session(vault) {
74
+ return new Session(this, vault);
75
+ }
76
+ /** Outra instância com os mesmos detectores e outro operador. */
77
+ withOperator(operator) {
78
+ const clone = Object.create(Veu.prototype);
79
+ Object.assign(clone, {
80
+ options: { ...this.options, operator },
81
+ analyzer: this.analyzer,
82
+ anonymizer: new Anonymizer(this.analyzer, { ...this.options, operator }),
83
+ });
84
+ return clone;
85
+ }
86
+ }
87
+ /** Um cofre compartilhado por várias chamadas: o mesmo CPF vira o mesmo [CPF_1] na conversa inteira. */
88
+ export class Session {
89
+ veu;
90
+ vault;
91
+ totals = {};
92
+ constructor(veu = new Veu(), vault) {
93
+ this.veu = veu;
94
+ this.vault = vault ?? veu.newVault();
95
+ }
96
+ anonymize(text) {
97
+ const result = this.veu.anonymize(text, this.vault);
98
+ for (const [label, count] of Object.entries(result.counts()))
99
+ this.totals[label] = (this.totals[label] ?? 0) + count;
100
+ return result.text;
101
+ }
102
+ /** Anonimiza todos os textos de um objeto ou lista (por exemplo, uma lista de mensagens). */
103
+ anonymizeData(value) {
104
+ return mapStrings(value, (text) => this.anonymize(text));
105
+ }
106
+ restore(text) {
107
+ return this.vault.restore(text);
108
+ }
109
+ restoreData(value) {
110
+ return mapStrings(value, (text) => this.vault.restore(text));
111
+ }
112
+ restorer() {
113
+ return this.vault.restorer();
114
+ }
115
+ /** Restaura um stream de pedaços de texto (por exemplo, a resposta de um modelo em streaming). */
116
+ async *restoreStream(chunks) {
117
+ const restorer = this.vault.restorer();
118
+ for await (const chunk of chunks) {
119
+ const ready = restorer.feed(chunk);
120
+ if (ready)
121
+ yield ready;
122
+ }
123
+ const tail = restorer.flush();
124
+ if (tail)
125
+ yield tail;
126
+ }
127
+ counts() {
128
+ return { ...this.totals };
129
+ }
130
+ }
131
+ export function mapStrings(value, transform) {
132
+ if (typeof value === "string")
133
+ return transform(value);
134
+ if (Array.isArray(value))
135
+ return value.map((item) => mapStrings(item, transform));
136
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
137
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapStrings(item, transform)]));
138
+ }
139
+ return value;
140
+ }
141
+ let defaultVeu = null;
142
+ const shared = () => (defaultVeu ??= new Veu());
143
+ /** Acha os dados pessoais e segredos de um texto. */
144
+ export function analyze(text) {
145
+ return shared().analyze(text);
146
+ }
147
+ /** Anonimiza um texto com a configuração padrão. */
148
+ export function anonymize(text, vault) {
149
+ return shared().anonymize(text, vault);
150
+ }
151
+ /** Restaura um texto com o cofre de uma anonimização anterior. */
152
+ export function restore(text, vault) {
153
+ return vault.restore(text);
154
+ }
155
+ /** Uma sessão com a configuração padrão. */
156
+ export function session(vault) {
157
+ return shared().session(vault);
158
+ }
159
+ /** Quantos dados de cada tipo há no texto (sem mostrar os valores). */
160
+ export function summarize(text) {
161
+ return counter(analyze(text).map((entity) => entity.label));
162
+ }
@@ -0,0 +1,38 @@
1
+ import { Masker } from "../gateway.ts";
2
+ import { Session, Veu } from "../index.ts";
3
+ import type { Vault } from "../vault.ts";
4
+ import { type MaskInfo } from "./fetch.ts";
5
+ export { BlockedError } from "./fetch.ts";
6
+ type Json = any;
7
+ export interface VeuMiddlewareOptions {
8
+ veu?: Veu;
9
+ /** Sessão com um cofre compartilhado entre chamadas. */
10
+ session?: Session;
11
+ /** Tipos que fazem a chamada falhar com BlockedError em vez de serem escondidos. */
12
+ block?: string[];
13
+ /** Avisa o modelo para repetir os marcadores (padrão: true). */
14
+ instructModel?: boolean;
15
+ /** Versão da especificação de middleware: "v4" (AI SDK 7, padrão), "v3" (AI SDK 6) ou "v2" (AI SDK 5). */
16
+ version?: "v2" | "v3" | "v4";
17
+ onMask?: (info: MaskInfo) => void;
18
+ }
19
+ export declare function maskPrompt(prompt: Json[], masker: Masker): Json[];
20
+ export declare function veuMiddleware(options?: VeuMiddlewareOptions): {
21
+ specificationVersion: "v2" | "v3" | "v4";
22
+ middlewareVersion?: "v2" | undefined;
23
+ transformParams({ params }: {
24
+ params: Json;
25
+ type?: string;
26
+ model?: Json;
27
+ }): Promise<any>;
28
+ wrapGenerate({ doGenerate, params }: {
29
+ doGenerate: () => PromiseLike<Json>;
30
+ params: Json;
31
+ }): Promise<any>;
32
+ wrapStream({ doStream, params }: {
33
+ doStream: () => PromiseLike<Json>;
34
+ params: Json;
35
+ }): Promise<any>;
36
+ };
37
+ /** Restaura as partes de um stream do AI SDK; um marcador cortado entre partes espera a próxima. */
38
+ export declare function restoreStreamParts(vault: Vault): TransformStream<Json, Json>;
@@ -0,0 +1,197 @@
1
+ // Middleware para o AI SDK da Vercel: protege qualquer modelo (OpenAI, Anthropic, Google, Mistral...).
2
+ //
3
+ // import { wrapLanguageModel, generateText } from "ai";
4
+ // import { openai } from "@ai-sdk/openai";
5
+ // import { veuMiddleware } from "@guhttps/veu/ai-sdk";
6
+ //
7
+ // const model = wrapLanguageModel({ model: openai("gpt-5-mini"), middleware: veuMiddleware() });
8
+ //
9
+ // Esconde os dados do prompt (textos, argumentos e resultados de ferramentas) e restaura a resposta,
10
+ // inclusive em streaming. O raciocínio ("reasoning") não é alterado: ele pode vir assinado pelo provedor.
11
+ import { INSTRUCTION, Masker, restoreJsonString } from "../gateway.js";
12
+ import { Session, Veu } from "../index.js";
13
+ import { BlockedError } from "./fetch.js";
14
+ export { BlockedError } from "./fetch.js";
15
+ function maskToolOutput(output, masker) {
16
+ if (!output || typeof output !== "object")
17
+ return output;
18
+ if ((output.type === "text" || output.type === "error-text") && typeof output.value === "string") {
19
+ return { ...output, value: masker.text(output.value) };
20
+ }
21
+ if (output.type === "json" || output.type === "error-json")
22
+ return { ...output, value: masker.obj(output.value) };
23
+ if (output.type === "content" && Array.isArray(output.value)) {
24
+ return { ...output, value: output.value.map((item) => (item?.type === "text" ? { ...item, text: masker.text(item.text) } : item)) };
25
+ }
26
+ return output;
27
+ }
28
+ function maskPart(part, masker) {
29
+ if (!part || typeof part !== "object")
30
+ return part;
31
+ switch (part.type) {
32
+ case "text":
33
+ return { ...part, text: masker.text(part.text) };
34
+ case "tool-call":
35
+ if ("input" in part)
36
+ return { ...part, input: typeof part.input === "string" ? masker.jsonString(part.input) : masker.obj(part.input) };
37
+ if ("args" in part)
38
+ return { ...part, args: typeof part.args === "string" ? masker.jsonString(part.args) : masker.obj(part.args) };
39
+ return part;
40
+ case "tool-result":
41
+ if ("output" in part)
42
+ return { ...part, output: maskToolOutput(part.output, masker) };
43
+ if ("result" in part)
44
+ return { ...part, result: masker.obj(part.result) };
45
+ return part;
46
+ default:
47
+ return part; // reasoning, arquivos e imagens não mudam
48
+ }
49
+ }
50
+ export function maskPrompt(prompt, masker) {
51
+ return prompt.map((message) => {
52
+ if (message.role === "system")
53
+ return { ...message, content: masker.text(message.content) };
54
+ if (typeof message.content === "string")
55
+ return { ...message, content: masker.text(message.content) };
56
+ if (Array.isArray(message.content))
57
+ return { ...message, content: message.content.map((part) => maskPart(part, masker)) };
58
+ return message;
59
+ });
60
+ }
61
+ function addInstruction(prompt) {
62
+ const first = prompt[0];
63
+ if (first?.role === "system" && typeof first.content === "string") {
64
+ return [{ ...first, content: `${first.content}\n\n${INSTRUCTION}` }, ...prompt.slice(1)];
65
+ }
66
+ return [{ role: "system", content: INSTRUCTION }, ...prompt];
67
+ }
68
+ function restoreContent(content, vault) {
69
+ if (!Array.isArray(content))
70
+ return content;
71
+ return content.map((item) => {
72
+ if (item?.type === "text" && typeof item.text === "string")
73
+ return { ...item, text: vault.restore(item.text) };
74
+ if (item?.type === "tool-call" && typeof item.input === "string")
75
+ return { ...item, input: restoreJsonString(item.input, vault) };
76
+ return item;
77
+ });
78
+ }
79
+ export function veuMiddleware(options = {}) {
80
+ const veu = options.session?.veu ?? options.veu ?? new Veu();
81
+ const block = new Set(options.block ?? veu.options.block ?? []);
82
+ const instruct = options.instructModel ?? veu.options.instructModel ?? true;
83
+ const vaults = new WeakMap();
84
+ const version = options.version ?? "v4";
85
+ return {
86
+ specificationVersion: version,
87
+ ...(version === "v2" ? { middlewareVersion: "v2" } : {}),
88
+ async transformParams({ params }) {
89
+ const vault = options.session?.vault ?? veu.newVault();
90
+ const masker = new Masker(veu.anonymizer, vault);
91
+ let prompt = maskPrompt(params.prompt ?? [], masker);
92
+ const labels = Object.keys(masker.counts);
93
+ const blocked = labels.filter((label) => block.has(label)).sort();
94
+ if (blocked.length)
95
+ throw new BlockedError(blocked);
96
+ if (instruct && labels.length && vault.hasPlaceholders)
97
+ prompt = addInstruction(prompt);
98
+ if (labels.length)
99
+ options.onMask?.({ url: "ai-sdk", counts: { ...masker.counts } });
100
+ const transformed = { ...params, prompt };
101
+ vaults.set(transformed, vault);
102
+ return transformed;
103
+ },
104
+ async wrapGenerate({ doGenerate, params }) {
105
+ const result = await doGenerate();
106
+ const vault = vaults.get(params);
107
+ if (!vault?.size)
108
+ return result;
109
+ const restored = { ...result, content: restoreContent(result.content, vault) };
110
+ if (typeof result.text === "string")
111
+ restored.text = vault.restore(result.text);
112
+ return restored;
113
+ },
114
+ async wrapStream({ doStream, params }) {
115
+ const result = await doStream();
116
+ const vault = vaults.get(params);
117
+ if (!vault?.size)
118
+ return result;
119
+ return { ...result, stream: result.stream.pipeThrough(restoreStreamParts(vault)) };
120
+ },
121
+ };
122
+ }
123
+ /** Restaura as partes de um stream do AI SDK; um marcador cortado entre partes espera a próxima. */
124
+ export function restoreStreamParts(vault) {
125
+ const restorers = new Map();
126
+ const feed = (key, part, text, json = false) => {
127
+ let entry = restorers.get(key);
128
+ if (!entry) {
129
+ entry = { restorer: vault.restorer(json), part };
130
+ restorers.set(key, entry);
131
+ }
132
+ return entry.restorer.feed(text);
133
+ };
134
+ const flushKey = (key, controller) => {
135
+ const entry = restorers.get(key);
136
+ restorers.delete(key);
137
+ const tail = entry?.restorer.flush();
138
+ if (!entry || !tail)
139
+ return;
140
+ const { part } = entry;
141
+ if ("textDelta" in part)
142
+ controller.enqueue({ ...part, textDelta: tail });
143
+ else
144
+ controller.enqueue({ ...part, delta: tail });
145
+ };
146
+ const flushAll = (controller) => {
147
+ for (const key of [...restorers.keys()])
148
+ flushKey(key, controller);
149
+ };
150
+ return new TransformStream({
151
+ transform(part, controller) {
152
+ switch (part?.type) {
153
+ case "text-delta": {
154
+ if (typeof part.delta === "string") {
155
+ const key = `texto:${part.id ?? ""}`;
156
+ controller.enqueue({ ...part, delta: feed(key, part, part.delta) });
157
+ }
158
+ else if (typeof part.textDelta === "string") {
159
+ controller.enqueue({ ...part, textDelta: feed("texto", part, part.textDelta) });
160
+ }
161
+ else {
162
+ controller.enqueue(part);
163
+ }
164
+ return;
165
+ }
166
+ case "tool-input-delta":
167
+ controller.enqueue({ ...part, delta: feed(`ferramenta:${part.id ?? ""}`, part, part.delta ?? "", true) });
168
+ return;
169
+ case "text-end":
170
+ flushKey(`texto:${part.id ?? ""}`, controller);
171
+ controller.enqueue(part);
172
+ return;
173
+ case "tool-input-end":
174
+ flushKey(`ferramenta:${part.id ?? ""}`, controller);
175
+ controller.enqueue(part);
176
+ return;
177
+ case "tool-call":
178
+ if (typeof part.input === "string")
179
+ controller.enqueue({ ...part, input: restoreJsonString(part.input, vault) });
180
+ else if (typeof part.args === "string")
181
+ controller.enqueue({ ...part, args: restoreJsonString(part.args, vault) });
182
+ else
183
+ controller.enqueue(part);
184
+ return;
185
+ case "finish":
186
+ flushAll(controller);
187
+ controller.enqueue(part);
188
+ return;
189
+ default:
190
+ controller.enqueue(part);
191
+ }
192
+ },
193
+ flush(controller) {
194
+ flushAll(controller);
195
+ },
196
+ });
197
+ }
@@ -0,0 +1,25 @@
1
+ import { Session, Veu } from "../index.ts";
2
+ export interface MaskInfo {
3
+ url: string;
4
+ counts: Record<string, number>;
5
+ }
6
+ export interface CreateFetchOptions {
7
+ /** Instância configurada do Véu (padrão: configuração padrão). */
8
+ veu?: Veu;
9
+ /** fetch usado de verdade (padrão: o fetch global). */
10
+ fetch?: typeof globalThis.fetch;
11
+ /** Sessão com um cofre compartilhado: o mesmo CPF vira o mesmo marcador em todas as chamadas. */
12
+ session?: Session;
13
+ /** Tipos que fazem a requisição ser recusada em vez de escondida (ex.: ["CHAVE_PRIVADA"]). */
14
+ block?: string[];
15
+ /** Avisa o modelo para repetir os marcadores (padrão: true). */
16
+ instructModel?: boolean;
17
+ /** Chamado a cada requisição com dados escondidos (só contagens, nunca os valores). */
18
+ onMask?: (info: MaskInfo) => void;
19
+ }
20
+ export declare class BlockedError extends Error {
21
+ readonly labels: string[];
22
+ constructor(labels: string[]);
23
+ }
24
+ /** Cria um fetch que protege as chamadas a APIs de IA e repassa as outras sem mudar nada. */
25
+ export declare function createFetch(options?: CreateFetchOptions): typeof globalThis.fetch;
@@ -0,0 +1,99 @@
1
+ // fetch protegido: esconde os dados antes de a requisição sair e restaura a resposta, sem proxy.
2
+ //
3
+ // import OpenAI from "openai";
4
+ // import { createFetch } from "@guhttps/veu/fetch";
5
+ // const client = new OpenAI({ fetch: createFetch() });
6
+ //
7
+ // Funciona com qualquer SDK ou código que aceite um fetch próprio (OpenAI, Anthropic, Ollama, APIs compatíveis).
8
+ import { INSTRUCTION, Masker, detectAdapter, isStreaming, restoreObj, streamTransformer } from "../gateway.js";
9
+ import { Session, Veu } from "../index.js";
10
+ export class BlockedError extends Error {
11
+ labels;
12
+ constructor(labels) {
13
+ super(`Requisição bloqueada pelo Véu: contém dados que a política não permite enviar (${labels.join(", ")}).`);
14
+ this.labels = labels;
15
+ }
16
+ }
17
+ const DROP_RESPONSE_HEADERS = ["content-length", "content-encoding", "transfer-encoding"];
18
+ function responseHeaders(source) {
19
+ const headers = new Headers(source);
20
+ for (const name of DROP_RESPONSE_HEADERS)
21
+ headers.delete(name);
22
+ return headers;
23
+ }
24
+ /** Cria um fetch que protege as chamadas a APIs de IA e repassa as outras sem mudar nada. */
25
+ export function createFetch(options = {}) {
26
+ const veu = options.session?.veu ?? options.veu ?? new Veu();
27
+ const base = options.fetch ?? globalThis.fetch.bind(globalThis);
28
+ const block = new Set(options.block ?? veu.options.block ?? []);
29
+ const instruct = options.instructModel ?? veu.options.instructModel ?? true;
30
+ return async function veuFetch(input, init) {
31
+ // Decide pela URL e pelo método antes de tocar no corpo: criar um Request consumiria o corpo original.
32
+ const rawUrl = input instanceof Request ? input.url : String(input);
33
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
34
+ const adapter = detectAdapter(method, new URL(rawUrl, "http://localhost").pathname);
35
+ if (!adapter)
36
+ return base(input, init);
37
+ const request = new Request(input, init);
38
+ const url = new URL(request.url);
39
+ const raw = await request.text();
40
+ let payload;
41
+ try {
42
+ payload = JSON.parse(raw || "{}");
43
+ }
44
+ catch {
45
+ return base(request.url, { method: request.method, headers: request.headers, body: raw, signal: request.signal });
46
+ }
47
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
48
+ return base(request.url, { method: request.method, headers: request.headers, body: raw, signal: request.signal });
49
+ }
50
+ const vault = options.session?.vault ?? veu.newVault();
51
+ const masker = new Masker(veu.anonymizer, vault);
52
+ adapter.mask(payload, masker);
53
+ const blocked = Object.keys(masker.counts).filter((label) => block.has(label)).sort();
54
+ if (blocked.length) {
55
+ const message = new BlockedError(blocked).message;
56
+ return new Response(JSON.stringify(adapter.errorBody(message)), {
57
+ status: 400, headers: { "content-type": "application/json", "x-veu-bloqueado": blocked.join(",") },
58
+ });
59
+ }
60
+ if (instruct && Object.keys(masker.counts).length && vault.hasPlaceholders)
61
+ adapter.instruct(payload, INSTRUCTION);
62
+ if (Object.keys(masker.counts).length)
63
+ options.onMask?.({ url: `${url.origin}${url.pathname}`, counts: { ...masker.counts } });
64
+ const headers = new Headers(request.headers);
65
+ headers.delete("content-length");
66
+ const response = await base(request.url, {
67
+ method: request.method, headers, body: JSON.stringify(payload), signal: request.signal,
68
+ });
69
+ if (!adapter.restoresOutput || !vault.size || !response.body)
70
+ return response;
71
+ const contentType = response.headers.get("content-type") ?? "";
72
+ if (isStreaming(contentType)) {
73
+ const transformer = streamTransformer(adapter, vault, contentType);
74
+ const encoder = new TextEncoder();
75
+ const body = response.body.pipeThrough(new TransformStream({
76
+ transform(chunk, controller) {
77
+ const output = transformer.feed(chunk);
78
+ if (output)
79
+ controller.enqueue(encoder.encode(output));
80
+ },
81
+ flush(controller) {
82
+ const output = transformer.close();
83
+ if (output)
84
+ controller.enqueue(encoder.encode(output));
85
+ },
86
+ }));
87
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: responseHeaders(response.headers) });
88
+ }
89
+ const text = await response.text();
90
+ let restored;
91
+ try {
92
+ restored = JSON.stringify(restoreObj(JSON.parse(text), vault));
93
+ }
94
+ catch {
95
+ restored = vault.restore(text);
96
+ }
97
+ return new Response(restored, { status: response.status, statusText: response.statusText, headers: responseHeaders(response.headers) });
98
+ };
99
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./index.ts";
2
+ export { restoreObj, detectAdapter, Masker, INSTRUCTION } from "./gateway.ts";
3
+ export { createFetch } from "./integrations/fetch.ts";
@@ -0,0 +1,4 @@
1
+ // Ponto de entrada do pacote para o navegador (dist/veu.global.js expõe window.veu).
2
+ export * from "./index.js";
3
+ export { restoreObj, detectAdapter, Masker, INSTRUCTION } from "./gateway.js";
4
+ export { createFetch } from "./integrations/fetch.js";
@@ -0,0 +1,43 @@
1
+ import type { Candidate, Recognizer } from "./entities.ts";
2
+ /** Pontuação conforme o valor é válido e há contexto por perto. null descarta o candidato. */
3
+ export interface Scores {
4
+ valid: number | null;
5
+ invalid?: number | null;
6
+ validContext?: number | null;
7
+ invalidContext?: number | null;
8
+ }
9
+ export declare function pickScore(scores: Scores, isValid: boolean, hasContext: boolean): number | null;
10
+ export interface PatternSpec {
11
+ label: string;
12
+ regex: RegExp;
13
+ scores: Scores;
14
+ validator?: (value: string) => boolean;
15
+ context: RegExp | null;
16
+ before: number;
17
+ after: number;
18
+ adjust?: (value: string, score: number) => number | null;
19
+ exclude?: (value: string) => boolean;
20
+ name?: string;
21
+ }
22
+ interface SpecOptions {
23
+ validator?: (value: string) => boolean;
24
+ context?: readonly string[];
25
+ flags?: string;
26
+ before?: number;
27
+ after?: number;
28
+ adjust?: (value: string, score: number) => number | null;
29
+ exclude?: (value: string) => boolean;
30
+ name?: string;
31
+ }
32
+ export declare function spec(label: string, pattern: string, scores: Scores, options?: SpecOptions): PatternSpec;
33
+ export declare const DEFAULT_SPECS: PatternSpec[];
34
+ export declare class PatternRecognizer implements Recognizer {
35
+ name: string;
36
+ specs: PatternSpec[];
37
+ labels: ReadonlySet<string>;
38
+ constructor(specs?: PatternSpec[]);
39
+ find(text: string): Iterable<Candidate>;
40
+ }
41
+ /** Padrão definido pelo usuário. requiresContext: só conta com uma das palavras de contexto por perto. */
42
+ export declare function customPattern(label: string, pattern: string, score?: number, context?: readonly string[], requiresContext?: boolean): PatternSpec;
43
+ export {};