anonyma 1.0.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.
@@ -0,0 +1,772 @@
1
+ import { A as AnonymizeOptions, a as AnonymizeResult, F as FieldRuleMap, c as AnonymizerConfig, d as Anonymizer, P as PiiCategory, D as Detector, e as PiiMatch, f as DetokenizeResult, T as TokenizeOptions, b as TokenizeResult, B as BatchResult, C as CompliancePreset, S as StrategyOptions, g as AnonymizationRule, M as MaskOptions, R as RedactOptions, h as PseudonymizeOptions, H as HashOptions, G as GeneralizeOptions, i as SynthesizeOptions } from './types-D-9HzVuy.js';
2
+ export { j as AnonymaPlugin, k as CustomPattern, l as DetectorRegistry, E as EncryptOptions, m as FieldRule, L as Locale, n as StrategyName, o as TokenFormat, V as ValidatorFunction } from './types-D-9HzVuy.js';
3
+ export { decrypt, encrypt } from './crypto.js';
4
+
5
+ /**
6
+ * @module anonymize
7
+ * @description Core anonymization engine — detects PII and applies strategies.
8
+ */
9
+
10
+ /**
11
+ * Detect all PII in `text` using the built-in detectors.
12
+ *
13
+ * @param text - The input string to scan.
14
+ * @param categories - Optional subset of categories to check. Defaults to all.
15
+ * @param customDetectors - Optional overrides for built-in detectors.
16
+ * @param aggressive - When `true`, use expanded pattern sets for each detector.
17
+ * @returns A sorted array of non-overlapping {@link PiiMatch} objects.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { detect } from "anonyma";
22
+ *
23
+ * detect("Email: alice@example.com, IP: 192.168.1.1");
24
+ * // [
25
+ * // { category: "email", value: "alice@example.com", start: 7, end: 24, confidence: 0.99 },
26
+ * // { category: "ipv4", value: "192.168.1.1", start: 30, end: 41, confidence: 0.98 },
27
+ * // ]
28
+ * ```
29
+ */
30
+ declare function detect(text: string, categories?: readonly PiiCategory[], customDetectors?: Partial<Record<PiiCategory, Detector>>, aggressive?: boolean): PiiMatch[];
31
+ /**
32
+ * Return `true` if `text` contains any detectable PII, `false` otherwise.
33
+ *
34
+ * Uses an early-exit optimisation — scanning stops after the first match is
35
+ * found. Useful for validation gates and conditional processing pipelines.
36
+ *
37
+ * @param text - The input string to scan.
38
+ * @param categories - Optional subset of categories to check. Defaults to all.
39
+ * @param customDetectors - Optional overrides for built-in detectors.
40
+ * @returns `true` if any PII is detected; `false` otherwise.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { hasPII } from "anonyma";
45
+ *
46
+ * if (hasPII(commentText)) {
47
+ * return { error: "Comment contains personal information." };
48
+ * }
49
+ * ```
50
+ */
51
+ declare function hasPII(text: string, categories?: readonly PiiCategory[], customDetectors?: Partial<Record<PiiCategory, Detector>>): boolean;
52
+ /**
53
+ * Detect and anonymize all PII in `text`.
54
+ *
55
+ * Operates in a single left-to-right pass: detected matches are replaced in
56
+ * reverse order (right-to-left) to preserve correct string offsets.
57
+ *
58
+ * @param text - The input string to anonymize.
59
+ * @param options - Anonymization configuration.
60
+ * @returns An {@link AnonymizeResult} containing the anonymized text and
61
+ * optionally the detected matches.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import { anonymize } from "anonyma";
66
+ *
67
+ * anonymize("Contact alice@example.com or call 555-867-5309.");
68
+ * // { text: "Contact [REDACTED] or call [REDACTED].", matches: [] }
69
+ *
70
+ * // Consistent tokens — same value gets same label
71
+ * anonymize("alice@example.com and alice@example.com again", { consistentTokens: true });
72
+ * // { text: "EMAIL_1 and EMAIL_1 again", matches: [] }
73
+ *
74
+ * // Aggressive mode — catches obfuscated PII
75
+ * anonymize("Email user [at] example [dot] com", { aggressive: true });
76
+ * // { text: "Email [REDACTED]", matches: [] }
77
+ * ```
78
+ */
79
+ declare function anonymize(text: string, options?: AnonymizeOptions): AnonymizeResult;
80
+ /**
81
+ * Asynchronous version of {@link anonymize}. Supports the `hash` strategy
82
+ * (uses true SHA-256 via the Web Crypto API) and future async strategies
83
+ * (`tokenize`, `encrypt`, `synthesize`).
84
+ *
85
+ * Falls back to the synchronous implementation for all other strategies.
86
+ *
87
+ * @param text - The input string to anonymize.
88
+ * @param options - Anonymization configuration. Supports the same options as
89
+ * {@link anonymize} plus `hash` strategy with actual SHA-256 output.
90
+ * @returns A promise that resolves to an {@link AnonymizeResult}.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * import { anonymizeAsync } from "anonyma";
95
+ *
96
+ * const result = await anonymizeAsync("Contact alice@example.com", {
97
+ * defaultStrategy: { strategy: "hash" },
98
+ * });
99
+ * // { text: "Contact <sha256-hex>", matches: [] }
100
+ * ```
101
+ */
102
+ declare function anonymizeAsync(text: string, options?: AnonymizeOptions): Promise<AnonymizeResult>;
103
+ /**
104
+ * Recursively anonymize every string value found in a JSON-serializable object
105
+ * tree. Returns a deep clone — the input is never mutated.
106
+ *
107
+ * Handles:
108
+ * - Plain objects (nested to any depth)
109
+ * - Arrays (including mixed-type arrays)
110
+ * - Primitive values (`null`, `undefined`, numbers, booleans) — passed through unchanged
111
+ * - Circular references — throws {@link ValidationError}
112
+ *
113
+ * @param obj - The root object to anonymize. Must be free of circular references.
114
+ * @param options - Optional anonymization configuration forwarded to `anonymize()`.
115
+ * @returns A new object of the same shape with all string values anonymized.
116
+ *
117
+ * @throws {@link ValidationError} When `obj` contains a circular reference or is not an object.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { anonymizeObject } from "anonyma";
122
+ *
123
+ * const result = anonymizeObject({
124
+ * user: { name: "Alice", email: "alice@example.com" },
125
+ * notes: ["Call 555-867-5309", "No PII here"],
126
+ * });
127
+ * // {
128
+ * // user: { name: "Alice", email: "[REDACTED]" },
129
+ * // notes: ["[REDACTED]", "No PII here"],
130
+ * // }
131
+ * ```
132
+ */
133
+ declare function anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T;
134
+ /**
135
+ * Anonymize specific fields in a plain record using field-level rules.
136
+ * Supports dot-notation paths for nested fields.
137
+ *
138
+ * This function returns a new record — it never mutates the input.
139
+ *
140
+ * @param record - The input record.
141
+ * @param rules - A map of field path → {@link FieldRule}.
142
+ * @returns A new record with the specified fields anonymized.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * import { anonymizeRecord } from "anonyma";
147
+ *
148
+ * anonymizeRecord(
149
+ * { name: "Alice", email: "alice@example.com", age: "27" },
150
+ * {
151
+ * email: { strategy: { strategy: "mask", keepLeading: 1, keepTrailing: 3 } },
152
+ * age: { strategy: { strategy: "generalize" } },
153
+ * }
154
+ * );
155
+ * // { name: "Alice", email: "a***************com", age: "20-29" }
156
+ * ```
157
+ */
158
+ declare function anonymizeRecord<T extends Record<string, unknown>>(record: T, rules: FieldRuleMap): T;
159
+ /**
160
+ * Create a reusable, pre-configured {@link Anonymizer} instance.
161
+ *
162
+ * @param config - Anonymizer configuration.
163
+ * @returns A configured {@link Anonymizer}.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { createAnonymizer } from "anonyma";
168
+ *
169
+ * const anonymizer = createAnonymizer({
170
+ * categories: ["email", "phone"],
171
+ * defaultStrategy: { strategy: "mask", keepLeading: 0, keepTrailing: 4 },
172
+ * });
173
+ *
174
+ * anonymizer.anonymize("Call 555-867-5309 or email alice@example.com");
175
+ * // { text: "Call ****5309 or email **.com", matches: [] }
176
+ *
177
+ * anonymizer.hasPII("No PII here");
178
+ * // false
179
+ *
180
+ * anonymizer.anonymizeObject({ email: "alice@example.com", score: 42 });
181
+ * // { email: "[REDACTED]", score: 42 }
182
+ * ```
183
+ */
184
+ declare function createAnonymizer(config?: AnonymizerConfig): Anonymizer;
185
+
186
+ /**
187
+ * @module tokenize
188
+ * @description High-level reversible tokenization API for anonyma.
189
+ *
190
+ * Unlike `anonymize()` — which is one-way — `tokenize()` replaces PII with
191
+ * opaque tokens that can be restored later via `detokenize()`. This is
192
+ * particularly useful for LLM pipelines where the model receives sanitized
193
+ * text and the output must be un-redacted before delivery.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * import { tokenize, detokenize } from "anonyma";
198
+ *
199
+ * const { text, mapping } = tokenize("Contact alice@example.com");
200
+ * // text: "Contact [EMAIL_0001]"
201
+ * // mapping: Map { "[EMAIL_0001]" => "alice@example.com" }
202
+ *
203
+ * const original = detokenize(text, mapping);
204
+ * // "Contact alice@example.com"
205
+ * ```
206
+ */
207
+
208
+ /**
209
+ * Replace all detected PII in `text` with reversible opaque tokens.
210
+ *
211
+ * The returned `mapping` maps each token back to its original value. Pass it
212
+ * to {@link detokenize} to restore the original text.
213
+ *
214
+ * @param text - The input string.
215
+ * @param options - Tokenization options (categories, format, custom detectors…).
216
+ * @returns A {@link TokenizeResult} containing `text` and `mapping`.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * const { text, mapping } = tokenize(
221
+ * "Email alice@example.com, phone 555-867-5309",
222
+ * { categories: ["email", "phone"], format: "bracket" }
223
+ * );
224
+ * // text: "Email [EMAIL_0001], phone [PHONE_0001]"
225
+ * // mapping: Map { "[EMAIL_0001]" => "alice@example.com", "[PHONE_0001]" => "555-867-5309" }
226
+ * ```
227
+ */
228
+ declare function tokenize(text: string, options?: TokenizeOptions): TokenizeResult;
229
+ /**
230
+ * Async variant of {@link tokenize} — identical behaviour but returns a Promise.
231
+ * Useful for consistency in async pipelines.
232
+ */
233
+ declare function tokenizeAsync(text: string, options?: TokenizeOptions): Promise<TokenizeResult>;
234
+ /**
235
+ * Restore all tokens in `text` using the `mapping` returned by {@link tokenize}.
236
+ *
237
+ * Tokens not present in `mapping` are left unchanged and reported in
238
+ * `unresolved`.
239
+ *
240
+ * @param text - A tokenized string produced by {@link tokenize}.
241
+ * @param mapping - The `mapping` from the matching {@link TokenizeResult}.
242
+ * @returns A {@link DetokenizeResult} with the restored `text` and
243
+ * any `unresolved` tokens.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * const original = detokenize("[EMAIL_0001]", new Map([["[EMAIL_0001]", "alice@example.com"]]));
248
+ * // { text: "alice@example.com", unresolved: [] }
249
+ * ```
250
+ */
251
+ declare function detokenize(text: string, mapping: ReadonlyMap<string, string>): DetokenizeResult;
252
+
253
+ /**
254
+ * @module llm
255
+ * @description Helpers designed for LLM (Large Language Model) pipelines.
256
+ *
257
+ * The pattern is:
258
+ * 1. **Sanitize** user text before sending it to the LLM → all PII replaced with tokens.
259
+ * 2. Send the sanitized text to the LLM.
260
+ * 3. **Restore** the LLM's response by swapping tokens back to original values.
261
+ *
262
+ * Tokens survive typical LLM round-trips because they use a safe character set
263
+ * (`[CATEGORY_NNNN]`) that models rarely re-format.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * import { sanitizeForLLM, restoreFromLLM } from "anonyma";
268
+ *
269
+ * const { text, mapping } = sanitizeForLLM("Send invoice to alice@example.com");
270
+ * // text: "Send invoice to [EMAIL_0001]"
271
+ *
272
+ * const llmResponse = await callLLM(text);
273
+ * // "I have sent the invoice to [EMAIL_0001]."
274
+ *
275
+ * const final = restoreFromLLM(llmResponse, mapping);
276
+ * // "I have sent the invoice to alice@example.com."
277
+ * ```
278
+ */
279
+
280
+ /**
281
+ * Replace all PII in `text` with reversible opaque tokens before passing the
282
+ * text to a language model.
283
+ *
284
+ * This is a thin convenience wrapper around {@link tokenize} with sensible
285
+ * defaults for LLM use-cases:
286
+ * - `format`: `"bracket"` (tokens are `[CATEGORY_NNNN]`)
287
+ * - Aggressive mode off by default (reduces false-positive noise in prompts)
288
+ *
289
+ * @param text - The user-supplied text to sanitize.
290
+ * @param options - Optional overrides for tokenization settings.
291
+ * @returns A {@link TokenizeResult}. Pass `mapping` to {@link restoreFromLLM}.
292
+ */
293
+ declare function sanitizeForLLM(text: string, options?: TokenizeOptions): TokenizeResult;
294
+ /**
295
+ * Replace all tokens in the LLM `response` with their original PII values.
296
+ *
297
+ * Tokens that aren't found in `mapping` are left unchanged (the LLM may have
298
+ * dropped or altered them). Unresolved tokens are reported in the returned
299
+ * `unresolved` array so callers can detect data loss.
300
+ *
301
+ * @param response - The raw response string from the language model.
302
+ * @param mapping - The `mapping` from the corresponding {@link sanitizeForLLM} call.
303
+ * @returns A {@link DetokenizeResult} with the restored text.
304
+ */
305
+ declare function restoreFromLLM(response: string, mapping: ReadonlyMap<string, string>): DetokenizeResult;
306
+
307
+ /**
308
+ * @module batch
309
+ * @description Batch processing utilities for anonymizing or tokenizing large
310
+ * collections of texts in one call.
311
+ *
312
+ * Each item is processed independently — a failure in one item does **not**
313
+ * abort the rest of the batch. Errors are collected per-item and exposed in
314
+ * the returned {@link BatchResult}.
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * import { anonymizeBatch } from "anonyma";
319
+ *
320
+ * const results = anonymizeBatch(["alice@example.com", "192.0.2.1"]);
321
+ * // [
322
+ * // { index: 0, ok: true, value: { text: "[REDACTED]", matches: [] } },
323
+ * // { index: 1, ok: true, value: { text: "[REDACTED]", matches: [] } },
324
+ * // ]
325
+ * ```
326
+ */
327
+
328
+ /**
329
+ * Synchronously anonymize an array of strings.
330
+ *
331
+ * @param texts - The array of input strings.
332
+ * @param options - Anonymization options applied to every item.
333
+ * @returns An array of {@link BatchResult} objects, one per input item.
334
+ */
335
+ declare function anonymizeBatch(texts: readonly string[], options?: AnonymizeOptions): BatchResult<AnonymizeResult>[];
336
+ /**
337
+ * Asynchronously anonymize an array of strings (supports `hash`, `encrypt`,
338
+ * and other async strategies).
339
+ *
340
+ * Items are processed in parallel via `Promise.allSettled`.
341
+ *
342
+ * @param texts - The array of input strings.
343
+ * @param options - Anonymization options applied to every item.
344
+ * @param concurrency - Maximum number of items processed simultaneously.
345
+ * Defaults to unlimited. Pass a number to limit concurrency (useful for
346
+ * large datasets to avoid memory pressure).
347
+ * @returns A promise resolving to an array of {@link BatchResult} objects.
348
+ */
349
+ declare function anonymizeBatchAsync(texts: readonly string[], options?: AnonymizeOptions, concurrency?: number): Promise<BatchResult<AnonymizeResult>[]>;
350
+ /**
351
+ * Tokenize an array of strings, returning a separate token mapping per item.
352
+ *
353
+ * Token counters are **not** shared across items — each item gets fresh
354
+ * sequential tokens starting at `_0001`. If you need a shared mapping across
355
+ * all items, call {@link tokenize} directly in a loop with your own
356
+ * `TokenStore`.
357
+ *
358
+ * @param texts - The array of input strings.
359
+ * @param options - Tokenization options applied to every item.
360
+ * @returns An array of {@link BatchResult} objects containing {@link TokenizeResult}.
361
+ */
362
+ declare function tokenizeBatch(texts: readonly string[], options?: TokenizeOptions): BatchResult<TokenizeResult>[];
363
+ /**
364
+ * Detect PII in an array of strings.
365
+ *
366
+ * @param texts - The array of input strings.
367
+ * @param categories - Optional category filter.
368
+ * @returns An array of {@link BatchResult} objects containing PiiMatch arrays.
369
+ */
370
+ declare function detectBatch(texts: readonly string[], categories?: readonly PiiCategory[]): BatchResult<PiiMatch[]>[];
371
+
372
+ /**
373
+ * @module presets
374
+ * @description Built-in compliance preset configurations for GDPR, HIPAA, CCPA,
375
+ * PCI-DSS, SOX, and FERPA. Import from `"anonyma"` or extend using the
376
+ * `preset` option in {@link AnonymizeOptions}.
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * import { anonymize } from "anonyma";
381
+ *
382
+ * // Apply HIPAA preset — redacts all 18 HIPAA Safe Harbor identifiers
383
+ * anonymize(text, { preset: "hipaa" });
384
+ *
385
+ * // Extend GDPR preset with API key detection
386
+ * anonymize(text, { preset: "gdpr", enabledCategories: { "api-key": true } });
387
+ * ```
388
+ */
389
+
390
+ /**
391
+ * A compliance preset configuration.
392
+ */
393
+ interface PresetConfig {
394
+ /** Display name of the preset. */
395
+ readonly name: CompliancePreset;
396
+ /** Description of what the preset covers. */
397
+ readonly description: string;
398
+ /**
399
+ * PII categories this preset activates.
400
+ * The anonymizer will detect and redact these categories.
401
+ */
402
+ readonly categories: readonly PiiCategory[];
403
+ /**
404
+ * Default strategy applied to all categories in this preset.
405
+ */
406
+ readonly defaultStrategy: StrategyOptions;
407
+ /**
408
+ * Per-category strategy overrides (optional).
409
+ */
410
+ readonly rules?: readonly AnonymizationRule[];
411
+ }
412
+ /** All built-in presets keyed by name. */
413
+ declare const PRESET_REGISTRY: Readonly<Record<CompliancePreset, PresetConfig>>;
414
+ /**
415
+ * Get a compliance preset configuration by name.
416
+ *
417
+ * @param name - The preset name.
418
+ * @returns The {@link PresetConfig} for the named preset.
419
+ * @throws {@link PresetNotFoundError} if the preset name is not recognised.
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * import { getPreset } from "anonyma";
424
+ *
425
+ * const preset = getPreset("hipaa");
426
+ * console.log(preset.categories); // ["name", "address", ...]
427
+ * ```
428
+ */
429
+ declare function getPreset(name: CompliancePreset): PresetConfig;
430
+
431
+ /**
432
+ * @module strategies/mask
433
+ * @description The `mask` anonymization strategy.
434
+ */
435
+
436
+ /**
437
+ * Replace interior characters of `value` with a mask character, optionally
438
+ * keeping a number of leading and/or trailing characters visible.
439
+ *
440
+ * The function is deterministic and pure — given the same inputs it always
441
+ * produces the same output.
442
+ *
443
+ * @param value - The string to mask.
444
+ * @param options - Masking configuration.
445
+ * @returns The masked string.
446
+ *
447
+ * @throws {@link ValidationError} When `keepLeading` or `keepTrailing` is negative.
448
+ * @throws {@link ValidationError} When `maskChar` is not exactly one character.
449
+ *
450
+ * @example
451
+ * ```ts
452
+ * import { mask } from "anonyma";
453
+ *
454
+ * mask("john.doe@example.com");
455
+ * // "********************"
456
+ *
457
+ * mask("john.doe@example.com", { keepLeading: 1, keepTrailing: 4 });
458
+ * // "j***************m" (keeps "j" and ".com")
459
+ *
460
+ * mask("+1 (555) 867-5309", { keepLeading: 0, keepTrailing: 4 });
461
+ * // "*************5309"
462
+ * ```
463
+ */
464
+ declare function mask(value: string, options?: MaskOptions): string;
465
+
466
+ /**
467
+ * @module strategies/redact
468
+ * @description The `redact` anonymization strategy.
469
+ */
470
+
471
+ /**
472
+ * Replace `value` entirely with a redaction label.
473
+ *
474
+ * @param value - The string to redact (validated but not inspected).
475
+ * @param options - Redaction configuration.
476
+ * @returns The redaction label.
477
+ *
478
+ * @throws {@link ValidationError} When `label` is an empty string.
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * import { redact } from "anonyma";
483
+ *
484
+ * redact("john.doe@example.com");
485
+ * // "[REDACTED]"
486
+ *
487
+ * redact("123-45-6789", { label: "[SSN REMOVED]" });
488
+ * // "[SSN REMOVED]"
489
+ * ```
490
+ */
491
+ declare function redact(value: string, options?: RedactOptions): string;
492
+
493
+ /**
494
+ * @module strategies/pseudonymize
495
+ * @description The `pseudonymize` anonymization strategy.
496
+ *
497
+ * Generates a deterministic pseudonym from the input value + an optional seed.
498
+ * The same `(value, seed)` pair always produces the same pseudonym, enabling
499
+ * consistent replacement throughout a dataset without storing a lookup table.
500
+ *
501
+ * When no `seed` is provided, the pseudonym is randomly generated and is NOT
502
+ * deterministic across calls.
503
+ *
504
+ * ⚠️ This strategy is NOT cryptographically secure. For strong irreversibility
505
+ * use the `hash` strategy instead.
506
+ */
507
+
508
+ /**
509
+ * Replace `value` with a deterministic (or random) pseudonym.
510
+ *
511
+ * @param value - The original PII value.
512
+ * @param options - Pseudonymization configuration.
513
+ * @returns A pseudonym string.
514
+ *
515
+ * @throws {@link ValidationError} When `prefix` contains whitespace or control characters.
516
+ *
517
+ * @example
518
+ * ```ts
519
+ * import { pseudonymize } from "anonyma";
520
+ *
521
+ * // Deterministic when a seed is provided:
522
+ * pseudonymize("alice@example.com", { seed: "my-secret" });
523
+ * // "id_3a7f1c2b" (same output every time for this input+seed)
524
+ *
525
+ * // Random when no seed is provided:
526
+ * pseudonymize("alice@example.com");
527
+ * // "id_e9a3f7d1" (different on every call)
528
+ * ```
529
+ */
530
+ declare function pseudonymize(value: string, options?: PseudonymizeOptions): string;
531
+
532
+ /**
533
+ * @module strategies/hash
534
+ * @description The `hash` anonymization strategy using SHA-256 (Web Crypto API).
535
+ *
536
+ * This strategy is one-way and cryptographically strong. Adding an optional
537
+ * `pepper` makes the output specific to your deployment and prevents
538
+ * rainbow-table attacks.
539
+ *
540
+ * ⚠️ Requires Node.js ≥ 18 or an environment that exposes `globalThis.crypto.subtle`.
541
+ */
542
+
543
+ /**
544
+ * Compute a SHA-256 hash of `value`, returning a hex string.
545
+ *
546
+ * @param value - The string to hash.
547
+ * @param options - Hashing configuration.
548
+ * @returns A Promise that resolves to a hex-encoded (possibly truncated) hash.
549
+ *
550
+ * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not available.
551
+ * @throws {@link ValidationError} When `truncate` is not a positive integer ≤ 64.
552
+ *
553
+ * @example
554
+ * ```ts
555
+ * import { hash } from "anonyma";
556
+ *
557
+ * await hash("alice@example.com");
558
+ * // "5f3e4b3a9c1d8f2a" (first 16 hex chars of the SHA-256 digest)
559
+ *
560
+ * await hash("alice@example.com", { truncate: 32, pepper: "my-pepper" });
561
+ * // A 32-character hex string, pepper-salted
562
+ * ```
563
+ */
564
+ declare function hash(value: string, options?: HashOptions): Promise<string>;
565
+
566
+ /**
567
+ * @module strategies/generalize
568
+ * @description The `generalize` anonymization strategy.
569
+ *
570
+ * Replaces a precise value with a coarser, less-identifying representation.
571
+ * Currently supports:
572
+ * - **Numeric generalization**: bucketing a number into a range (e.g. `27` → `"20-29"`)
573
+ * - **String passthrough**: non-numeric strings are returned unchanged.
574
+ */
575
+
576
+ /**
577
+ * Generalize `value` by replacing exact numeric values with a range bucket.
578
+ * Non-numeric strings are returned without modification.
579
+ *
580
+ * @param value - The value to generalize.
581
+ * @param options - Generalization configuration.
582
+ * @returns A generalized string representation.
583
+ *
584
+ * @throws {@link ValidationError} When `bucketSize` is not a positive integer.
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * import { generalize } from "anonyma";
589
+ *
590
+ * generalize("27"); // "20-29"
591
+ * generalize("30"); // "30-39"
592
+ * generalize("72"); // "70-79"
593
+ * generalize("27", { bucketSize: 5 }); // "25-29"
594
+ * generalize("not-a-number"); // "not-a-number" (passthrough)
595
+ * ```
596
+ */
597
+ declare function generalize(value: string, options?: GeneralizeOptions): string;
598
+
599
+ /**
600
+ * @module strategies/synthesize
601
+ * @description The `synthesize` anonymization strategy — replaces PII with
602
+ * structurally valid, format-preserving synthetic data.
603
+ *
604
+ * The generator is **deterministic**: the same `(value, seed)` pair always
605
+ * produces the same synthetic output. This means the same PII value is always
606
+ * replaced with the same synthetic stand-in, which preserves referential
607
+ * integrity across a dataset without retaining any real PII.
608
+ *
609
+ * No external libraries are used. All generators are self-contained.
610
+ */
611
+
612
+ /**
613
+ * Replace `value` with a structurally similar, format-preserving synthetic
614
+ * substitute.
615
+ *
616
+ * @param value - The original PII value to synthesize.
617
+ * @param category - The PII category, used to select the generator.
618
+ * @param options - Synthesis options (`seed` overrides the deterministic default).
619
+ * @returns A synthetic string that mirrors the format of `value`.
620
+ *
621
+ * @example
622
+ * ```ts
623
+ * import { synthesize } from "anonyma/strategies/synthesize";
624
+ *
625
+ * synthesize("alice@example.com", "email");
626
+ * // "bob.smith42@test.org" (deterministic for this input)
627
+ *
628
+ * synthesize("alice@example.com", "email", { seed: "custom-seed" });
629
+ * // deterministic based on value + seed combination
630
+ * ```
631
+ */
632
+ declare function synthesize(value: string, category: string, options?: SynthesizeOptions): string;
633
+
634
+ /**
635
+ * @module errors
636
+ * @description Typed error classes for the anonyma library.
637
+ *
638
+ * All errors extend `AnonymaError` so consumers can use a single `instanceof` check.
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * import { AnonymaError, ValidationError } from "anonyma";
643
+ *
644
+ * try {
645
+ * mask(value, { keepLeading: -1 });
646
+ * } catch (err) {
647
+ * if (err instanceof ValidationError) {
648
+ * console.error("bad input:", err.message, err.field);
649
+ * }
650
+ * }
651
+ * ```
652
+ */
653
+ /**
654
+ * Base class for all errors thrown by the anonyma library.
655
+ * Consumers can use `err instanceof AnonymaError` to narrowly handle library errors.
656
+ */
657
+ declare class AnonymaError extends Error {
658
+ /** Machine-readable error code. */
659
+ readonly code: string;
660
+ constructor(message: string, code: string);
661
+ }
662
+ /**
663
+ * Thrown when a function receives an argument that fails validation.
664
+ *
665
+ * @example
666
+ * ```ts
667
+ * throw new ValidationError("keepLeading", "must be a non-negative integer");
668
+ * ```
669
+ */
670
+ declare class ValidationError extends AnonymaError {
671
+ /** The name of the invalid field or parameter. */
672
+ readonly field: string;
673
+ constructor(field: string, reason: string);
674
+ }
675
+ /**
676
+ * Thrown when an unsupported strategy name is encountered.
677
+ *
678
+ * @example
679
+ * ```ts
680
+ * throw new UnsupportedStrategyError("foobar");
681
+ * ```
682
+ */
683
+ declare class UnsupportedStrategyError extends AnonymaError {
684
+ /** The strategy name that was not recognised. */
685
+ readonly strategy: string;
686
+ constructor(strategy: string);
687
+ }
688
+ /**
689
+ * Thrown when an unknown PII category is referenced in a rule or config.
690
+ *
691
+ * @example
692
+ * ```ts
693
+ * throw new UnknownCategoryError("passport");
694
+ * ```
695
+ */
696
+ declare class UnknownCategoryError extends AnonymaError {
697
+ /** The category name that was not recognised. */
698
+ readonly category: string;
699
+ constructor(category: string);
700
+ }
701
+ /**
702
+ * Thrown when the runtime environment does not support a required Web Crypto API.
703
+ * This is only relevant for the `hash` and `encrypt` strategies.
704
+ */
705
+ declare class CryptoNotAvailableError extends AnonymaError {
706
+ constructor();
707
+ }
708
+ /**
709
+ * Thrown when encryption or decryption fails.
710
+ *
711
+ * @example
712
+ * ```ts
713
+ * throw new EncryptionError("encrypt", originalError);
714
+ * ```
715
+ */
716
+ declare class EncryptionError extends AnonymaError {
717
+ /** The operation that failed (`"encrypt"` or `"decrypt"`). */
718
+ readonly operation: "encrypt" | "decrypt";
719
+ constructor(operation: "encrypt" | "decrypt", cause?: unknown);
720
+ }
721
+ /**
722
+ * Thrown when an unknown compliance preset name is referenced.
723
+ *
724
+ * @example
725
+ * ```ts
726
+ * throw new PresetNotFoundError("unknown-preset");
727
+ * ```
728
+ */
729
+ declare class PresetNotFoundError extends AnonymaError {
730
+ /** The preset name that was not recognised. */
731
+ readonly preset: string;
732
+ constructor(preset: string);
733
+ }
734
+ /**
735
+ * Thrown when an allowlist configuration entry is invalid.
736
+ *
737
+ * @example
738
+ * ```ts
739
+ * throw new AllowlistMatchError("allowlist[0]", "must be a non-empty string");
740
+ * ```
741
+ */
742
+ declare class AllowlistMatchError extends AnonymaError {
743
+ /** The allowlist entry or field that was invalid. */
744
+ readonly field: string;
745
+ constructor(field: string, reason: string);
746
+ }
747
+ /**
748
+ * Thrown when a batch processing operation encounters errors.
749
+ * Contains partial results for items that succeeded.
750
+ *
751
+ * @example
752
+ * ```ts
753
+ * try {
754
+ * anonymizeBatch(texts);
755
+ * } catch (err) {
756
+ * if (err instanceof BatchProcessingError) {
757
+ * console.log(`${err.failed} items failed, ${err.succeeded} succeeded`);
758
+ * }
759
+ * }
760
+ * ```
761
+ */
762
+ declare class BatchProcessingError extends AnonymaError {
763
+ /** Number of items that succeeded. */
764
+ readonly succeeded: number;
765
+ /** Number of items that failed. */
766
+ readonly failed: number;
767
+ /** Total items submitted. */
768
+ readonly total: number;
769
+ constructor(succeeded: number, failed: number, total: number);
770
+ }
771
+
772
+ export { AllowlistMatchError, AnonymaError, AnonymizationRule, AnonymizeOptions, AnonymizeResult, Anonymizer, AnonymizerConfig, BatchProcessingError, BatchResult, CompliancePreset, CryptoNotAvailableError, Detector, DetokenizeResult, EncryptionError, FieldRuleMap, GeneralizeOptions, HashOptions, MaskOptions, PRESET_REGISTRY, PiiCategory, PiiMatch, type PresetConfig, PresetNotFoundError, PseudonymizeOptions, RedactOptions, StrategyOptions, SynthesizeOptions, TokenizeOptions, TokenizeResult, UnknownCategoryError, UnsupportedStrategyError, ValidationError, anonymize, anonymizeAsync, anonymizeBatch, anonymizeBatchAsync, anonymizeObject, anonymizeRecord, createAnonymizer, detect, detectBatch, detokenize, generalize, getPreset, hasPII, hash, mask, pseudonymize, redact, restoreFromLLM, sanitizeForLLM, synthesize, tokenize, tokenizeAsync, tokenizeBatch };