anonyma 1.1.1 → 1.2.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.
Files changed (171) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/README.md +125 -7
  3. package/dist/ai/index.cjs +31 -20
  4. package/dist/ai/index.cjs.map +1 -1
  5. package/dist/ai/index.d.cts +5 -5
  6. package/dist/ai/index.d.ts +5 -5
  7. package/dist/ai/index.js +24 -13
  8. package/dist/ai/index.js.map +1 -1
  9. package/dist/audit/index.cjs +14 -14
  10. package/dist/audit/index.d.cts +2 -2
  11. package/dist/audit/index.d.ts +2 -2
  12. package/dist/audit/index.js +9 -9
  13. package/dist/{chunk-YMLR375Z.js → chunk-264R3VFP.js} +4 -3
  14. package/dist/chunk-264R3VFP.js.map +1 -0
  15. package/dist/{chunk-ISL5B4LU.cjs → chunk-32U3DM7M.cjs} +11 -11
  16. package/dist/{chunk-ISL5B4LU.cjs.map → chunk-32U3DM7M.cjs.map} +1 -1
  17. package/dist/{chunk-ZXPZ7W37.cjs → chunk-42ZZZUMO.cjs} +231 -60
  18. package/dist/chunk-42ZZZUMO.cjs.map +1 -0
  19. package/dist/chunk-4BYN6GVK.js +213 -0
  20. package/dist/chunk-4BYN6GVK.js.map +1 -0
  21. package/dist/{chunk-JKW36IPT.js → chunk-A2OMTO3L.js} +4 -4
  22. package/dist/{chunk-JKW36IPT.js.map → chunk-A2OMTO3L.js.map} +1 -1
  23. package/dist/{chunk-TW7PM3UJ.cjs → chunk-AITKBKQX.cjs} +2 -2
  24. package/dist/{chunk-TW7PM3UJ.cjs.map → chunk-AITKBKQX.cjs.map} +1 -1
  25. package/dist/{chunk-G4AN7FND.js → chunk-BWE4O2ES.js} +23 -9
  26. package/dist/chunk-BWE4O2ES.js.map +1 -0
  27. package/dist/{chunk-GS3FRH4K.js → chunk-CMJXIEBA.js} +2 -2
  28. package/dist/chunk-CMJXIEBA.js.map +1 -0
  29. package/dist/{chunk-GYMG5OI3.cjs → chunk-ESVFPMG4.cjs} +2 -2
  30. package/dist/{chunk-GYMG5OI3.cjs.map → chunk-ESVFPMG4.cjs.map} +1 -1
  31. package/dist/{chunk-2YG7R4KJ.cjs → chunk-EUNLKSYP.cjs} +5 -5
  32. package/dist/{chunk-2YG7R4KJ.cjs.map → chunk-EUNLKSYP.cjs.map} +1 -1
  33. package/dist/{chunk-S7NH6CHY.cjs → chunk-F3BYJFUM.cjs} +5 -3
  34. package/dist/chunk-F3BYJFUM.cjs.map +1 -0
  35. package/dist/{chunk-IJAMLYOT.cjs → chunk-HDHQXVUM.cjs} +50 -36
  36. package/dist/chunk-HDHQXVUM.cjs.map +1 -0
  37. package/dist/{chunk-OGNLB2KA.js → chunk-HFAIBE3T.js} +3 -3
  38. package/dist/{chunk-OGNLB2KA.js.map → chunk-HFAIBE3T.js.map} +1 -1
  39. package/dist/{chunk-PKHZ7CVI.js → chunk-IBDFBUFZ.js} +2 -2
  40. package/dist/chunk-IBDFBUFZ.js.map +1 -0
  41. package/dist/{chunk-3CY6ATKS.cjs → chunk-JBH2EFFF.cjs} +36 -36
  42. package/dist/{chunk-3CY6ATKS.cjs.map → chunk-JBH2EFFF.cjs.map} +1 -1
  43. package/dist/chunk-JPU7KQZX.cjs +82 -0
  44. package/dist/{chunk-CRXRJZEV.cjs.map → chunk-JPU7KQZX.cjs.map} +1 -1
  45. package/dist/{chunk-E3PICZYI.js → chunk-KHT23UVV.js} +3 -3
  46. package/dist/{chunk-E3PICZYI.js.map → chunk-KHT23UVV.js.map} +1 -1
  47. package/dist/{chunk-2ZZHLCEJ.js → chunk-LAZIR73I.js} +18 -87
  48. package/dist/chunk-LAZIR73I.js.map +1 -0
  49. package/dist/{chunk-FB56NAAH.cjs → chunk-NO4ZCIM6.cjs} +19 -92
  50. package/dist/chunk-NO4ZCIM6.cjs.map +1 -0
  51. package/dist/{chunk-S4BJ2ADB.cjs → chunk-PCU6AG7H.cjs} +4 -4
  52. package/dist/{chunk-S4BJ2ADB.cjs.map → chunk-PCU6AG7H.cjs.map} +1 -1
  53. package/dist/{chunk-GBYHQQUY.js → chunk-PSZHBY5V.js} +221 -50
  54. package/dist/chunk-PSZHBY5V.js.map +1 -0
  55. package/dist/{chunk-6LDAIJBL.js → chunk-QBBJR7DZ.js} +2 -2
  56. package/dist/{chunk-6LDAIJBL.js.map → chunk-QBBJR7DZ.js.map} +1 -1
  57. package/dist/{chunk-3D5ZCJ7R.js → chunk-QHQ2AU45.js} +3 -3
  58. package/dist/{chunk-3D5ZCJ7R.js.map → chunk-QHQ2AU45.js.map} +1 -1
  59. package/dist/{chunk-IHEIYZPL.cjs → chunk-RJX27YEX.cjs} +2 -2
  60. package/dist/chunk-RJX27YEX.cjs.map +1 -0
  61. package/dist/{chunk-QYD4F6T7.cjs → chunk-ROXNQKOA.cjs} +2 -2
  62. package/dist/{chunk-QYD4F6T7.cjs.map → chunk-ROXNQKOA.cjs.map} +1 -1
  63. package/dist/chunk-SHEXFU6T.js +107 -0
  64. package/dist/chunk-SHEXFU6T.js.map +1 -0
  65. package/dist/chunk-T2KIN6VL.cjs +218 -0
  66. package/dist/chunk-T2KIN6VL.cjs.map +1 -0
  67. package/dist/{chunk-RCW5IPPR.js → chunk-UCT6HDUD.js} +3 -3
  68. package/dist/{chunk-RCW5IPPR.js.map → chunk-UCT6HDUD.js.map} +1 -1
  69. package/dist/chunk-UN74SYHV.cjs +115 -0
  70. package/dist/chunk-UN74SYHV.cjs.map +1 -0
  71. package/dist/{chunk-F7O2FA3F.cjs → chunk-VAO3Y3HZ.cjs} +7 -6
  72. package/dist/chunk-VAO3Y3HZ.cjs.map +1 -0
  73. package/dist/{chunk-BBJPQPGP.js → chunk-VE3OSDM7.js} +5 -3
  74. package/dist/chunk-VE3OSDM7.js.map +1 -0
  75. package/dist/{chunk-7HK2V5Q4.js → chunk-X7IVXKDE.js} +3 -3
  76. package/dist/{chunk-7HK2V5Q4.js.map → chunk-X7IVXKDE.js.map} +1 -1
  77. package/dist/{chunk-UA3EOFBS.cjs → chunk-XVCVIUZS.cjs} +8 -8
  78. package/dist/{chunk-UA3EOFBS.cjs.map → chunk-XVCVIUZS.cjs.map} +1 -1
  79. package/dist/{chunk-SIHPDZXA.js → chunk-YSTC7WRF.js} +2 -2
  80. package/dist/{chunk-SIHPDZXA.js.map → chunk-YSTC7WRF.js.map} +1 -1
  81. package/dist/compliance/index.cjs +15 -15
  82. package/dist/compliance/index.d.cts +4 -4
  83. package/dist/compliance/index.d.ts +4 -4
  84. package/dist/compliance/index.js +5 -5
  85. package/dist/crypto.cjs +4 -4
  86. package/dist/crypto.d.cts +1 -1
  87. package/dist/crypto.d.ts +1 -1
  88. package/dist/crypto.js +2 -2
  89. package/dist/detectors/index.cjs +38 -38
  90. package/dist/detectors/index.d.cts +1 -1
  91. package/dist/detectors/index.d.ts +1 -1
  92. package/dist/detectors/index.js +3 -3
  93. package/dist/engine/index.cjs +70 -70
  94. package/dist/engine/index.d.cts +3 -3
  95. package/dist/engine/index.d.ts +3 -3
  96. package/dist/engine/index.js +8 -8
  97. package/dist/hash-P2VGKVFP.cjs +14 -0
  98. package/dist/{hash-2PSYNDMM.cjs.map → hash-P2VGKVFP.cjs.map} +1 -1
  99. package/dist/hash-T6YJG3DU.js +5 -0
  100. package/dist/{hash-CELLDNKN.js.map → hash-T6YJG3DU.js.map} +1 -1
  101. package/dist/index.cjs +44 -34
  102. package/dist/index.cjs.map +1 -1
  103. package/dist/index.d.cts +23 -5
  104. package/dist/index.d.ts +23 -5
  105. package/dist/index.js +11 -9
  106. package/dist/index.js.map +1 -1
  107. package/dist/{json-CvKtPL8l.d.cts → json-BXN577tt.d.cts} +3 -2
  108. package/dist/{json-BruY_-tV.d.ts → json-BudrzkOQ.d.ts} +3 -2
  109. package/dist/mcp/index.cjs +29 -28
  110. package/dist/mcp/index.cjs.map +1 -1
  111. package/dist/mcp/index.js +14 -13
  112. package/dist/mcp/index.js.map +1 -1
  113. package/dist/middleware/express.cjs +11 -11
  114. package/dist/middleware/express.d.cts +3 -3
  115. package/dist/middleware/express.d.ts +3 -3
  116. package/dist/middleware/express.js +10 -10
  117. package/dist/middleware/hono.cjs +11 -11
  118. package/dist/middleware/hono.d.cts +3 -3
  119. package/dist/middleware/hono.d.ts +3 -3
  120. package/dist/middleware/hono.js +10 -10
  121. package/dist/middleware/index.cjs +11 -11
  122. package/dist/middleware/index.d.cts +3 -3
  123. package/dist/middleware/index.d.ts +3 -3
  124. package/dist/middleware/index.js +10 -10
  125. package/dist/schemas.cjs +47 -47
  126. package/dist/schemas.cjs.map +1 -1
  127. package/dist/schemas.d.cts +2 -2
  128. package/dist/schemas.d.ts +2 -2
  129. package/dist/schemas.js +2 -2
  130. package/dist/schemas.js.map +1 -1
  131. package/dist/{session-CEFGgjFV.d.ts → session-CPXEQ2uC.d.cts} +18 -5
  132. package/dist/{session-DEQrPea7.d.cts → session-D3WMN6fE.d.ts} +18 -5
  133. package/dist/stream.cjs +10 -8
  134. package/dist/stream.cjs.map +1 -1
  135. package/dist/stream.d.cts +1 -1
  136. package/dist/stream.d.ts +1 -1
  137. package/dist/stream.js +7 -5
  138. package/dist/stream.js.map +1 -1
  139. package/dist/{types-oxllMFYF.d.ts → types-B3VjDuP8.d.cts} +2 -282
  140. package/dist/{types-D5BeXwnX.d.ts → types-DHAVKfzT.d.ts} +2 -2
  141. package/dist/types-LZHFEgx5.d.cts +1083 -0
  142. package/dist/types-LZHFEgx5.d.ts +1083 -0
  143. package/dist/{types-BtvX8QTd.d.cts → types-vmONSbz4.d.cts} +2 -2
  144. package/dist/{types-BL5UWH0y.d.cts → types-yZHnS7yv.d.ts} +2 -282
  145. package/dist/validators.cjs +10 -10
  146. package/dist/validators.js +1 -1
  147. package/dist/vault/index.cjs +65 -46
  148. package/dist/vault/index.cjs.map +1 -1
  149. package/dist/vault/index.d.cts +98 -5
  150. package/dist/vault/index.d.ts +98 -5
  151. package/dist/vault/index.js +11 -5
  152. package/dist/vault/index.js.map +1 -1
  153. package/package.json +16 -7
  154. package/dist/chunk-2ZZHLCEJ.js.map +0 -1
  155. package/dist/chunk-BBJPQPGP.js.map +0 -1
  156. package/dist/chunk-CRXRJZEV.cjs +0 -82
  157. package/dist/chunk-F7O2FA3F.cjs.map +0 -1
  158. package/dist/chunk-FB56NAAH.cjs.map +0 -1
  159. package/dist/chunk-G4AN7FND.js.map +0 -1
  160. package/dist/chunk-GBYHQQUY.js.map +0 -1
  161. package/dist/chunk-GS3FRH4K.js.map +0 -1
  162. package/dist/chunk-IHEIYZPL.cjs.map +0 -1
  163. package/dist/chunk-IJAMLYOT.cjs.map +0 -1
  164. package/dist/chunk-PKHZ7CVI.js.map +0 -1
  165. package/dist/chunk-S7NH6CHY.cjs.map +0 -1
  166. package/dist/chunk-YMLR375Z.js.map +0 -1
  167. package/dist/chunk-ZXPZ7W37.cjs.map +0 -1
  168. package/dist/hash-2PSYNDMM.cjs +0 -14
  169. package/dist/hash-CELLDNKN.js +0 -5
  170. package/dist/types-cbGVW8cD.d.cts +0 -592
  171. package/dist/types-cbGVW8cD.d.ts +0 -592
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/strategies/tokenize.ts","../src/internal/allowlist.ts","../src/anonymize.ts","../src/tokenize.ts"],"names":["assignToken","result","TOKEN_PREFIX_MAP"],"mappings":";;;;;;AA+BO,SAAS,gBAAA,GAA+B;AAC7C,EAAA,OAAO;AAAA,IACL,MAAA,sBAAY,GAAA,EAAI;AAAA,IAChB,KAAA,sBAAW,GAAA,EAAI;AAAA,IACf,QAAA,sBAAc,GAAA;AAAI,GACpB;AACF;AAgBO,SAAS,YACd,KAAA,EACA,QAAA,EACA,KAAA,EACA,MAAA,EACA,SAAsB,SAAA,EACd;AACR,EAAA,MAAM,WAAW,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,KAAA,CAAM,aAAa,CAAA,CAAA;AACjD,EAAA,MAAM,QAAA,GAAW,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,QAAQ,CAAA;AACzC,EAAA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aAAA;AAAA,IACA,YAAY,MAAA,CAAO;AAAA,GACrB;AACF","file":"chunk-PSZHBY5V.js","sourcesContent":["/**\n * @module strategies/tokenize\n * @description The `tokenize` anonymization strategy — replaces PII with\n * deterministic, reversible tokens that can later be detokenized.\n *\n * Tokens are opaque identifiers (`[CATEGORY_xxxx]` or `<CATEGORY_N>`) that\n * carry no information about the original value but allow lossless recovery\n * when the token map is retained.\n *\n * This module provides low-level building blocks used by the public\n * `tokenize()` / `detokenize()` API in `src/tokenize.ts`.\n */\n\nimport type { TokenFormat } from \"../types.js\";\n\n/**\n * A mutable in-memory token store mapping token→value and value→token.\n * Scoped to a single tokenisation session.\n *\n * @public\n */\nexport interface TokenStore {\n /** Map: token string → original PII value */\n readonly tokens: Map<string, string>;\n /** Map: `\"CATEGORY:normalizedValue\"` → existing token (for dedup) */\n readonly index: Map<string, string>;\n /** Per-category counters for generating sequential token IDs */\n readonly counters: Map<string, number>;\n}\n\n/** Create an empty token store. */\nexport function createTokenStore(): TokenStore {\n return {\n tokens: new Map(),\n index: new Map(),\n counters: new Map(),\n };\n}\n\n/**\n * Produce a new or existing token for `(category, value)`.\n *\n * Tokens are *deduplicated* — the same value in the same category always\n * receives the same token within a session.\n *\n * @param store - The active token store.\n * @param category - The PII category (e.g. `\"email\"`).\n * @param value - The original PII string.\n * @param prefix - Category prefix used in the token label (e.g. `\"EMAIL\"`).\n * @param format - Token format: `\"bracket\"` (`[EMAIL_0001]`), `\"angle\"` (`<EMAIL_1>`) or\n * `\"brace\"` (`{{EMAIL_1}}`).\n * @returns The deterministic token string.\n */\nexport function assignToken(\n store: TokenStore,\n category: string,\n value: string,\n prefix: string,\n format: TokenFormat = \"bracket\",\n): string {\n const indexKey = `${prefix}:${value.toLowerCase()}`;\n const existing = store.index.get(indexKey);\n if (existing !== undefined) return existing;\n\n const count = (store.counters.get(prefix) ?? 0) + 1;\n store.counters.set(prefix, count);\n\n const id = format === \"bracket\" ? String(count).padStart(4, \"0\") : String(count);\n const token =\n format === \"bracket\"\n ? `[${prefix}_${id}]`\n : format === \"brace\"\n ? `{{${prefix}_${id}}}`\n : `<${prefix}_${id}>`;\n\n store.index.set(indexKey, token);\n store.tokens.set(token, value);\n return token;\n}\n\n/**\n * Matches a token of every format `assignToken()` produces: `[PREFIX_NNNN]`,\n * `<PREFIX_N>` and `{{PREFIX_N}}`. A prefix may contain digits (`IPV4`).\n * Every part is bounded, so text that only looks like a token is cheap to reject.\n */\nexport const LEGACY_TOKEN_PATTERN =\n /\\[[A-Z][A-Z0-9_]{0,60}_\\d{1,12}\\]|<[A-Z][A-Z0-9_]{0,60}_\\d{1,12}>|\\{\\{[A-Z][A-Z0-9_]{0,60}_\\d{1,12}\\}\\}/g;\n\n/**\n * Replace a token with its original value. Returns `undefined` when the token\n * is not found in `store`.\n *\n * @param store - The active token store.\n * @param token - The token to resolve.\n */\nexport function resolveToken(store: TokenStore, token: string): string | undefined {\n return store.tokens.get(token);\n}\n\n/**\n * Restore all tokens in `text` using `store`.\n * Tokens that are not found in `store` are left unchanged.\n *\n * @param text - The tokenized text.\n * @param store - The token store from the original tokenization call.\n * @returns The restored text and a list of any unresolved tokens.\n */\nexport function detokenizeText(\n text: string,\n store: TokenStore,\n): { text: string; unresolved: string[] } {\n const unresolved: string[] = [];\n\n const result = text.replace(LEGACY_TOKEN_PATTERN, (token) => {\n const original = store.tokens.get(token);\n if (original !== undefined) return original;\n unresolved.push(token);\n return token;\n });\n\n return { text: result, unresolved };\n}\n","/**\n * @module internal/allowlist\n * @description Allowlist matching of the 1.x functions: the detected values\n * that the caller lists are left untouched.\n * @internal\n */\n\n/**\n * Compile an allowlist into a predicate that tells whether a detected value\n * is allowlisted.\n *\n * A string entry matches a value equal to it, ignoring case unless\n * `caseSensitive` is set; a value that merely contains an entry does not\n * match. A pattern matches a value it finds a match in. Its `g` and `y` flags\n * are dropped, so that no value depends on the values tested before it and\n * the caller's `RegExp` keeps its `lastIndex`.\n *\n * @param entries - Exact values to leave untouched.\n * @param patterns - Patterns of values to leave untouched.\n * @param caseSensitive - Whether entries are compared case-sensitively.\n * @returns A predicate that returns `true` for an allowlisted value.\n * @internal\n */\nexport function compileAllowlist(\n entries: readonly string[],\n patterns: readonly RegExp[],\n caseSensitive: boolean,\n): (value: string) => boolean {\n if (entries.length === 0 && patterns.length === 0) return () => false;\n\n const exact = new Set(entries.map((entry) => (caseSensitive ? entry : entry.toLowerCase())));\n const compiled = patterns.map(\n (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\")),\n );\n\n return (value) =>\n exact.has(caseSensitive ? value : value.toLowerCase()) ||\n compiled.some((pattern) => pattern.test(value));\n}\n","/**\n * @module anonymize\n * @description Core anonymization engine — detects PII and applies strategies.\n */\n\nimport { DETECTOR_REGISTRY, AGGRESSIVE_DETECTOR_REGISTRY } from \"./detectors/index.js\";\nimport { createTokenStore, assignToken as assignTokenFn } from \"./strategies/tokenize.js\";\nimport { mask } from \"./strategies/mask.js\";\nimport { redact } from \"./strategies/redact.js\";\nimport { pseudonymize } from \"./strategies/pseudonymize.js\";\nimport { generalize } from \"./strategies/generalize.js\";\nimport {\n UnsupportedStrategyError,\n UnknownCategoryError,\n ValidationError,\n PresetNotFoundError,\n} from \"./errors.js\";\nimport { getPreset } from \"./presets.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport type {\n AnonymaPlugin,\n AnonymizeOptions,\n AnonymizeResult,\n AnonymizerConfig,\n Anonymizer,\n FieldRuleMap,\n PiiCategory,\n PiiMatch,\n PluginStrategyOptions,\n StrategyFunction,\n StrategyName,\n StrategyOptions,\n Detector,\n CustomPattern,\n TokenizeOptions,\n TokenMatch,\n ValidatorFunction,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** All recognised PII category names. */\nconst ALL_CATEGORIES: readonly PiiCategory[] = [\n \"email\",\n \"phone\",\n \"ssn\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"iban\",\n \"date-of-birth\",\n \"name\",\n \"address\",\n \"passport\",\n \"drivers-license\",\n \"national-id\",\n \"bank-account\",\n \"cryptocurrency\",\n \"tax-id\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"api-key\",\n \"social-media\",\n \"vin\",\n \"license-plate\",\n \"tracking-number\",\n \"case-number\",\n \"company-registration\",\n] as const;\n\n/**\n * Category → token prefix mapping for `consistentTokens` mode.\n * @internal\n */\nconst TOKEN_PREFIX_MAP: Readonly<Record<PiiCategory, string>> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n} as const;\n\n/**\n * Names of the built-in strategies. A plugin cannot register a strategy under\n * one of them.\n *\n * @internal\n */\nconst STRATEGY_NAMES: ReadonlySet<string> = new Set<StrategyName>([\n \"mask\",\n \"redact\",\n \"pseudonymize\",\n \"hash\",\n \"generalize\",\n \"tokenize\",\n \"encrypt\",\n \"synthesize\",\n]);\n\n/**\n * What the plugins of an anonymizer register, checked and merged by\n * {@link resolvePlugins}.\n *\n * @internal\n */\ninterface PluginRegistry {\n /** Detectors by category. */\n readonly detectors: Partial<Record<PiiCategory, Detector>>;\n /** Strategies by name. */\n readonly strategies: ReadonlyMap<string, StrategyFunction>;\n /** Validators by category; a match is kept only when each of them accepts its value. */\n readonly validators: ReadonlyMap<PiiCategory, readonly ValidatorFunction[]>;\n}\n\n/**\n * The registry of the standalone functions, which apply no plugin.\n *\n * @internal\n */\nconst NO_PLUGINS: PluginRegistry = {\n detectors: {},\n strategies: new Map(),\n validators: new Map(),\n};\n\n/**\n * Whether `name` is a built-in PII category.\n *\n * @internal\n */\nfunction isCategory(name: string): name is PiiCategory {\n return (ALL_CATEGORIES as readonly string[]).includes(name);\n}\n\n/**\n * Whether `opts` names a built-in strategy rather than a plugin strategy.\n *\n * @internal\n */\nfunction isBuiltinStrategy(opts: StrategyOptions | PluginStrategyOptions): opts is StrategyOptions {\n return STRATEGY_NAMES.has(opts.strategy);\n}\n\n/**\n * Apply a single strategy synchronously. The `hash` strategy is async but\n * for text-level anonymization we need synchronous replacement. We use\n * pseudonymize as a deterministic fallback for hash in sync contexts.\n *\n * @remarks\n * ⚠️ **`hash` fallback**: When `hash` is used in a synchronous `anonymize()`\n * call, it falls back to a deterministic pseudonym. If true SHA-256 hashing is\n * required, call `hash()` directly (it returns a `Promise<string>`).\n *\n * @internal\n */\nfunction applyStrategySync(value: string, opts: StrategyOptions): string {\n switch (opts.strategy) {\n case \"mask\":\n return mask(value, opts);\n case \"redact\":\n return redact(value, opts);\n case \"pseudonymize\":\n return pseudonymize(value, opts);\n case \"hash\":\n // Hash is async; callers that need true hashing should use hashValue() directly.\n // For the synchronous pipeline we fall back to a deterministic pseudonym.\n // eslint-disable-next-line no-console\n console.warn(\n \"[anonyma] The `hash` strategy is async and cannot be used in the synchronous \" +\n \"`anonymize()` pipeline. Falling back to a deterministic pseudonym. \" +\n \"Use `anonymizeAsync()` or `hash()` for SHA-256 output.\",\n );\n return pseudonymize(value, { seed: opts.pepper ?? \"__hash_fallback__\", prefix: \"hsh_\" });\n case \"generalize\":\n return generalize(value, opts);\n case \"tokenize\":\n case \"encrypt\":\n case \"synthesize\":\n // Neither anonymize() nor anonymizeAsync() applies these strategies: the\n // value is redacted. The span engine applies all of them.\n // eslint-disable-next-line no-console\n console.warn(\n `[anonyma] anonymize() and anonymizeAsync() do not apply the \\`${opts.strategy}\\` ` +\n `strategy; the value is redacted instead. Use a pipeline of \"anonyma/engine\" ` +\n `to apply it.`,\n );\n return redact(value);\n /* v8 ignore start -- applyStrategy() passes built-in strategies only */\n default: {\n // Exhaustiveness check — TypeScript should never reach here.\n const _exhaustive: never = opts;\n throw new UnsupportedStrategyError((_exhaustive as StrategyOptions).strategy);\n }\n /* v8 ignore stop */\n }\n}\n\n/**\n * Apply a built-in strategy with {@link applyStrategySync}, or a strategy that\n * a plugin registers.\n *\n * @throws {@link UnsupportedStrategyError} When neither anonyma nor a plugin\n * provides the strategy.\n * @throws {@link ValidationError} When the plugin strategy returns no string.\n *\n * @internal\n */\nfunction applyStrategy(\n value: string,\n opts: StrategyOptions | PluginStrategyOptions,\n plugins: PluginRegistry,\n): string {\n if (isBuiltinStrategy(opts)) return applyStrategySync(value, opts);\n\n const strategy = plugins.strategies.get(opts.strategy);\n if (strategy === undefined) throw new UnsupportedStrategyError(opts.strategy);\n\n const replacement = strategy(value, opts.options);\n // Checked at runtime because plugins may be plain JavaScript.\n if (typeof replacement !== \"string\") {\n throw new ValidationError(`strategies.${opts.strategy}`, \"must return a string\");\n }\n return replacement;\n}\n\n/**\n * Sort and de-duplicate an array of PII matches by position.\n * When matches overlap, the one with the higher confidence wins.\n *\n * Works on any match-like object that has `start`, `end`, and `confidence`.\n *\n * @internal\n */\nfunction deduplicateMatches<T extends { start: number; end: number; confidence: number }>(\n matches: T[],\n): T[] {\n // Sort by start position; on ties prefer higher confidence.\n const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n\n const result: T[] = [];\n let cursor = 0;\n\n for (const m of sorted) {\n if (m.start >= cursor) {\n result.push(m);\n cursor = m.end;\n }\n }\n\n return result;\n}\n\n/**\n * Get the active detector for a category: a custom override, else a plugin\n * detector, else the built-in one.\n *\n * @internal\n */\nfunction resolveDetector(\n category: PiiCategory,\n customDetectors: Partial<Record<PiiCategory, Detector>> | undefined,\n aggressive: boolean | undefined,\n plugins: PluginRegistry,\n): Detector {\n if (customDetectors?.[category]) return customDetectors[category];\n const pluginDetector = plugins.detectors[category];\n if (pluginDetector) return pluginDetector;\n return aggressive ? AGGRESSIVE_DETECTOR_REGISTRY[category] : DETECTOR_REGISTRY[category];\n}\n\n/**\n * Run the active detector of a category and keep the matches that every\n * plugin validator of the category accepts.\n *\n * @internal\n */\nfunction runDetector(\n text: string,\n category: PiiCategory,\n customDetectors: Partial<Record<PiiCategory, Detector>> | undefined,\n aggressive: boolean | undefined,\n plugins: PluginRegistry,\n): PiiMatch[] {\n const matches = resolveDetector(category, customDetectors, aggressive, plugins)(text);\n const validators = plugins.validators.get(category);\n if (validators === undefined) return matches;\n return matches.filter((match) => validators.every((validate) => validate(match.value)));\n}\n\n/**\n * Internal representation of a custom pattern match used within the\n * anonymization pipeline. Not exposed publicly.\n *\n * @internal\n */\ninterface CustomMatch {\n readonly category: string;\n readonly value: string;\n readonly start: number;\n readonly end: number;\n readonly confidence: number;\n readonly replacement: string;\n}\n\n/**\n * Run custom patterns against `text` and produce CustomMatch objects.\n *\n * @internal\n */\nfunction detectCustomPatterns(\n text: string,\n customPatterns: readonly CustomPattern[],\n): CustomMatch[] {\n const results: CustomMatch[] = [];\n\n for (const cp of customPatterns) {\n if (!(cp.pattern instanceof RegExp)) {\n throw new ValidationError(\"customPatterns[].pattern\", \"must be a RegExp instance\");\n }\n\n // Ensure global flag is set; create a fresh copy to avoid lastIndex mutation.\n const flags = cp.pattern.flags.includes(\"g\") ? cp.pattern.flags : cp.pattern.flags + \"g\";\n const re = new RegExp(cp.pattern.source, flags);\n const category = cp.category ?? \"custom\";\n const confidence = cp.confidence ?? 0.85;\n const label = cp.label ?? \"[REDACTED]\";\n\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n results.push({\n category,\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence,\n replacement: label,\n });\n }\n }\n\n return results;\n}\n\n/**\n * Resolve the list of categories to detect from `AnonymizeOptions`.\n * Handles `rules`, `enabledCategories`, and defaults.\n *\n * @internal\n */\nfunction resolveCategories(\n options: AnonymizeOptions<StrategyOptions | PluginStrategyOptions>,\n): PiiCategory[] {\n const { rules = [], enabledCategories } = options;\n\n if (rules.length > 0) {\n // rules takes priority — only scan the explicitly listed categories.\n return rules.map((r) => r.category);\n }\n\n if (enabledCategories) {\n return ALL_CATEGORIES.filter((cat) => enabledCategories[cat] === true);\n }\n\n return [...ALL_CATEGORIES];\n}\n\n// ---------------------------------------------------------------------------\n// Public: detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect all PII in `text` using the built-in detectors.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @param aggressive - When `true`, use expanded pattern sets for each detector.\n * @returns A sorted array of non-overlapping {@link PiiMatch} objects.\n *\n * @example\n * ```ts\n * import { detect } from \"anonyma\";\n *\n * detect(\"Email: alice@example.com, IP: 192.168.1.1\");\n * // [\n * // { category: \"email\", value: \"alice@example.com\", start: 7, end: 24, confidence: 0.99 },\n * // { category: \"ipv4\", value: \"192.168.1.1\", start: 30, end: 41, confidence: 0.98 },\n * // ]\n * ```\n */\nexport function detect(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): PiiMatch[] {\n return detectWith(text, categories, customDetectors, aggressive, NO_PLUGINS);\n}\n\n/**\n * {@link detect} with the detectors and validators of an anonymizer's plugins.\n *\n * @internal\n */\nfunction detectWith(\n text: string,\n categories: readonly PiiCategory[],\n customDetectors: Partial<Record<PiiCategory, Detector>> | undefined,\n aggressive: boolean | undefined,\n plugins: PluginRegistry,\n): PiiMatch[] {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n const raw: PiiMatch[] = [];\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n raw.push(...runDetector(text, category, customDetectors, aggressive, plugins));\n }\n\n return deduplicateMatches(raw);\n}\n\n// ---------------------------------------------------------------------------\n// Public: hasPII()\n// ---------------------------------------------------------------------------\n\n/**\n * Return `true` if `text` contains any detectable PII, `false` otherwise.\n *\n * Uses an early-exit optimisation — scanning stops after the first match is\n * found. Useful for validation gates and conditional processing pipelines.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @returns `true` if any PII is detected; `false` otherwise.\n *\n * @example\n * ```ts\n * import { hasPII } from \"anonyma\";\n *\n * if (hasPII(commentText)) {\n * return { error: \"Comment contains personal information.\" };\n * }\n * ```\n */\nexport function hasPII(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n): boolean {\n return hasPIIWith(text, categories, customDetectors, NO_PLUGINS);\n}\n\n/**\n * {@link hasPII} with the detectors and validators of an anonymizer's plugins.\n *\n * @internal\n */\nfunction hasPIIWith(\n text: string,\n categories: readonly PiiCategory[],\n customDetectors: Partial<Record<PiiCategory, Detector>> | undefined,\n plugins: PluginRegistry,\n): boolean {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n if (runDetector(text, category, customDetectors, undefined, plugins).length > 0) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymize()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect and anonymize all PII in `text`.\n *\n * Operates in a single left-to-right pass: detected matches are replaced in\n * reverse order (right-to-left) to preserve correct string offsets.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration.\n * @returns An {@link AnonymizeResult} containing the anonymized text and\n * optionally the detected matches.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * anonymize(\"Contact alice@example.com or call 555-867-5309.\");\n * // { text: \"Contact [REDACTED] or call [REDACTED].\", matches: [] }\n *\n * // Consistent tokens — same value gets same label\n * anonymize(\"alice@example.com and alice@example.com again\", { consistentTokens: true });\n * // { text: \"EMAIL_1 and EMAIL_1 again\", matches: [] }\n *\n * // Aggressive mode — catches obfuscated PII\n * anonymize(\"Email user [at] example [dot] com\", { aggressive: true });\n * // { text: \"Email [REDACTED]\", matches: [] }\n * ```\n */\nexport function anonymize(text: string, options: AnonymizeOptions = {}): AnonymizeResult {\n return anonymizeWith(text, options, NO_PLUGINS);\n}\n\n/**\n * {@link anonymize} with the detectors, strategies and validators of an\n * anonymizer's plugins.\n *\n * @internal\n */\nfunction anonymizeWith(\n text: string,\n options: AnonymizeOptions<StrategyOptions | PluginStrategyOptions>,\n plugins: PluginRegistry,\n): AnonymizeResult {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n if (options.globalReplacement?.trim().length === 0) {\n throw new ValidationError(\"globalReplacement\", \"must not be an empty string\");\n }\n\n // Resolve preset if provided.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n // Build a category → strategy map from the rules array.\n const ruleMap = new Map<PiiCategory, StrategyOptions | PluginStrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) {\n throw new UnknownCategoryError(rule.category);\n }\n ruleMap.set(rule.category, rule.strategy);\n }\n\n // Resolve which categories to scan.\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n // True for a value that must NOT be anonymized even if detected as PII.\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n // Run built-in detectors.\n const builtInMatches = detectWith(text, categories, customDetectors, aggressive, plugins);\n\n // Run custom patterns.\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n // Apply allowlist + confidenceThreshold filtering to built-in matches.\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n // Combine and deduplicate all matches by position.\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n // --- Consistent token state (scoped to this call only) ---\n const tokenMap = new Map<string, string>(); // key: \"category:normalizedValue\" → token\n const tokenCounters = new Map<string, number>(); // key: prefix → counter\n\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n // Apply strategies in reverse order to preserve indices.\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n // Pre-computed replacement from custom pattern.\n replacement = match.replacement;\n } else {\n // Built-in PII match: look up per-category rule or fall back to default.\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n replacement = applyStrategy(match.value, strategy, plugins);\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n // Only include built-in PiiMatch objects in the public result (custom matches\n // have a non-PiiCategory category and are not part of the public API surface).\n const reportedMatches = includeMatches ? filteredBuiltInMatches : [];\n\n return {\n text: result,\n matches: reportedMatches,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Asynchronous version of {@link anonymize}. Supports the `hash` strategy\n * (uses true SHA-256 via the Web Crypto API) and future async strategies\n * (`tokenize`, `encrypt`, `synthesize`).\n *\n * Falls back to the synchronous implementation for all other strategies.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration. Supports the same options as\n * {@link anonymize} plus `hash` strategy with actual SHA-256 output.\n * @returns A promise that resolves to an {@link AnonymizeResult}.\n *\n * @example\n * ```ts\n * import { anonymizeAsync } from \"anonyma\";\n *\n * const result = await anonymizeAsync(\"Contact alice@example.com\", {\n * defaultStrategy: { strategy: \"hash\" },\n * });\n * // { text: \"Contact <sha256-hex>\", matches: [] }\n * ```\n */\nexport async function anonymizeAsync(\n text: string,\n options: AnonymizeOptions = {},\n): Promise<AnonymizeResult> {\n return anonymizeAsyncWith(text, options, NO_PLUGINS);\n}\n\n/**\n * {@link anonymizeAsync} with the detectors, strategies and validators of an\n * anonymizer's plugins.\n *\n * @internal\n */\nasync function anonymizeAsyncWith(\n text: string,\n options: AnonymizeOptions<StrategyOptions | PluginStrategyOptions>,\n plugins: PluginRegistry,\n): Promise<AnonymizeResult> {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n // For strategies that don't involve async primitives, delegate to sync.\n const hasAsyncStrategy = (opts: StrategyOptions | PluginStrategyOptions): boolean =>\n opts.strategy === \"hash\" ||\n opts.strategy === \"encrypt\" ||\n opts.strategy === \"tokenize\" ||\n opts.strategy === \"synthesize\";\n\n const needsAsync =\n (options.defaultStrategy != null && hasAsyncStrategy(options.defaultStrategy)) ||\n (options.rules ?? []).some((r) => hasAsyncStrategy(r.strategy));\n\n if (!needsAsync) {\n return anonymizeWith(text, options, plugins);\n }\n\n // Lazy-import to avoid circular dependency on strategies not yet in the\n // synchronous bundle (hash is async-native, others upcoming).\n const { hash: hashFn } = await import(\"./strategies/hash.js\");\n\n // Resolve identical logic as sync path.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n const ruleMap = new Map<PiiCategory, StrategyOptions | PluginStrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) throw new UnknownCategoryError(rule.category);\n ruleMap.set(rule.category, rule.strategy);\n }\n\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n const builtInMatches = detectWith(text, categories, customDetectors, aggressive, plugins);\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n const tokenMap = new Map<string, string>();\n const tokenCounters = new Map<string, number>();\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n replacement = match.replacement;\n } else {\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n if (isBuiltinStrategy(strategy) && strategy.strategy === \"hash\") {\n replacement = await hashFn(match.value, strategy);\n } else {\n replacement = applyStrategy(match.value, strategy, plugins);\n }\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n return {\n text: result,\n matches: includeMatches ? filteredBuiltInMatches : [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeObject()\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively anonymize every string value found in a JSON-serializable object\n * tree. Returns a deep clone — the input is never mutated.\n *\n * Handles:\n * - Plain objects (nested to any depth)\n * - Arrays (including mixed-type arrays)\n * - Primitive values (`null`, `undefined`, numbers, booleans) — passed through unchanged\n * - Circular references — throws {@link ValidationError}\n *\n * @param obj - The root object to anonymize. Must be free of circular references.\n * @param options - Optional anonymization configuration forwarded to `anonymize()`.\n * @returns A new object of the same shape with all string values anonymized.\n *\n * @throws {@link ValidationError} When `obj` contains a circular reference or is not an object.\n *\n * @example\n * ```ts\n * import { anonymizeObject } from \"anonyma\";\n *\n * const result = anonymizeObject({\n * user: { name: \"Alice\", email: \"alice@example.com\" },\n * notes: [\"Call 555-867-5309\", \"No PII here\"],\n * });\n * // {\n * // user: { name: \"Alice\", email: \"[REDACTED]\" },\n * // notes: [\"[REDACTED]\", \"No PII here\"],\n * // }\n * ```\n */\nexport function anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n return anonymizeObjectWith(obj, options, NO_PLUGINS);\n}\n\n/**\n * {@link anonymizeObject} with the detectors, strategies and validators of an\n * anonymizer's plugins.\n *\n * @internal\n */\nfunction anonymizeObjectWith<T extends object>(\n obj: T,\n options: AnonymizeOptions<StrategyOptions | PluginStrategyOptions> | undefined,\n plugins: PluginRegistry,\n): T {\n if (typeof obj !== \"object\") {\n throw new ValidationError(\"obj\", \"must be an object\");\n }\n return deepAnonymizeValue(obj, options, new WeakSet(), plugins) as T;\n}\n\n/**\n * Recursive implementation for `anonymizeObject`.\n * `seen` tracks visited objects to detect circular references.\n *\n * @internal\n */\nfunction deepAnonymizeValue(\n value: unknown,\n options: AnonymizeOptions<StrategyOptions | PluginStrategyOptions> | undefined,\n seen: WeakSet<object>,\n plugins: PluginRegistry,\n): unknown {\n if (value === null || value === undefined) return value;\n\n if (typeof value === \"string\") {\n return anonymizeWith(value, options ?? {}, plugins).text;\n }\n\n if (typeof value !== \"object\") {\n // numbers, booleans, Symbols, BigInts — pass through unchanged.\n return value;\n }\n\n if (seen.has(value)) {\n throw new ValidationError(\"obj\", \"contains a circular reference\");\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const result = value.map((item) => deepAnonymizeValue(item, options, seen, plugins));\n seen.delete(value as object);\n return result;\n }\n\n // Plain object.\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = deepAnonymizeValue(\n (value as Record<string, unknown>)[key],\n options,\n seen,\n plugins,\n );\n }\n seen.delete(value);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeRecord()\n// ---------------------------------------------------------------------------\n\n/**\n * Safely get a nested value from a plain record using dot-notation path.\n *\n * @internal\n */\nfunction getByPath(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) {\n return undefined;\n }\n // Safe: we check isObject above.\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Safely set a nested value on a plain record using dot-notation path.\n * Returns a new object (shallow clone at each level touched).\n *\n * @internal\n */\nfunction setByPath(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): Record<string, unknown> {\n const parts = path.split(\".\");\n\n if (parts.length === 1) {\n return { ...obj, [path]: value };\n }\n\n const [head, ...tail] = parts as [string, ...string[]];\n // setByPath is only called after getByPath confirmed the path exists, so obj[head] is\n // always defined in practice. The `?? {}` fallback is a defensive guard.\n /* v8 ignore next */\n const nested = (obj[head] ?? {}) as Record<string, unknown>;\n return {\n ...obj,\n [head]: setByPath(nested, tail.join(\".\"), value),\n };\n}\n\n/**\n * Anonymize specific fields in a plain record using field-level rules.\n * Supports dot-notation paths for nested fields.\n *\n * This function returns a new record — it never mutates the input.\n *\n * @param record - The input record.\n * @param rules - A map of field path → {@link FieldRule}.\n * @returns A new record with the specified fields anonymized.\n *\n * @example\n * ```ts\n * import { anonymizeRecord } from \"anonyma\";\n *\n * anonymizeRecord(\n * { name: \"Alice\", email: \"alice@example.com\", age: \"27\" },\n * {\n * email: { strategy: { strategy: \"mask\", keepLeading: 1, keepTrailing: 3 } },\n * age: { strategy: { strategy: \"generalize\" } },\n * }\n * );\n * // { name: \"Alice\", email: \"a***************com\", age: \"20-29\" }\n * ```\n */\nexport function anonymizeRecord<T extends Record<string, unknown>>(\n record: T,\n rules: FieldRuleMap,\n): T {\n return anonymizeRecordWith(record, rules, NO_PLUGINS);\n}\n\n/**\n * {@link anonymizeRecord} with the strategies of an anonymizer's plugins.\n *\n * @internal\n */\nfunction anonymizeRecordWith<T extends Record<string, unknown>>(\n record: T,\n rules: FieldRuleMap<StrategyOptions | PluginStrategyOptions>,\n plugins: PluginRegistry,\n): T {\n if (typeof record !== \"object\" || Array.isArray(record)) {\n throw new ValidationError(\"record\", \"must be a plain object\");\n }\n\n let result: Record<string, unknown> = { ...record };\n\n for (const [path, rule] of Object.entries(rules)) {\n if (Object.prototype.hasOwnProperty.call(rules, path)) {\n const raw = getByPath(result, path);\n if (raw === undefined || raw === null) continue;\n if (typeof raw !== \"string\" && typeof raw !== \"number\" && typeof raw !== \"boolean\") continue;\n\n const strValue = String(raw);\n const anonymized = applyStrategy(strValue, rule.strategy, plugins);\n result = setByPath(result, path, anonymized);\n }\n }\n\n return result as T;\n}\n\n// ---------------------------------------------------------------------------\n// Plugins\n// ---------------------------------------------------------------------------\n\n/**\n * Check the plugins of an anonymizer and merge what they register.\n *\n * @throws {@link ValidationError} When a plugin has no name or the name of\n * another, when two plugins register a detector for the same category or a\n * strategy under the same name, or when a strategy has a built-in name.\n * @throws {@link UnknownCategoryError} When a detector or validator is keyed by\n * a name that is not a category.\n *\n * @internal\n */\nfunction resolvePlugins(plugins: readonly AnonymaPlugin[]): PluginRegistry {\n const names = new Set<string>();\n const detectors: Partial<Record<PiiCategory, Detector>> = {};\n const detectorOwners = new Map<PiiCategory, string>();\n const strategies = new Map<string, StrategyFunction>();\n const strategyOwners = new Map<string, string>();\n const validators = new Map<PiiCategory, ValidatorFunction[]>();\n\n plugins.forEach((plugin, index) => {\n const field = `plugins[${String(index)}]`;\n const { name } = plugin;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new ValidationError(`${field}.name`, \"must be a non-empty string\");\n }\n if (names.has(name)) {\n throw new ValidationError(`${field}.name`, `another plugin is named \"${name}\"`);\n }\n names.add(name);\n\n for (const [category, detector] of Object.entries(plugin.detectors ?? {})) {\n if (!isCategory(category)) throw new UnknownCategoryError(category);\n const owner = detectorOwners.get(category);\n if (owner !== undefined) {\n throw new ValidationError(\n `${field}.detectors.${category}`,\n `plugin \"${owner}\" registers a detector for this category`,\n );\n }\n detectorOwners.set(category, name);\n detectors[category] = detector;\n }\n\n for (const [strategyName, strategy] of Object.entries(plugin.strategies ?? {})) {\n if (STRATEGY_NAMES.has(strategyName)) {\n throw new ValidationError(\n `${field}.strategies.${strategyName}`,\n \"a built-in strategy has this name\",\n );\n }\n const owner = strategyOwners.get(strategyName);\n if (owner !== undefined) {\n throw new ValidationError(\n `${field}.strategies.${strategyName}`,\n `plugin \"${owner}\" registers a strategy with this name`,\n );\n }\n strategyOwners.set(strategyName, name);\n strategies.set(strategyName, strategy);\n }\n\n for (const [category, validator] of Object.entries(plugin.validators ?? {})) {\n if (!isCategory(category)) throw new UnknownCategoryError(category);\n validators.set(category, [...(validators.get(category) ?? []), validator]);\n }\n });\n\n return { detectors, strategies, validators };\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizer()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reusable, pre-configured {@link Anonymizer} instance.\n *\n * The anonymizer applies the detectors, strategies and validators of the\n * `plugins` of its configuration (see {@link AnonymaPlugin}).\n *\n * @param config - Anonymizer configuration.\n * @returns A configured {@link Anonymizer}.\n * @throws {@link UnsupportedStrategyError} When `defaultStrategy` names a\n * strategy that neither anonyma nor one of the plugins provides.\n *\n * @example\n * ```ts\n * import { createAnonymizer } from \"anonyma\";\n *\n * const anonymizer = createAnonymizer({\n * categories: [\"email\", \"phone\"],\n * defaultStrategy: { strategy: \"mask\", keepLeading: 0, keepTrailing: 4 },\n * });\n *\n * anonymizer.anonymize(\"Call 555-867-5309 or email alice@example.com\");\n * // { text: \"Call ****5309 or email **.com\", matches: [] }\n *\n * anonymizer.hasPII(\"No PII here\");\n * // false\n *\n * anonymizer.anonymizeObject({ email: \"alice@example.com\", score: 42 });\n * // { email: \"[REDACTED]\", score: 42 }\n * ```\n */\nexport function createAnonymizer(config: AnonymizerConfig = {}): Anonymizer {\n // Resolve preset first so its defaults can be overridden by explicit config.\n let presetConfig: ReturnType<typeof getPreset> | undefined;\n if (config.preset) {\n try {\n presetConfig = getPreset(config.preset);\n } catch {\n throw new PresetNotFoundError(config.preset);\n }\n }\n\n const {\n categories = presetConfig ? presetConfig.categories : [...ALL_CATEGORIES],\n defaultStrategy = presetConfig?.defaultStrategy ?? { strategy: \"redact\" as const },\n customDetectors,\n customPatterns,\n globalReplacement,\n consistentTokens,\n aggressive,\n plugins = [],\n } = config;\n\n // Validate categories up-front.\n for (const cat of categories) {\n if (!ALL_CATEGORIES.includes(cat)) {\n throw new UnknownCategoryError(cat);\n }\n }\n\n const registry = resolvePlugins(plugins);\n // The types accept any strategy name here, so check it before a value needs it.\n if (!isBuiltinStrategy(defaultStrategy) && !registry.strategies.has(defaultStrategy.strategy)) {\n throw new UnsupportedStrategyError(defaultStrategy.strategy);\n }\n\n /** Shared base options derived from config. */\n function baseOptions(\n overrides?: Partial<AnonymizeOptions<StrategyOptions | PluginStrategyOptions>>,\n ): AnonymizeOptions<StrategyOptions | PluginStrategyOptions> {\n const base: AnonymizeOptions<StrategyOptions | PluginStrategyOptions> = {\n defaultStrategy,\n ...(customDetectors !== undefined ? { customDetectors } : {}),\n ...(customPatterns !== undefined ? { customPatterns } : {}),\n ...(globalReplacement !== undefined ? { globalReplacement } : {}),\n ...(consistentTokens !== undefined ? { consistentTokens } : {}),\n ...(aggressive !== undefined ? { aggressive } : {}),\n ...overrides,\n rules:\n overrides?.rules ??\n (presetConfig\n ? presetConfig.categories.map((category) => ({\n category,\n strategy:\n presetConfig.rules?.find((r) => r.category === category)?.strategy ??\n defaultStrategy,\n }))\n : categories.map((category) => ({\n category,\n strategy: defaultStrategy,\n }))),\n };\n return base;\n }\n\n return {\n anonymize(\n text: string,\n options?: Partial<AnonymizeOptions<StrategyOptions | PluginStrategyOptions>>,\n ): AnonymizeResult {\n return anonymizeWith(text, baseOptions(options), registry);\n },\n\n detect(text: string): PiiMatch[] {\n return detectWith(text, categories, customDetectors, aggressive, registry);\n },\n\n anonymizeRecord<T extends Record<string, unknown>>(\n record: T,\n rules: FieldRuleMap<StrategyOptions | PluginStrategyOptions>,\n ): T {\n return anonymizeRecordWith(record, rules, registry);\n },\n\n anonymizeObject<T extends object>(\n obj: T,\n options?: AnonymizeOptions<StrategyOptions | PluginStrategyOptions>,\n ): T {\n return anonymizeObjectWith(obj, baseOptions(options), registry);\n },\n\n async anonymizeAsync(\n text: string,\n options?: Partial<AnonymizeOptions<StrategyOptions | PluginStrategyOptions>>,\n ): Promise<AnonymizeResult> {\n return anonymizeAsyncWith(text, baseOptions(options), registry);\n },\n\n tokenize(text: string, options?: TokenizeOptions): ReturnType<Anonymizer[\"tokenize\"]> {\n // Inline implementation to avoid circular dependency (tokenize.ts imports detectFn)\n const {\n categories: tCats,\n format = \"bracket\",\n customDetectors: tCustDet,\n aggressive: tAgg = aggressive,\n confidenceThreshold: tConfidence = 0,\n allowlist: tAllowlist = [],\n allowlistCaseSensitive: tCaseSensitive = false,\n } = options ?? {};\n\n const isAllowlisted = compileAllowlist(tAllowlist, [], tCaseSensitive);\n\n const tMatches = detectWith(\n text,\n tCats ?? categories,\n tCustDet ?? customDetectors,\n tAgg,\n registry,\n ).filter((m) => m.confidence >= tConfidence && !isAllowlisted(m.value));\n\n const store = createTokenStore();\n let tResult = text;\n const tTokens: TokenMatch[] = [];\n for (const match of [...tMatches].reverse()) {\n // detect() exclusively returns PiiCategory matches, so the toUpperCase() fallback\n // is unreachable through the public API.\n /* v8 ignore next */\n const prefix = TOKEN_PREFIX_MAP[match.category];\n const token = assignTokenFn(store, match.category, match.value, prefix, format);\n tTokens.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n tResult = tResult.slice(0, match.start) + token + tResult.slice(match.end);\n }\n return { text: tResult, mapping: store.tokens, tokens: tTokens };\n },\n\n hasPII(text: string): boolean {\n return hasPIIWith(text, categories, customDetectors, registry);\n },\n };\n}\n","/**\n * @module tokenize\n * @description High-level reversible tokenization API for anonyma.\n *\n * Unlike `anonymize()` — which is one-way — `tokenize()` replaces PII with\n * opaque tokens that can be restored later via `detokenize()`. This is\n * particularly useful for LLM pipelines where the model receives sanitized\n * text and the output must be un-redacted before delivery.\n *\n * @example\n * ```ts\n * import { tokenize, detokenize } from \"anonyma\";\n *\n * const { text, mapping } = tokenize(\"Contact alice@example.com\");\n * // text: \"Contact [EMAIL_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\" }\n *\n * const original = detokenize(text, mapping);\n * // \"Contact alice@example.com\"\n * ```\n */\n\nimport { detect } from \"./anonymize.js\";\nimport {\n createTokenStore,\n assignToken,\n detokenizeText,\n LEGACY_TOKEN_PATTERN,\n} from \"./strategies/tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport { isThenable } from \"./vault/anonyma-vault.js\";\nimport type { AnonymaVault } from \"./vault/anonyma-vault.js\";\nimport { createVaultTokenizer } from \"./vault/vault-tokenizer.js\";\nimport type { VaultTokenizer } from \"./vault/vault-tokenizer.js\";\nimport type {\n TokenizeResult,\n DetokenizeResult,\n TokenizeOptions,\n TokenMatch,\n TokenFormat,\n PiiMatch,\n} from \"./types.js\";\n\n// Category → token prefix mapping (mirrors TOKEN_PREFIX_MAP in anonymize.ts).\nconst TOKEN_PREFIX_MAP: Record<string, string> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n};\n\n// ---------------------------------------------------------------------------\n// Public: tokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Replace all detected PII in `text` with reversible opaque tokens.\n *\n * The returned `mapping` maps each token back to its original value. Pass it\n * to {@link detokenize} to restore the original text.\n *\n * @param text - The input string.\n * @param options - Tokenization options (categories, format, custom detectors…).\n * @returns A {@link TokenizeResult} containing `text` and `mapping`.\n *\n * @example\n * ```ts\n * const { text, mapping } = tokenize(\n * \"Email alice@example.com, phone 555-867-5309\",\n * { categories: [\"email\", \"phone\"], format: \"bracket\" }\n * );\n * // text: \"Email [EMAIL_0001], phone [PHONE_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\", \"[PHONE_0001]\" => \"555-867-5309\" }\n *\n * // Keep the tokens in a vault, and restore them later from any text:\n * const vault = new InMemoryVault();\n * tokenize(\"Mail john@example.com\", { vault }).text; // \"Mail {{EMAIL_1}}\"\n * restore(\"Sent to {{EMAIL_1}}.\", vault).text; // \"Sent to john@example.com.\"\n * ```\n *\n * @throws {@link ValidationError} When `vault` answers asynchronously; use {@link tokenizeAsync}.\n */\nexport function tokenize(text: string, options: TokenizeOptions = {}): TokenizeResult {\n const matches = detectForTokenize(text, options);\n if (options.vault !== undefined) {\n const tokenizer = vaultTokenizerFor(options.vault, options.format);\n const placed = matches.map((match) => {\n const token = tokenizer.tokenize(match.value, { category: match.category });\n if (isThenable(token)) {\n // The vault is asynchronous; tokenizeAsync() is the entry point for it.\n void token.catch(() => undefined);\n throw new ValidationError(\"vault\", \"answers asynchronously: use tokenizeAsync()\");\n }\n return { match, token };\n });\n return replaceInOrder(text, placed);\n }\n\n const store = createTokenStore();\n let result = text;\n const reversed = [...matches].reverse();\n const tokenMatches: TokenMatch[] = [];\n const format = options.format ?? \"bracket\";\n\n for (const match of reversed) {\n const prefix = TOKEN_PREFIX_MAP[match.category] ?? match.category.toUpperCase();\n const token = assignToken(store, match.category, match.value, prefix, format);\n tokenMatches.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n result = result.slice(0, match.start) + token + result.slice(match.end);\n }\n\n return { text: result, mapping: store.tokens, tokens: tokenMatches };\n}\n\n// ---------------------------------------------------------------------------\n// Public: tokenizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Async variant of {@link tokenize} — identical behaviour but returns a Promise.\n * It is the entry point for an asynchronous `vault` (Redis, a KV store, …).\n *\n * @example\n * ```ts\n * const { text } = await tokenizeAsync(\"Mail john@example.com\", { vault: redisVault });\n * // \"Mail {{EMAIL_1}}\"\n * ```\n */\nexport async function tokenizeAsync(\n text: string,\n options: TokenizeOptions = {},\n): Promise<TokenizeResult> {\n if (options.vault === undefined) return tokenize(text, options);\n const matches = detectForTokenize(text, options);\n const tokenizer = vaultTokenizerFor(options.vault, options.format);\n const placed: Placed[] = [];\n for (const match of matches) {\n placed.push({\n match,\n token: await tokenizer.tokenize(match.value, { category: match.category }),\n });\n }\n return replaceInOrder(text, placed);\n}\n\n/** The detections `tokenize()` replaces, in document order. */\nfunction detectForTokenize(text: string, options: TokenizeOptions): PiiMatch[] {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n const {\n categories,\n customDetectors,\n aggressive = false,\n confidenceThreshold = 0,\n allowlist = [],\n allowlistCaseSensitive = false,\n } = options;\n const isAllowlisted = compileAllowlist(allowlist, [], allowlistCaseSensitive);\n return detect(text, categories, customDetectors, aggressive).filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n}\n\n/** The vault tokenizer for one `tokenize()` call. */\nfunction vaultTokenizerFor(vault: AnonymaVault, format: TokenFormat = \"brace\"): VaultTokenizer {\n return createVaultTokenizer({ vault, format: format === \"custom\" ? \"angle\" : format });\n}\n\n/** A detection and the token that replaces it. */\ninterface Placed {\n readonly match: PiiMatch;\n readonly token: string;\n}\n\n/** Replace each match with its token, in document order. */\nfunction replaceInOrder(text: string, placed: readonly Placed[]): TokenizeResult {\n const parts: string[] = [];\n const mapping = new Map<string, string>();\n const tokenMatches: TokenMatch[] = [];\n let cursor = 0;\n for (const { match, token } of placed) {\n parts.push(text.slice(cursor, match.start), token);\n cursor = match.end;\n if (!mapping.has(token)) mapping.set(token, match.value);\n tokenMatches.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n }\n parts.push(text.slice(cursor));\n return { text: parts.join(\"\"), mapping, tokens: tokenMatches };\n}\n\n// ---------------------------------------------------------------------------\n// Public: detokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Restore all tokens in `text` using the `mapping` returned by {@link tokenize}.\n *\n * Tokens not present in `mapping` are left unchanged and reported in\n * `unresolved`.\n *\n * @param text - A tokenized string produced by {@link tokenize}.\n * @param mapping - The `mapping` from the matching {@link TokenizeResult}.\n * @returns A {@link DetokenizeResult} with the restored `text` and\n * any `unresolved` tokens.\n *\n * @example\n * ```ts\n * const original = detokenize(\"[EMAIL_0001]\", new Map([[\"[EMAIL_0001]\", \"alice@example.com\"]]));\n * // { text: \"alice@example.com\", unresolved: [] }\n * ```\n */\nexport function detokenize(text: string, mapping: ReadonlyMap<string, string>): DetokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n // Build a temporary store from the mapping.\n const store = createTokenStore();\n for (const [token, value] of mapping) {\n store.tokens.set(token, value);\n }\n\n const result = detokenizeText(text, store);\n // Count how many token occurrences appeared in the text and were resolved.\n // We scan the text for all token-like patterns and subtract the unresolved ones.\n const totalInText = (text.match(LEGACY_TOKEN_PATTERN) ?? []).length;\n const replacedCount = totalInText - result.unresolved.length;\n return {\n text: result.text,\n replacedCount,\n unresolved: result.unresolved,\n };\n}\n"]}
@@ -99,5 +99,5 @@ function randomBytes(crypto, length) {
99
99
  }
100
100
 
101
101
  export { concatBytes, decodeText, encodeText, fromBase64Url, isWellFormed, randomBytes, toBase32, toBase64Url, toHex, utf8 };
102
- //# sourceMappingURL=chunk-6LDAIJBL.js.map
103
- //# sourceMappingURL=chunk-6LDAIJBL.js.map
102
+ //# sourceMappingURL=chunk-QBBJR7DZ.js.map
103
+ //# sourceMappingURL=chunk-QBBJR7DZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/encoding.ts"],"names":[],"mappings":";AAOA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,IAAM,OAAA,GAAU,IAAI,WAAA,CAAY,OAAA,EAAS,EAAE,KAAA,EAAO,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,CAAA;AAEzE,IAAM,cAAA,GAAiB,wEAAA;AAEvB,IAAM,YAAA,GAAe,GAAA;AASd,SAAS,KAAK,IAAA,EAAqB;AACxC,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA;AACnC,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,OAAA,CAAQ,MAAM,CAAA;AACzC,EAAA,GAAA,CAAI,IAAI,OAAO,CAAA;AACf,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,SAAS,KAAA,EAAuC;AAC9D,EAAA,IAAI;AACF,IAAA,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,SAAS,aAAa,IAAA,EAAuB;AAClD,EAAA,OAAO,CAAC,cAAA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AChD;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,KAAA,EAAO;AAC1B,IAAA,MAAA,IAAA,CAAW,KAAK,IAAA,IAAQ,CAAA;AAAA,EAC1B;AACA,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,WAAA,CAAY,QAAgB,MAAA,EAAuB;AACjE,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,MAAM,CAAA;AACjC,EAAA,MAAA,CAAO,gBAAgB,GAAG,CAAA;AAC1B,EAAA,OAAO,GAAA;AACT","file":"chunk-6LDAIJBL.js","sourcesContent":["/**\n * @module internal/encoding\n * @description Byte and text encodings shared by the cryptographic modules.\n * They avoid `Buffer` so that they work in every runtime.\n * @internal\n */\n\nconst encoder = new TextEncoder();\n// `ignoreBOM` keeps a leading U+FEFF: a decoded value must equal what was encoded.\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n/** First byte of the fallback encoding of {@link encodeText}; it never starts a UTF-8 sequence. */\nconst UTF16_MARKER = 0xff;\n\n/** Bytes backed by a plain `ArrayBuffer`, as the Web Crypto API requires. */\nexport type Bytes = Uint8Array<ArrayBuffer>;\n\n/**\n * Encode a string as UTF-8.\n * @internal\n */\nexport function utf8(text: string): Bytes {\n const encoded = encoder.encode(text);\n const out = new Uint8Array(encoded.length);\n out.set(encoded);\n return out;\n}\n\n/**\n * Decode UTF-8 bytes. Returns `undefined` when the bytes are not valid UTF-8.\n * @internal\n */\nexport function fromUtf8(bytes: Uint8Array): string | undefined {\n try {\n return decoder.decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether `text` is well-formed UTF-16, that is, has no lone surrogate.\n * @internal\n */\nexport function isWellFormed(text: string): boolean {\n return !LONE_SURROGATE.test(text);\n}\n\n/**\n * Encode a string without loss. Well-formed strings become UTF-8. A string\n * with a lone surrogate, which UTF-8 cannot represent, becomes a marker byte\n * followed by its UTF-16 code units, so that different strings never share an\n * encoding.\n * @internal\n */\nexport function encodeText(text: string): Bytes {\n if (isWellFormed(text)) return utf8(text);\n const out = new Uint8Array(1 + text.length * 2);\n out[0] = UTF16_MARKER;\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n out[1 + i * 2] = unit & 0xff;\n out[2 + i * 2] = unit >>> 8;\n }\n return out;\n}\n\n/**\n * Reverse {@link encodeText}. Returns `undefined` for bytes it did not produce.\n * @internal\n */\nexport function decodeText(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== UTF16_MARKER) return fromUtf8(bytes);\n if (bytes.length % 2 !== 1) return undefined;\n let out = \"\";\n for (let i = 1; i < bytes.length; i += 2) {\n out += String.fromCharCode((bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8));\n }\n return out;\n}\n\n/**\n * Concatenate byte arrays.\n * @internal\n */\nexport function concatBytes(...parts: readonly Uint8Array[]): Bytes {\n let length = 0;\n for (const part of parts) length += part.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * Lower-case hexadecimal encoding.\n * @internal\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * URL-safe base64 without padding (RFC 4648 §5). Encodes in slices so that\n * large inputs never exceed the engine's argument limit.\n * @internal\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The URL-safe base64 alphabet, in value order. */\nconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/**\n * Decode URL-safe base64 without padding. Returns `undefined` for malformed\n * input, including input whose last character carries bits that the encoder\n * would have left at zero: every byte string has exactly one accepted text.\n * @internal\n */\nexport function fromBase64Url(text: string): Bytes | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return undefined;\n const remainder = text.length % 4;\n if (remainder !== 0) {\n const last = BASE64_ALPHABET.indexOf(text.charAt(text.length - 1));\n if ((last & (remainder === 2 ? 0b1111 : 0b11)) !== 0) return undefined;\n }\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * Crockford base32 of the first `chars * 5` bits of `bytes`. The alphabet has\n * no `I`, `L`, `O` or `U`, so identifiers survive being read aloud or retyped.\n * @internal\n */\nexport function toBase32(bytes: Uint8Array, chars: number): string {\n let out = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5 && out.length < chars) {\n bits -= 5;\n out += CROCKFORD.charAt((buffer >>> bits) & 31);\n }\n if (out.length === chars) break;\n buffer &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * `length` cryptographically random bytes.\n * @internal\n */\nexport function randomBytes(crypto: Crypto, length: number): Bytes {\n const out = new Uint8Array(length);\n crypto.getRandomValues(out);\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/encoding.ts"],"names":[],"mappings":";AAOA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,IAAM,OAAA,GAAU,IAAI,WAAA,CAAY,OAAA,EAAS,EAAE,KAAA,EAAO,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,CAAA;AAEzE,IAAM,cAAA,GAAiB,wEAAA;AAEvB,IAAM,YAAA,G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kCAAA;AAOX,SAAS,QAAA,CAAS,OAAmB,KAAA,EAAuB;AACjE,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAA,GAAU,UAAU,CAAA,GAAK,IAAA;AACzB,IAAA,IAAA,IAAQ,CAAA;AACR,IAAA,OAAO,IAAA,IAAQ,CAAA,IAAK,GAAA,CAAI,MAAA,GAAS,KAAA,EAAO;AACtC,MAAA,IAAA,IAAQ,CAAA;AACR,MAAA,GAAA,IAAO,SAAA,CAAU,MAAA,CAAQ,MAAA,KAAW,IAAA,GAAQ,EAAE,CAAA;AAAA,IAChD;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,KAAA,EAAO;AAC1B,IAAA,MAAA,IAAA,CAAW,KAAK,IAAA,IAAQ,CAAA;AAAA,EAC1B;AACA,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,WAAA,CAAY,QAAgB,MAAA,EAAuB;AACjE,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,MAAM,CAAA;AACjC,EAAA,MAAA,CAAO,gBAAgB,GAAG,CAAA;AAC1B,EAAA,OAAO,GAAA;AACT","file":"chunk-QBBJR7DZ.js","sourcesContent":["/**\n * @module internal/encoding\n * @description Byte and text encodings shared by the cryptographic modules.\n * They avoid `Buffer` so that they work in every runtime.\n * @internal\n */\n\nconst encoder = new TextEncoder();\n// `ignoreBOM` keeps a leading U+FEFF: a decoded value must equal what was encoded.\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n/** First byte of the fallback encoding of {@link encodeText}; it never starts a UTF-8 sequence. */\nconst UTF16_MARKER = 0xff;\n\n/** Bytes backed by a plain `ArrayBuffer`, as the Web Crypto API requires. */\nexport type Bytes = Uint8Array<ArrayBuffer>;\n\n/**\n * Encode a string as UTF-8.\n * @internal\n */\nexport function utf8(text: string): Bytes {\n const encoded = encoder.encode(text);\n const out = new Uint8Array(encoded.length);\n out.set(encoded);\n return out;\n}\n\n/**\n * Decode UTF-8 bytes. Returns `undefined` when the bytes are not valid UTF-8.\n * @internal\n */\nexport function fromUtf8(bytes: Uint8Array): string | undefined {\n try {\n return decoder.decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether `text` is well-formed UTF-16, that is, has no lone surrogate.\n * @internal\n */\nexport function isWellFormed(text: string): boolean {\n return !LONE_SURROGATE.test(text);\n}\n\n/**\n * Encode a string without loss. Well-formed strings become UTF-8. A string\n * with a lone surrogate, which UTF-8 cannot represent, becomes a marker byte\n * followed by its UTF-16 code units, so that different strings never share an\n * encoding.\n * @internal\n */\nexport function encodeText(text: string): Bytes {\n if (isWellFormed(text)) return utf8(text);\n const out = new Uint8Array(1 + text.length * 2);\n out[0] = UTF16_MARKER;\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n out[1 + i * 2] = unit & 0xff;\n out[2 + i * 2] = unit >>> 8;\n }\n return out;\n}\n\n/**\n * Reverse {@link encodeText}. Returns `undefined` for bytes it did not produce.\n * @internal\n */\nexport function decodeText(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== UTF16_MARKER) return fromUtf8(bytes);\n if (bytes.length % 2 !== 1) return undefined;\n let out = \"\";\n for (let i = 1; i < bytes.length; i += 2) {\n /* v8 ignore next -- the length is odd, so i and i + 1 are always in range */\n out += String.fromCharCode((bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8));\n }\n return out;\n}\n\n/**\n * Concatenate byte arrays.\n * @internal\n */\nexport function concatBytes(...parts: readonly Uint8Array[]): Bytes {\n let length = 0;\n for (const part of parts) length += part.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * Lower-case hexadecimal encoding.\n * @internal\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * URL-safe base64 without padding (RFC 4648 §5). Encodes in slices so that\n * large inputs never exceed the engine's argument limit.\n * @internal\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The URL-safe base64 alphabet, in value order. */\nconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/**\n * Decode URL-safe base64 without padding. Returns `undefined` for malformed\n * input, including input whose last character carries bits that the encoder\n * would have left at zero: every byte string has exactly one accepted text.\n * @internal\n */\nexport function fromBase64Url(text: string): Bytes | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return undefined;\n const remainder = text.length % 4;\n if (remainder !== 0) {\n const last = BASE64_ALPHABET.indexOf(text.charAt(text.length - 1));\n if ((last & (remainder === 2 ? 0b1111 : 0b11)) !== 0) return undefined;\n }\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * Crockford base32 of the first `chars * 5` bits of `bytes`. The alphabet has\n * no `I`, `L`, `O` or `U`, so identifiers survive being read aloud or retyped.\n * @internal\n */\nexport function toBase32(bytes: Uint8Array, chars: number): string {\n let out = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5 && out.length < chars) {\n bits -= 5;\n out += CROCKFORD.charAt((buffer >>> bits) & 31);\n }\n if (out.length === chars) break;\n buffer &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * `length` cryptographically random bytes.\n * @internal\n */\nexport function randomBytes(crypto: Crypto, length: number): Bytes {\n const out = new Uint8Array(length);\n crypto.getRandomValues(out);\n return out;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { detectVinAggressive, detectNameAggressive, detectCreditCardAggressive, detectSsnAggressive, detectPhoneAggressive, detectEmailAggressive, detectCompanyRegistration, detectCaseNumber, detectTrackingNumber, detectLicensePlate, detectVin, detectSocialMedia, detectApiKey, detectPrescription, detectHealthInsurance, detectMedicalRecord, detectTaxId, detectCryptocurrency, detectBankAccount, detectNationalId, detectDriversLicense, detectPassport, detectAddress, detectName, detectDateOfBirth, detectIban, detectUrl, detectIpv6, detectIpv4, detectCreditCard, detectSsn, detectPhone, detectEmail } from './chunk-RCW5IPPR.js';
1
+ import { detectVinAggressive, detectNameAggressive, detectCreditCardAggressive, detectSsnAggressive, detectPhoneAggressive, detectEmailAggressive, detectCompanyRegistration, detectCaseNumber, detectTrackingNumber, detectLicensePlate, detectVin, detectSocialMedia, detectApiKey, detectPrescription, detectHealthInsurance, detectMedicalRecord, detectTaxId, detectCryptocurrency, detectBankAccount, detectNationalId, detectDriversLicense, detectPassport, detectAddress, detectName, detectDateOfBirth, detectIban, detectUrl, detectIpv6, detectIpv4, detectCreditCard, detectSsn, detectPhone, detectEmail } from './chunk-UCT6HDUD.js';
2
2
  import { ValidationError } from './chunk-2F2GWGTB.js';
3
3
 
4
4
  // src/engine/detector.ts
@@ -264,5 +264,5 @@ var LEGACY_AGGRESSIVE_DETECTORS = Object.freeze({
264
264
  });
265
265
 
266
266
  export { BUILTIN_CATEGORIES, LEGACY_AGGRESSIVE_DETECTORS, LEGACY_DETECTORS, addressDetector, apiKeyDetector, bankAccountDetector, caseNumberDetector, companyRegistrationDetector, cryptocurrencyDetector, dateOfBirthDetector, defineDetector, defineRegexDetector, driversLicenseDetector, fromLegacyDetector, healthInsuranceDetector, legacyCreditCardAggressiveDetector, legacyCreditCardDetector, legacyEmailAggressiveDetector, legacyEmailDetector, legacyIbanDetector, legacyIpv4Detector, legacyIpv6Detector, legacySsnAggressiveDetector, legacySsnDetector, licensePlateDetector, medicalRecordDetector, nameAggressiveDetector, nameDetector, nationalIdDetector, passportDetector, phoneAggressiveDetector, phoneDetector, prescriptionDetector, socialMediaDetector, taxIdDetector, trackingNumberDetector, urlDetector, vinAggressiveDetector, vinDetector };
267
- //# sourceMappingURL=chunk-3D5ZCJ7R.js.map
268
- //# sourceMappingURL=chunk-3D5ZCJ7R.js.map
267
+ //# sourceMappingURL=chunk-QHQ2AU45.js.map
268
+ //# sourceMappingURL=chunk-QHQ2AU45.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/engine/detector.ts","../src/engine/builtin.ts"],"names":[],"mappings":";;;;AAkCO,SAAS,eAAe,QAAA,EAAsC;AACnE,EAAA,IAAI,OAAO,QAAA,CAAS,EAAA,KAAO,YAAY,QAAA,CAAS,EAAA,CAAG,WAAW,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAI,eAAA,CAAgB,aAAA,EAAe,4BAA4B,CAAA;AAAA,EACvE;AACA,EAAA,IAAI,OAAO,QAAA,CAAS,QAAA,KAAa,YAAY,QAAA,CAAS,QAAA,CAAS,WAAW,CAAA,EAAG;AAC3E,IAAA,MAAM,IAAI,eAAA,CAAgB,mBAAA,EAAqB,4BAA4B,CAAA;AAAA,EAC7E;AACA,EAAA,IAAI,OAAO,QAAA,CAAS,IAAA,KAAS,UAAA,EAAY;AACvC,IAAA,MAAM,IAAI,eAAA,CAAgB,eAAA,EAAiB,oBAAoB,CAAA;AAAA,EACjE;AACA,EAAA,IACE,QAAA,CAAS,cAAA,KAAmB,MAAA,KAC3B,CAAC,MAAA,CAAO,SAAA,CAAU,QAAA,CAAS,cAAc,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AAM,kBAAA;AAAA,EACN,IAAA,EAAM,kBAAA;AAAA,EACN,GAAA,EAAK,WAAA;AAAA,EACL,IAAA,EAAM,kBAAA;AAAA,EACN,eAAA,EAAiB,mBAAA;AAAA,EACjB,IAAA,EAAM,YAAA;AAAA,EACN,OAAA,EAAS,eAAA;AAAA,EACT,QAAA,EAAU,gBAAA;AAAA,EACV,iBAAA,EAAmB,sBAAA;AAAA,EACnB,aAAA,EAAe,kBAAA;AAAA,EACf,cAAA,EAAgB,mBAAA;AAAA,EAChB,cAAA,EAAgB,sBAAA;AAAA,EAChB,QAAA,EAAU,aAAA;AAAA,EACV,gBAAA,EAAkB,qBAAA;AAAA,EAClB,kBAAA,EAAoB,uBAAA;AAAA,EACpB,YAAA,EAAc,oBAAA;AAAA,EACd,SAAA,EAAW,cAAA;AAAA,EACX,cAAA,EAAgB,mBAAA;AAAA,EAChB,GAAA,EAAK,WAAA;AAAA,EACL,eAAA,EAAiB,oBAAA;AAAA,EACjB,iBAAA,EAAmB,sBAAA;AAAA,EACnB,aAAA,EAAe,kBAAA;AAAA,EACf,sBAAA,EAAwB;AAC1B,CAAC;AAMM,IAAM,2BAAA,GACX,OAAO,MAAA,CAAO;AAAA,EACZ,GAAG,gBAAA;AAAA,EACH,KAAA,EAAO,6BAAA;AAAA,EACP,KAAA,EAAO,uBAAA;AAAA,EACP,GAAA,EAAK,2BAAA;AAAA,EACL,aAAA,EAAe,kCAAA;AAAA,EACf,IAAA,EAAM,sBAAA;AAAA,EACN,GAAA,EAAK;AACP,CAAC","file":"chunk-3D5ZCJ7R.js","sourcesContent":["/**\n * @module engine/detector\n * @description Factories for span detectors: a validating constructor, a\n * declarative regular-expression detector, and an adapter for the 1.x\n * `(text) => PiiMatch[]` detector functions.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { Detector } from \"../types.js\";\nimport type { Category, EmitSpan, SpanDetector } from \"./types.js\";\n\n/**\n * Validate a detector definition and return a frozen copy of it.\n *\n * @param detector - The detector definition.\n * @returns The frozen detector.\n * @throws {@link ValidationError} When `id` or `category` is empty or `scan` is not a function.\n *\n * @example\n * ```ts\n * import { defineDetector } from \"anonyma/engine\";\n *\n * export const badgeDetector = defineDetector({\n * id: \"acme/badge\",\n * category: \"badge\",\n * prefilter: (text) => text.includes(\"BDG-\"),\n * scan(text, emit) {\n * for (let at = text.indexOf(\"BDG-\"); at >= 0; at = text.indexOf(\"BDG-\", at + 1)) {\n * emit(at, at + 10, 0.9);\n * }\n * },\n * });\n * ```\n */\nexport function defineDetector(detector: SpanDetector): SpanDetector {\n if (typeof detector.id !== \"string\" || detector.id.length === 0) {\n throw new ValidationError(\"detector.id\", \"must be a non-empty string\");\n }\n if (typeof detector.category !== \"string\" || detector.category.length === 0) {\n throw new ValidationError(\"detector.category\", \"must be a non-empty string\");\n }\n if (typeof detector.scan !== \"function\") {\n throw new ValidationError(\"detector.scan\", \"must be a function\");\n }\n if (\n detector.maxMatchLength !== undefined &&\n (!Number.isInteger(detector.maxMatchLength) || detector.maxMatchLength < 1)\n ) {\n throw new ValidationError(\"detector.maxMatchLength\", \"must be a positive integer\");\n }\n return Object.freeze({ ...detector });\n}\n\n/**\n * Options accepted by {@link defineRegexDetector}.\n */\nexport interface RegexDetectorOptions {\n /** Detector identifier. Defaults to the category. */\n readonly id?: string;\n /** Category attached to every hit. */\n readonly category: Category;\n /**\n * The pattern to search for. It is compiled once; the `g` flag is added when\n * missing and the `y` flag is removed.\n */\n readonly pattern: RegExp;\n /** Confidence of a hit, fixed or computed from the match. Defaults to `0.85`. */\n readonly confidence?: number | ((match: RegExpExecArray) => number);\n /** Capture group whose text is the hit. Defaults to `0`, the whole match. */\n readonly group?: number;\n /** Extra check on a match, such as a checksum. Return `false` to discard it. */\n readonly validate?: (value: string, match: RegExpExecArray) => boolean;\n /** The detector is skipped for texts that contain none of these substrings. */\n readonly requires?: readonly string[];\n /** See {@link SpanDetector.maxMatchLength}. */\n readonly maxMatchLength?: number;\n}\n\n/**\n * Build a detector from a regular expression. The expression is compiled once\n * and reused across calls.\n *\n * @param options - The pattern and how to interpret its matches.\n * @returns A frozen {@link SpanDetector}.\n * @throws {@link ValidationError} When `pattern` is not a `RegExp`, `group` is negative or\n * `confidence` is not a number between 0 and 1.\n *\n * @example\n * ```ts\n * import { defineRegexDetector } from \"anonyma/engine\";\n *\n * export const orderIdDetector = defineRegexDetector({\n * category: \"order-id\",\n * pattern: /\\bACME-(\\d{6})\\b/,\n * confidence: 0.9,\n * requires: [\"ACME-\"],\n * maxMatchLength: 11,\n * });\n * ```\n */\nexport function defineRegexDetector(options: RegexDetectorOptions): SpanDetector {\n const { category, pattern, confidence = 0.85, group = 0, validate, requires } = options;\n\n if (!(pattern instanceof RegExp)) {\n throw new ValidationError(\"pattern\", \"must be a RegExp instance\");\n }\n if (!Number.isInteger(group) || group < 0) {\n throw new ValidationError(\"group\", \"must be a non-negative integer\");\n }\n if (\n typeof confidence !== \"function\" &&\n !(typeof confidence === \"number\" && confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\"confidence\", \"must be a number between 0 and 1, or a function\");\n }\n\n let flags = pattern.flags.replace(\"y\", \"\");\n if (!flags.includes(\"g\")) flags += \"g\";\n if (group > 0 && !flags.includes(\"d\")) flags += \"d\";\n const compiled = new RegExp(pattern.source, flags);\n\n const scan = (text: string, emit: EmitSpan): void => {\n compiled.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = compiled.exec(text)) !== null) {\n if (match[0].length === 0) {\n // A pattern that can match the empty string would never advance.\n compiled.lastIndex++;\n continue;\n }\n let start = match.index;\n let end = start + match[0].length;\n if (group > 0) {\n const bounds = match.indices?.[group];\n if (bounds === undefined || bounds[1] === bounds[0]) continue;\n [start, end] = bounds;\n }\n if (validate !== undefined && !validate(text.slice(start, end), match)) continue;\n emit(start, end, typeof confidence === \"function\" ? confidence(match) : confidence);\n }\n };\n\n return defineDetector({\n id: options.id ?? category,\n category,\n scan,\n ...(requires !== undefined && requires.length > 0\n ? { prefilter: (text: string): boolean => requires.some((needle) => text.includes(needle)) }\n : {}),\n ...(options.maxMatchLength !== undefined ? { maxMatchLength: options.maxMatchLength } : {}),\n });\n}\n\n/**\n * Options accepted by {@link fromLegacyDetector}.\n */\nexport interface LegacyDetectorOptions {\n /** Detector identifier. Defaults to the category. */\n readonly id?: string;\n /** See {@link SpanDetector.prefilter}. */\n readonly prefilter?: (text: string) => boolean;\n /** See {@link SpanDetector.maxMatchLength}. */\n readonly maxMatchLength?: number;\n}\n\n/**\n * Adapt a 1.x detector function — `(text) => PiiMatch[]` — to the span engine.\n * The adapted detector reports exactly the matches the function returns.\n *\n * @param category - Category attached to every hit.\n * @param detect - The 1.x detector function.\n * @param options - Optional identifier, prefilter and length bound.\n * @returns A frozen {@link SpanDetector}.\n *\n * @example\n * ```ts\n * import { fromLegacyDetector } from \"anonyma/engine\";\n * import { detectPhone } from \"anonyma/detectors\";\n *\n * export const phoneDetector = fromLegacyDetector(\"phone\", detectPhone);\n * ```\n */\nexport function fromLegacyDetector(\n category: Category,\n detect: Detector,\n options: LegacyDetectorOptions = {},\n): SpanDetector {\n if (typeof detect !== \"function\") {\n throw new ValidationError(\"detect\", \"must be a function\");\n }\n return defineDetector({\n id: options.id ?? category,\n category,\n scan(text, emit) {\n for (const match of detect(text)) emit(match.start, match.end, match.confidence);\n },\n ...(options.prefilter !== undefined ? { prefilter: options.prefilter } : {}),\n ...(options.maxMatchLength !== undefined ? { maxMatchLength: options.maxMatchLength } : {}),\n });\n}\n","/**\n * @module engine/builtin\n * @description The 27 built-in detectors as span detectors.\n *\n * Each export wraps the corresponding 1.x detector function and reports\n * exactly the same matches, so a pipeline built from them detects what\n * `detect()` detects. Every detector is a separate export: import only the\n * ones a pipeline needs and bundlers drop the rest.\n */\n\nimport { detectAddress } from \"../detectors/address.js\";\nimport { detectApiKey } from \"../detectors/api-key.js\";\nimport { detectBankAccount } from \"../detectors/bank-account.js\";\nimport { detectCaseNumber } from \"../detectors/case-number.js\";\nimport { detectCompanyRegistration } from \"../detectors/company-registration.js\";\nimport { detectCreditCard, detectCreditCardAggressive } from \"../detectors/credit-card.js\";\nimport { detectCryptocurrency } from \"../detectors/cryptocurrency.js\";\nimport { detectDateOfBirth } from \"../detectors/date-of-birth.js\";\nimport { detectDriversLicense } from \"../detectors/drivers-license.js\";\nimport { detectEmail, detectEmailAggressive } from \"../detectors/email.js\";\nimport { detectHealthInsurance } from \"../detectors/health-insurance.js\";\nimport { detectIban } from \"../detectors/iban.js\";\nimport { detectIpv4, detectIpv6 } from \"../detectors/ip-address.js\";\nimport { detectLicensePlate } from \"../detectors/license-plate.js\";\nimport { detectMedicalRecord } from \"../detectors/medical-record.js\";\nimport { detectName, detectNameAggressive } from \"../detectors/name.js\";\nimport { detectNationalId } from \"../detectors/national-id.js\";\nimport { detectPassport } from \"../detectors/passport.js\";\nimport { detectPhone, detectPhoneAggressive } from \"../detectors/phone.js\";\nimport { detectPrescription } from \"../detectors/prescription.js\";\nimport { detectSocialMedia } from \"../detectors/social-media.js\";\nimport { detectSsn, detectSsnAggressive } from \"../detectors/ssn.js\";\nimport { detectTaxId } from \"../detectors/tax-id.js\";\nimport { detectTrackingNumber } from \"../detectors/tracking-number.js\";\nimport { detectUrl } from \"../detectors/url.js\";\nimport { detectVin, detectVinAggressive } from \"../detectors/vin.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport { fromLegacyDetector } from \"./detector.js\";\nimport type { SpanDetector } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Prefilters\n// ---------------------------------------------------------------------------\n\nlet lastDigitText: string | undefined;\nlet lastDigitResult = false;\n\n/**\n * `true` when the text contains an ASCII digit. Several detectors can only\n * match text with digits, so the answer for the most recent text is kept.\n */\nfunction hasDigit(text: string): boolean {\n if (text !== lastDigitText) {\n lastDigitText = text;\n lastDigitResult = /\\d/.test(text);\n }\n return lastDigitResult;\n}\n\nconst hasAt = (text: string): boolean => text.includes(\"@\");\nconst hasDot = (text: string): boolean => text.includes(\".\") && hasDigit(text);\nconst hasColon = (text: string): boolean => text.includes(\":\");\nconst hasScheme = (text: string): boolean => text.includes(\"://\");\n\n// ---------------------------------------------------------------------------\n// Standard detectors\n// ---------------------------------------------------------------------------\n\n/** Email addresses. */\nexport const legacyEmailDetector: SpanDetector = fromLegacyDetector(\"email\", detectEmail, {\n prefilter: hasAt,\n});\n/** Phone numbers. */\nexport const phoneDetector: SpanDetector = fromLegacyDetector(\"phone\", detectPhone, {\n prefilter: hasDigit,\n});\n/** US Social Security Numbers. */\nexport const legacySsnDetector: SpanDetector = fromLegacyDetector(\"ssn\", detectSsn, {\n prefilter: hasDigit,\n maxMatchLength: 11,\n});\n/** Payment card numbers. */\nexport const legacyCreditCardDetector: SpanDetector = fromLegacyDetector(\n \"credit-card\",\n detectCreditCard,\n { prefilter: hasDigit, maxMatchLength: 40 },\n);\n/** IPv4 addresses. */\nexport const legacyIpv4Detector: SpanDetector = fromLegacyDetector(\"ipv4\", detectIpv4, {\n prefilter: hasDot,\n maxMatchLength: 18,\n});\n/** IPv6 addresses. */\nexport const legacyIpv6Detector: SpanDetector = fromLegacyDetector(\"ipv6\", detectIpv6, {\n prefilter: hasColon,\n maxMatchLength: 45,\n});\n/** URLs. */\nexport const urlDetector: SpanDetector = fromLegacyDetector(\"url\", detectUrl, {\n prefilter: hasScheme,\n});\n/** International Bank Account Numbers. */\nexport const legacyIbanDetector: SpanDetector = fromLegacyDetector(\"iban\", detectIban, {\n prefilter: hasDigit,\n maxMatchLength: 42,\n});\n/** Dates of birth. */\nexport const dateOfBirthDetector: SpanDetector = fromLegacyDetector(\n \"date-of-birth\",\n detectDateOfBirth,\n { prefilter: hasDigit },\n);\n/** Person names (heuristic). */\nexport const nameDetector: SpanDetector = fromLegacyDetector(\"name\", detectName);\n/** Postal addresses. */\nexport const addressDetector: SpanDetector = fromLegacyDetector(\"address\", detectAddress);\n/** Passport numbers. */\nexport const passportDetector: SpanDetector = fromLegacyDetector(\"passport\", detectPassport);\n/** Driver's licence numbers. */\nexport const driversLicenseDetector: SpanDetector = fromLegacyDetector(\n \"drivers-license\",\n detectDriversLicense,\n);\n/** National identification numbers. */\nexport const nationalIdDetector: SpanDetector = fromLegacyDetector(\"national-id\", detectNationalId);\n/** Bank account and routing numbers. */\nexport const bankAccountDetector: SpanDetector = fromLegacyDetector(\n \"bank-account\",\n detectBankAccount,\n);\n/** Cryptocurrency wallet addresses. */\nexport const cryptocurrencyDetector: SpanDetector = fromLegacyDetector(\n \"cryptocurrency\",\n detectCryptocurrency,\n);\n/** Tax identification numbers. */\nexport const taxIdDetector: SpanDetector = fromLegacyDetector(\"tax-id\", detectTaxId);\n/** Medical record numbers. */\nexport const medicalRecordDetector: SpanDetector = fromLegacyDetector(\n \"medical-record\",\n detectMedicalRecord,\n);\n/** Health insurance identifiers. */\nexport const healthInsuranceDetector: SpanDetector = fromLegacyDetector(\n \"health-insurance\",\n detectHealthInsurance,\n);\n/** Prescription numbers. */\nexport const prescriptionDetector: SpanDetector = fromLegacyDetector(\n \"prescription\",\n detectPrescription,\n);\n/** API keys and access tokens. */\nexport const apiKeyDetector: SpanDetector = fromLegacyDetector(\"api-key\", detectApiKey);\n/** Social media handles and identifiers. */\nexport const socialMediaDetector: SpanDetector = fromLegacyDetector(\n \"social-media\",\n detectSocialMedia,\n);\n/** Vehicle identification numbers. */\nexport const vinDetector: SpanDetector = fromLegacyDetector(\"vin\", detectVin);\n/** Vehicle licence plates. */\nexport const licensePlateDetector: SpanDetector = fromLegacyDetector(\n \"license-plate\",\n detectLicensePlate,\n);\n/** Shipment tracking numbers. */\nexport const trackingNumberDetector: SpanDetector = fromLegacyDetector(\n \"tracking-number\",\n detectTrackingNumber,\n);\n/** Court case numbers. */\nexport const caseNumberDetector: SpanDetector = fromLegacyDetector(\"case-number\", detectCaseNumber);\n/** Company registration numbers. */\nexport const companyRegistrationDetector: SpanDetector = fromLegacyDetector(\n \"company-registration\",\n detectCompanyRegistration,\n);\n\n// ---------------------------------------------------------------------------\n// Aggressive variants\n// ---------------------------------------------------------------------------\n\n/** Email addresses, including obfuscated forms such as `user [at] example [dot] com`. */\nexport const legacyEmailAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"email\",\n detectEmailAggressive,\n);\n/** Phone numbers, including seven-digit local numbers. */\nexport const phoneAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"phone\",\n detectPhoneAggressive,\n { prefilter: hasDigit },\n);\n/** US Social Security Numbers, aggressive variant. */\nexport const legacySsnAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"ssn\",\n detectSsnAggressive,\n { prefilter: hasDigit, maxMatchLength: 11 },\n);\n/** Payment card numbers, including masked forms such as `****-****-****-1234`. */\nexport const legacyCreditCardAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"credit-card\",\n detectCreditCardAggressive,\n { prefilter: hasDigit, maxMatchLength: 40 },\n);\n/** Person names, aggressive variant. */\nexport const nameAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"name\",\n detectNameAggressive,\n);\n/** Vehicle identification numbers without checksum validation. */\nexport const vinAggressiveDetector: SpanDetector = fromLegacyDetector(\"vin\", detectVinAggressive);\n\n// ---------------------------------------------------------------------------\n// Registries\n// ---------------------------------------------------------------------------\n\n/**\n * Every built-in category, in the order the 1.x engine scans them.\n */\nexport const BUILTIN_CATEGORIES: readonly PiiCategory[] = Object.freeze([\n \"email\",\n \"phone\",\n \"ssn\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"iban\",\n \"date-of-birth\",\n \"name\",\n \"address\",\n \"passport\",\n \"drivers-license\",\n \"national-id\",\n \"bank-account\",\n \"cryptocurrency\",\n \"tax-id\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"api-key\",\n \"social-media\",\n \"vin\",\n \"license-plate\",\n \"tracking-number\",\n \"case-number\",\n \"company-registration\",\n] as const);\n\n/**\n * Span detectors that reproduce the 1.x detectors exactly, keyed by category.\n *\n * @example\n * ```ts\n * import { createPipeline, LEGACY_DETECTORS, redactWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: Object.values(LEGACY_DETECTORS),\n * replace: { fallback: redactWith() },\n * overlap: \"legacy\",\n * });\n * ```\n */\nexport const LEGACY_DETECTORS: Readonly<Record<PiiCategory, SpanDetector>> = Object.freeze({\n email: legacyEmailDetector,\n phone: phoneDetector,\n ssn: legacySsnDetector,\n \"credit-card\": legacyCreditCardDetector,\n ipv4: legacyIpv4Detector,\n ipv6: legacyIpv6Detector,\n url: urlDetector,\n iban: legacyIbanDetector,\n \"date-of-birth\": dateOfBirthDetector,\n name: nameDetector,\n address: addressDetector,\n passport: passportDetector,\n \"drivers-license\": driversLicenseDetector,\n \"national-id\": nationalIdDetector,\n \"bank-account\": bankAccountDetector,\n cryptocurrency: cryptocurrencyDetector,\n \"tax-id\": taxIdDetector,\n \"medical-record\": medicalRecordDetector,\n \"health-insurance\": healthInsuranceDetector,\n prescription: prescriptionDetector,\n \"api-key\": apiKeyDetector,\n \"social-media\": socialMediaDetector,\n vin: vinDetector,\n \"license-plate\": licensePlateDetector,\n \"tracking-number\": trackingNumberDetector,\n \"case-number\": caseNumberDetector,\n \"company-registration\": companyRegistrationDetector,\n});\n\n/**\n * The aggressive counterpart of {@link LEGACY_DETECTORS}: categories that have\n * an aggressive 1.x variant use it, all others use the standard detector.\n */\nexport const LEGACY_AGGRESSIVE_DETECTORS: Readonly<Record<PiiCategory, SpanDetector>> =\n Object.freeze({\n ...LEGACY_DETECTORS,\n email: legacyEmailAggressiveDetector,\n phone: phoneAggressiveDetector,\n ssn: legacySsnAggressiveDetector,\n \"credit-card\": legacyCreditCardAggressiveDetector,\n name: nameAggressiveDetector,\n vin: vinAggressiveDetector,\n });\n"]}
1
+ {"version":3,"sources":["../src/engine/detector.ts","../src/engine/builtin.ts"],"names":[],"mappings":";;;;AAkCO,SAAS,eAAe,QAAA,EAAsC;AACnE,EAAA,IAAI,OAAO,QAAA,CAAS,EAAA,KAAO,YAAY,QAAA,CAAS,EAAA,C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A,GACX,OAAO,MAAA,CAAO;AAAA,EACZ,GAAG,gBAAA;AAAA,EACH,KAAA,EAAO,6BAAA;AAAA,EACP,KAAA,EAAO,uBAAA;AAAA,EACP,GAAA,EAAK,2BAAA;AAAA,EACL,aAAA,EAAe,kCAAA;AAAA,EACf,IAAA,EAAM,sBAAA;AAAA,EACN,GAAA,EAAK;AACP,CAAC","file":"chunk-QHQ2AU45.js","sourcesContent":["/**\n * @module engine/detector\n * @description Factories for span detectors: a validating constructor, a\n * declarative regular-expression detector, and an adapter for the 1.x\n * `(text) => PiiMatch[]` detector functions.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { Detector } from \"../types.js\";\nimport type { Category, EmitSpan, SpanDetector } from \"./types.js\";\n\n/**\n * Validate a detector definition and return a frozen copy of it.\n *\n * @param detector - The detector definition.\n * @returns The frozen detector.\n * @throws {@link ValidationError} When `id` or `category` is empty or `scan` is not a function.\n *\n * @example\n * ```ts\n * import { defineDetector } from \"anonyma/engine\";\n *\n * export const badgeDetector = defineDetector({\n * id: \"acme/badge\",\n * category: \"badge\",\n * prefilter: (text) => text.includes(\"BDG-\"),\n * scan(text, emit) {\n * for (let at = text.indexOf(\"BDG-\"); at >= 0; at = text.indexOf(\"BDG-\", at + 1)) {\n * emit(at, at + 10, 0.9);\n * }\n * },\n * });\n * ```\n */\nexport function defineDetector(detector: SpanDetector): SpanDetector {\n if (typeof detector.id !== \"string\" || detector.id.length === 0) {\n throw new ValidationError(\"detector.id\", \"must be a non-empty string\");\n }\n if (typeof detector.category !== \"string\" || detector.category.length === 0) {\n throw new ValidationError(\"detector.category\", \"must be a non-empty string\");\n }\n if (typeof detector.scan !== \"function\") {\n throw new ValidationError(\"detector.scan\", \"must be a function\");\n }\n if (\n detector.maxMatchLength !== undefined &&\n (!Number.isInteger(detector.maxMatchLength) || detector.maxMatchLength < 1)\n ) {\n throw new ValidationError(\"detector.maxMatchLength\", \"must be a positive integer\");\n }\n return Object.freeze({ ...detector });\n}\n\n/**\n * Options accepted by {@link defineRegexDetector}.\n */\nexport interface RegexDetectorOptions {\n /** Detector identifier. Defaults to the category. */\n readonly id?: string;\n /** Category attached to every hit. */\n readonly category: Category;\n /**\n * The pattern to search for. It is compiled once; the `g` flag is added when\n * missing and the `y` flag is removed.\n */\n readonly pattern: RegExp;\n /** Confidence of a hit, fixed or computed from the match. Defaults to `0.85`. */\n readonly confidence?: number | ((match: RegExpExecArray) => number);\n /** Capture group whose text is the hit. Defaults to `0`, the whole match. */\n readonly group?: number;\n /** Extra check on a match, such as a checksum. Return `false` to discard it. */\n readonly validate?: (value: string, match: RegExpExecArray) => boolean;\n /** The detector is skipped for texts that contain none of these substrings. */\n readonly requires?: readonly string[];\n /** See {@link SpanDetector.maxMatchLength}. */\n readonly maxMatchLength?: number;\n}\n\n/**\n * Build a detector from a regular expression. The expression is compiled once\n * and reused across calls.\n *\n * @param options - The pattern and how to interpret its matches.\n * @returns A frozen {@link SpanDetector}.\n * @throws {@link ValidationError} When `pattern` is not a `RegExp`, `group` is negative or\n * `confidence` is not a number between 0 and 1.\n *\n * @example\n * ```ts\n * import { defineRegexDetector } from \"anonyma/engine\";\n *\n * export const orderIdDetector = defineRegexDetector({\n * category: \"order-id\",\n * pattern: /\\bACME-(\\d{6})\\b/,\n * confidence: 0.9,\n * requires: [\"ACME-\"],\n * maxMatchLength: 11,\n * });\n * ```\n */\nexport function defineRegexDetector(options: RegexDetectorOptions): SpanDetector {\n const { category, pattern, confidence = 0.85, group = 0, validate, requires } = options;\n\n if (!(pattern instanceof RegExp)) {\n throw new ValidationError(\"pattern\", \"must be a RegExp instance\");\n }\n if (!Number.isInteger(group) || group < 0) {\n throw new ValidationError(\"group\", \"must be a non-negative integer\");\n }\n if (\n typeof confidence !== \"function\" &&\n !(typeof confidence === \"number\" && confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\"confidence\", \"must be a number between 0 and 1, or a function\");\n }\n\n let flags = pattern.flags.replace(\"y\", \"\");\n if (!flags.includes(\"g\")) flags += \"g\";\n if (group > 0 && !flags.includes(\"d\")) flags += \"d\";\n const compiled = new RegExp(pattern.source, flags);\n\n const scan = (text: string, emit: EmitSpan): void => {\n compiled.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = compiled.exec(text)) !== null) {\n if (match[0].length === 0) {\n // A pattern that can match the empty string would never advance.\n compiled.lastIndex++;\n continue;\n }\n let start = match.index;\n let end = start + match[0].length;\n if (group > 0) {\n const bounds = match.indices?.[group];\n if (bounds === undefined || bounds[1] === bounds[0]) continue;\n [start, end] = bounds;\n }\n if (validate !== undefined && !validate(text.slice(start, end), match)) continue;\n emit(start, end, typeof confidence === \"function\" ? confidence(match) : confidence);\n }\n };\n\n return defineDetector({\n id: options.id ?? category,\n category,\n scan,\n ...(requires !== undefined && requires.length > 0\n ? { prefilter: (text: string): boolean => requires.some((needle) => text.includes(needle)) }\n : {}),\n ...(options.maxMatchLength !== undefined ? { maxMatchLength: options.maxMatchLength } : {}),\n });\n}\n\n/**\n * Options accepted by {@link fromLegacyDetector}.\n */\nexport interface LegacyDetectorOptions {\n /** Detector identifier. Defaults to the category. */\n readonly id?: string;\n /** See {@link SpanDetector.prefilter}. */\n readonly prefilter?: (text: string) => boolean;\n /** See {@link SpanDetector.maxMatchLength}. */\n readonly maxMatchLength?: number;\n}\n\n/**\n * Adapt a 1.x detector function — `(text) => PiiMatch[]` — to the span engine.\n * The adapted detector reports exactly the matches the function returns.\n *\n * @param category - Category attached to every hit.\n * @param detect - The 1.x detector function.\n * @param options - Optional identifier, prefilter and length bound.\n * @returns A frozen {@link SpanDetector}.\n *\n * @example\n * ```ts\n * import { fromLegacyDetector } from \"anonyma/engine\";\n * import { detectPhone } from \"anonyma/detectors\";\n *\n * export const phoneDetector = fromLegacyDetector(\"phone\", detectPhone);\n * ```\n */\nexport function fromLegacyDetector(\n category: Category,\n detect: Detector,\n options: LegacyDetectorOptions = {},\n): SpanDetector {\n if (typeof detect !== \"function\") {\n throw new ValidationError(\"detect\", \"must be a function\");\n }\n return defineDetector({\n id: options.id ?? category,\n category,\n scan(text, emit) {\n for (const match of detect(text)) emit(match.start, match.end, match.confidence);\n },\n ...(options.prefilter !== undefined ? { prefilter: options.prefilter } : {}),\n ...(options.maxMatchLength !== undefined ? { maxMatchLength: options.maxMatchLength } : {}),\n });\n}\n","/**\n * @module engine/builtin\n * @description The 27 built-in detectors as span detectors.\n *\n * Each export wraps the corresponding 1.x detector function and reports\n * exactly the same matches, so a pipeline built from them detects what\n * `detect()` detects. Every detector is a separate export: import only the\n * ones a pipeline needs and bundlers drop the rest.\n */\n\nimport { detectAddress } from \"../detectors/address.js\";\nimport { detectApiKey } from \"../detectors/api-key.js\";\nimport { detectBankAccount } from \"../detectors/bank-account.js\";\nimport { detectCaseNumber } from \"../detectors/case-number.js\";\nimport { detectCompanyRegistration } from \"../detectors/company-registration.js\";\nimport { detectCreditCard, detectCreditCardAggressive } from \"../detectors/credit-card.js\";\nimport { detectCryptocurrency } from \"../detectors/cryptocurrency.js\";\nimport { detectDateOfBirth } from \"../detectors/date-of-birth.js\";\nimport { detectDriversLicense } from \"../detectors/drivers-license.js\";\nimport { detectEmail, detectEmailAggressive } from \"../detectors/email.js\";\nimport { detectHealthInsurance } from \"../detectors/health-insurance.js\";\nimport { detectIban } from \"../detectors/iban.js\";\nimport { detectIpv4, detectIpv6 } from \"../detectors/ip-address.js\";\nimport { detectLicensePlate } from \"../detectors/license-plate.js\";\nimport { detectMedicalRecord } from \"../detectors/medical-record.js\";\nimport { detectName, detectNameAggressive } from \"../detectors/name.js\";\nimport { detectNationalId } from \"../detectors/national-id.js\";\nimport { detectPassport } from \"../detectors/passport.js\";\nimport { detectPhone, detectPhoneAggressive } from \"../detectors/phone.js\";\nimport { detectPrescription } from \"../detectors/prescription.js\";\nimport { detectSocialMedia } from \"../detectors/social-media.js\";\nimport { detectSsn, detectSsnAggressive } from \"../detectors/ssn.js\";\nimport { detectTaxId } from \"../detectors/tax-id.js\";\nimport { detectTrackingNumber } from \"../detectors/tracking-number.js\";\nimport { detectUrl } from \"../detectors/url.js\";\nimport { detectVin, detectVinAggressive } from \"../detectors/vin.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport { fromLegacyDetector } from \"./detector.js\";\nimport type { SpanDetector } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Prefilters\n// ---------------------------------------------------------------------------\n\nlet lastDigitText: string | undefined;\nlet lastDigitResult = false;\n\n/**\n * `true` when the text contains an ASCII digit. Several detectors can only\n * match text with digits, so the answer for the most recent text is kept.\n */\nfunction hasDigit(text: string): boolean {\n if (text !== lastDigitText) {\n lastDigitText = text;\n lastDigitResult = /\\d/.test(text);\n }\n return lastDigitResult;\n}\n\nconst hasAt = (text: string): boolean => text.includes(\"@\");\nconst hasDot = (text: string): boolean => text.includes(\".\") && hasDigit(text);\nconst hasColon = (text: string): boolean => text.includes(\":\");\nconst hasScheme = (text: string): boolean => text.includes(\"://\");\n\n// ---------------------------------------------------------------------------\n// Standard detectors\n// ---------------------------------------------------------------------------\n\n/** Email addresses. */\nexport const legacyEmailDetector: SpanDetector = fromLegacyDetector(\"email\", detectEmail, {\n prefilter: hasAt,\n});\n/** Phone numbers. */\nexport const phoneDetector: SpanDetector = fromLegacyDetector(\"phone\", detectPhone, {\n prefilter: hasDigit,\n});\n/** US Social Security Numbers. */\nexport const legacySsnDetector: SpanDetector = fromLegacyDetector(\"ssn\", detectSsn, {\n prefilter: hasDigit,\n maxMatchLength: 11,\n});\n/** Payment card numbers. */\nexport const legacyCreditCardDetector: SpanDetector = fromLegacyDetector(\n \"credit-card\",\n detectCreditCard,\n { prefilter: hasDigit, maxMatchLength: 40 },\n);\n/** IPv4 addresses. */\nexport const legacyIpv4Detector: SpanDetector = fromLegacyDetector(\"ipv4\", detectIpv4, {\n prefilter: hasDot,\n maxMatchLength: 18,\n});\n/** IPv6 addresses. */\nexport const legacyIpv6Detector: SpanDetector = fromLegacyDetector(\"ipv6\", detectIpv6, {\n prefilter: hasColon,\n maxMatchLength: 45,\n});\n/** URLs. */\nexport const urlDetector: SpanDetector = fromLegacyDetector(\"url\", detectUrl, {\n prefilter: hasScheme,\n});\n/** International Bank Account Numbers. */\nexport const legacyIbanDetector: SpanDetector = fromLegacyDetector(\"iban\", detectIban, {\n prefilter: hasDigit,\n maxMatchLength: 42,\n});\n/** Dates of birth. */\nexport const dateOfBirthDetector: SpanDetector = fromLegacyDetector(\n \"date-of-birth\",\n detectDateOfBirth,\n { prefilter: hasDigit },\n);\n/** Person names (heuristic). */\nexport const nameDetector: SpanDetector = fromLegacyDetector(\"name\", detectName);\n/** Postal addresses. */\nexport const addressDetector: SpanDetector = fromLegacyDetector(\"address\", detectAddress);\n/** Passport numbers. */\nexport const passportDetector: SpanDetector = fromLegacyDetector(\"passport\", detectPassport);\n/** Driver's licence numbers. */\nexport const driversLicenseDetector: SpanDetector = fromLegacyDetector(\n \"drivers-license\",\n detectDriversLicense,\n);\n/** National identification numbers. */\nexport const nationalIdDetector: SpanDetector = fromLegacyDetector(\"national-id\", detectNationalId);\n/** Bank account and routing numbers. */\nexport const bankAccountDetector: SpanDetector = fromLegacyDetector(\n \"bank-account\",\n detectBankAccount,\n);\n/** Cryptocurrency wallet addresses. */\nexport const cryptocurrencyDetector: SpanDetector = fromLegacyDetector(\n \"cryptocurrency\",\n detectCryptocurrency,\n);\n/** Tax identification numbers. */\nexport const taxIdDetector: SpanDetector = fromLegacyDetector(\"tax-id\", detectTaxId);\n/** Medical record numbers. */\nexport const medicalRecordDetector: SpanDetector = fromLegacyDetector(\n \"medical-record\",\n detectMedicalRecord,\n);\n/** Health insurance identifiers. */\nexport const healthInsuranceDetector: SpanDetector = fromLegacyDetector(\n \"health-insurance\",\n detectHealthInsurance,\n);\n/** Prescription numbers. */\nexport const prescriptionDetector: SpanDetector = fromLegacyDetector(\n \"prescription\",\n detectPrescription,\n);\n/** API keys and access tokens. */\nexport const apiKeyDetector: SpanDetector = fromLegacyDetector(\"api-key\", detectApiKey);\n/** Social media handles and identifiers. */\nexport const socialMediaDetector: SpanDetector = fromLegacyDetector(\n \"social-media\",\n detectSocialMedia,\n);\n/** Vehicle identification numbers. */\nexport const vinDetector: SpanDetector = fromLegacyDetector(\"vin\", detectVin);\n/** Vehicle licence plates. */\nexport const licensePlateDetector: SpanDetector = fromLegacyDetector(\n \"license-plate\",\n detectLicensePlate,\n);\n/** Shipment tracking numbers. */\nexport const trackingNumberDetector: SpanDetector = fromLegacyDetector(\n \"tracking-number\",\n detectTrackingNumber,\n);\n/** Court case numbers. */\nexport const caseNumberDetector: SpanDetector = fromLegacyDetector(\"case-number\", detectCaseNumber);\n/** Company registration numbers. */\nexport const companyRegistrationDetector: SpanDetector = fromLegacyDetector(\n \"company-registration\",\n detectCompanyRegistration,\n);\n\n// ---------------------------------------------------------------------------\n// Aggressive variants\n// ---------------------------------------------------------------------------\n\n/** Email addresses, including obfuscated forms such as `user [at] example [dot] com`. */\nexport const legacyEmailAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"email\",\n detectEmailAggressive,\n);\n/** Phone numbers, including seven-digit local numbers. */\nexport const phoneAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"phone\",\n detectPhoneAggressive,\n { prefilter: hasDigit },\n);\n/** US Social Security Numbers, aggressive variant. */\nexport const legacySsnAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"ssn\",\n detectSsnAggressive,\n { prefilter: hasDigit, maxMatchLength: 11 },\n);\n/** Payment card numbers, including masked forms such as `****-****-****-1234`. */\nexport const legacyCreditCardAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"credit-card\",\n detectCreditCardAggressive,\n { prefilter: hasDigit, maxMatchLength: 40 },\n);\n/** Person names, aggressive variant. */\nexport const nameAggressiveDetector: SpanDetector = fromLegacyDetector(\n \"name\",\n detectNameAggressive,\n);\n/** Vehicle identification numbers without checksum validation. */\nexport const vinAggressiveDetector: SpanDetector = fromLegacyDetector(\"vin\", detectVinAggressive);\n\n// ---------------------------------------------------------------------------\n// Registries\n// ---------------------------------------------------------------------------\n\n/**\n * Every built-in category, in the order the 1.x engine scans them.\n */\nexport const BUILTIN_CATEGORIES: readonly PiiCategory[] = Object.freeze([\n \"email\",\n \"phone\",\n \"ssn\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"iban\",\n \"date-of-birth\",\n \"name\",\n \"address\",\n \"passport\",\n \"drivers-license\",\n \"national-id\",\n \"bank-account\",\n \"cryptocurrency\",\n \"tax-id\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"api-key\",\n \"social-media\",\n \"vin\",\n \"license-plate\",\n \"tracking-number\",\n \"case-number\",\n \"company-registration\",\n] as const);\n\n/**\n * Span detectors that reproduce the 1.x detectors exactly, keyed by category.\n *\n * @example\n * ```ts\n * import { createPipeline, LEGACY_DETECTORS, redactWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: Object.values(LEGACY_DETECTORS),\n * replace: { fallback: redactWith() },\n * overlap: \"legacy\",\n * });\n * ```\n */\nexport const LEGACY_DETECTORS: Readonly<Record<PiiCategory, SpanDetector>> = Object.freeze({\n email: legacyEmailDetector,\n phone: phoneDetector,\n ssn: legacySsnDetector,\n \"credit-card\": legacyCreditCardDetector,\n ipv4: legacyIpv4Detector,\n ipv6: legacyIpv6Detector,\n url: urlDetector,\n iban: legacyIbanDetector,\n \"date-of-birth\": dateOfBirthDetector,\n name: nameDetector,\n address: addressDetector,\n passport: passportDetector,\n \"drivers-license\": driversLicenseDetector,\n \"national-id\": nationalIdDetector,\n \"bank-account\": bankAccountDetector,\n cryptocurrency: cryptocurrencyDetector,\n \"tax-id\": taxIdDetector,\n \"medical-record\": medicalRecordDetector,\n \"health-insurance\": healthInsuranceDetector,\n prescription: prescriptionDetector,\n \"api-key\": apiKeyDetector,\n \"social-media\": socialMediaDetector,\n vin: vinDetector,\n \"license-plate\": licensePlateDetector,\n \"tracking-number\": trackingNumberDetector,\n \"case-number\": caseNumberDetector,\n \"company-registration\": companyRegistrationDetector,\n});\n\n/**\n * The aggressive counterpart of {@link LEGACY_DETECTORS}: categories that have\n * an aggressive 1.x variant use it, all others use the standard detector.\n */\nexport const LEGACY_AGGRESSIVE_DETECTORS: Readonly<Record<PiiCategory, SpanDetector>> =\n Object.freeze({\n ...LEGACY_DETECTORS,\n email: legacyEmailAggressiveDetector,\n phone: phoneAggressiveDetector,\n ssn: legacySsnAggressiveDetector,\n \"credit-card\": legacyCreditCardAggressiveDetector,\n name: nameAggressiveDetector,\n vin: vinAggressiveDetector,\n });\n"]}
@@ -297,5 +297,5 @@ exports.getPreset = getPreset;
297
297
  exports.mask = mask;
298
298
  exports.pseudonymize = pseudonymize;
299
299
  exports.redact = redact;
300
- //# sourceMappingURL=chunk-IHEIYZPL.cjs.map
301
- //# sourceMappingURL=chunk-IHEIYZPL.cjs.map
300
+ //# sourceMappingURL=chunk-RJX27YEX.cjs.map
301
+ //# sourceMappingURL=chunk-RJX27YEX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/strategies/mask.ts","../src/strategies/redact.ts","../src/strategies/pseudonymize.ts","../src/strategies/generalize.ts","../src/presets.ts"],"names":["ValidationError","totalVisible","PresetNotFoundError"],"mappings":";;;;;AAoCO,SAAS,IAAA,CAAK,KAAA,EAAe,OAAA,GAAuB,EAAC,EAAW;AACrE,EAAA,MAAM,EAAE,WAAW,GAAA,EAAK,WAAA,GAAc,GAAG,YAAA,GAAe,CAAA,EAAG,cAAA,GAAiB,KAAA,EAAM,GAAI,OAAA;AAEtF,EAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACzB,IAAA,MAAM,IAAIA,iCAAA,CAAgB,UAAA,EAAY,+BAA+B,CAAA;AAAA,EACvE;AACA,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,WAAW,CAAA,IAAK,cAAc,CAAA,EAAG;AACrD,IAAA,MAAM,IAAIA,iCAAA,CAAgB,aAAA,EAAe,gCAAgC,CAAA;AAAA,EAC3E;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EAAW;AACxB,IAAA,MAAM,IAAIE,sCAAoB,IAAI,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-RJX27YEX.cjs","sourcesContent":["/**\n * @module strategies/mask\n * @description The `mask` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { MaskOptions } from \"../types.js\";\n\n/**\n * Replace interior characters of `value` with a mask character, optionally\n * keeping a number of leading and/or trailing characters visible.\n *\n * The function is deterministic and pure — given the same inputs it always\n * produces the same output.\n *\n * @param value - The string to mask.\n * @param options - Masking configuration.\n * @returns The masked string.\n *\n * @throws {@link ValidationError} When `keepLeading` or `keepTrailing` is negative.\n * @throws {@link ValidationError} When `maskChar` is not exactly one character.\n *\n * @example\n * ```ts\n * import { mask } from \"anonyma\";\n *\n * mask(\"john.doe@example.com\");\n * // \"********************\"\n *\n * mask(\"john.doe@example.com\", { keepLeading: 1, keepTrailing: 4 });\n * // \"j***************m\" (keeps \"j\" and \".com\")\n *\n * mask(\"+1 (555) 867-5309\", { keepLeading: 0, keepTrailing: 4 });\n * // \"*************5309\"\n * ```\n */\nexport function mask(value: string, options: MaskOptions = {}): string {\n const { maskChar = \"*\", keepLeading = 0, keepTrailing = 0, preserveFormat = false } = options;\n\n if (maskChar.length !== 1) {\n throw new ValidationError(\"maskChar\", \"must be exactly one character\");\n }\n if (!Number.isInteger(keepLeading) || keepLeading < 0) {\n throw new ValidationError(\"keepLeading\", \"must be a non-negative integer\");\n }\n if (!Number.isInteger(keepTrailing) || keepTrailing < 0) {\n throw new ValidationError(\"keepTrailing\", \"must be a non-negative integer\");\n }\n\n if (value.length === 0) return value;\n\n // --- Format-preserving mode ---\n // Letter → 'X' / 'x', digit → '0', separators/punctuation preserved. Letters\n // and digits of every script are masked, not only ASCII ones.\n // `keepLeading` / `keepTrailing` still apply (character counts, ignoring separators).\n if (preserveFormat) {\n const chars = Array.from(value);\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= chars.length) {\n return value; // everything is visible, nothing to mask\n }\n\n // Determine the interior slice to mask (skip leading / trailing).\n const interior = chars.slice(keepLeading, chars.length - (keepTrailing > 0 ? keepTrailing : 0));\n const maskedInterior = interior.map((ch) => {\n if (/\\p{L}/u.test(ch)) return ch !== ch.toLowerCase() ? \"X\" : \"x\";\n if (/\\p{N}/u.test(ch)) return \"0\";\n return ch; // separator / punctuation — preserved\n });\n\n return (\n chars.slice(0, keepLeading).join(\"\") +\n maskedInterior.join(\"\") +\n (keepTrailing > 0 ? chars.slice(-keepTrailing).join(\"\") : \"\")\n );\n }\n\n // --- Standard mode ---\n // When the visible region covers or exceeds the whole string, just mask everything.\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= value.length) {\n return maskChar.repeat(value.length);\n }\n\n const leading = value.slice(0, keepLeading);\n const trailing = keepTrailing > 0 ? value.slice(-keepTrailing) : \"\";\n const maskedLength = value.length - keepLeading - keepTrailing;\n\n return leading + maskChar.repeat(maskedLength) + trailing;\n}\n","/**\n * @module strategies/redact\n * @description The `redact` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { RedactOptions } from \"../types.js\";\n\n/**\n * Replace `value` entirely with a redaction label.\n *\n * @param value - The string to redact (validated but not inspected).\n * @param options - Redaction configuration.\n * @returns The redaction label.\n *\n * @throws {@link ValidationError} When `label` is an empty string.\n *\n * @example\n * ```ts\n * import { redact } from \"anonyma\";\n *\n * redact(\"john.doe@example.com\");\n * // \"[REDACTED]\"\n *\n * redact(\"123-45-6789\", { label: \"[SSN REMOVED]\" });\n * // \"[SSN REMOVED]\"\n * ```\n */\nexport function redact(value: string, options: RedactOptions = {}): string {\n const { label = \"[REDACTED]\" } = options;\n\n if (label.trim().length === 0) {\n throw new ValidationError(\"label\", \"must not be an empty string\");\n }\n\n // The value itself is not needed: whatever it is, it becomes the label.\n return label;\n}\n","/**\n * @module strategies/pseudonymize\n * @description The `pseudonymize` anonymization strategy.\n *\n * Generates a deterministic pseudonym from the input value + an optional seed.\n * The same `(value, seed)` pair always produces the same pseudonym, enabling\n * consistent replacement throughout a dataset without storing a lookup table.\n *\n * When no `seed` is provided, the pseudonym is randomly generated and is NOT\n * deterministic across calls.\n *\n * ⚠️ This strategy is NOT cryptographically secure. For strong irreversibility\n * use the `hash` strategy instead.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { PseudonymizeOptions } from \"../types.js\";\n\n/**\n * A lightweight, non-cryptographic integer hash (djb2 variant).\n * Used only for deterministic pseudonym generation.\n *\n * @internal\n */\nfunction djb2(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n // Safe: str.charCodeAt never throws for valid indices.\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n hash = hash >>> 0; // Convert to unsigned 32-bit integer\n }\n return hash;\n}\n\n/**\n * Generate a fixed-length hex string from a 32-bit integer.\n *\n * @internal\n */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Replace `value` with a deterministic (or random) pseudonym.\n *\n * @param value - The original PII value.\n * @param options - Pseudonymization configuration.\n * @returns A pseudonym string.\n *\n * @throws {@link ValidationError} When `prefix` contains whitespace or control characters.\n *\n * @example\n * ```ts\n * import { pseudonymize } from \"anonyma\";\n *\n * // Deterministic when a seed is provided:\n * pseudonymize(\"alice@example.com\", { seed: \"my-secret\" });\n * // \"id_3a7f1c2b\" (same output every time for this input+seed)\n *\n * // Random when no seed is provided:\n * pseudonymize(\"alice@example.com\");\n * // \"id_e9a3f7d1\" (different on every call)\n * ```\n */\nexport function pseudonymize(value: string, options: PseudonymizeOptions = {}): string {\n const { seed, prefix = \"id_\" } = options;\n\n if (/\\s/.test(prefix)) {\n throw new ValidationError(\"prefix\", \"must not contain whitespace characters\");\n }\n\n if (seed !== undefined) {\n // Deterministic path: mix value + seed through djb2.\n const combined = `${seed}:${value}`;\n const h1 = djb2(combined);\n const h2 = djb2(`${combined}:v2`);\n return `${prefix}${toHex8(h1)}${toHex8(h2)}`;\n }\n\n // Non-deterministic path: use crypto-quality random bytes if available.\n if (\n typeof globalThis.crypto !== \"undefined\" &&\n typeof globalThis.crypto.getRandomValues === \"function\"\n ) {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${prefix}${hex}`;\n }\n\n // Fallback for constrained environments (should not occur in Node ≥ 18).\n const fallback = Math.floor(Math.random() * 0xffffffff);\n return `${prefix}${toHex8(fallback)}`;\n}\n","/**\n * @module strategies/generalize\n * @description The `generalize` anonymization strategy.\n *\n * Replaces a precise value with a coarser, less-identifying representation.\n * Currently supports:\n * - **Numeric generalization**: bucketing a number into a range (e.g. `27` → `\"20-29\"`)\n * - **String passthrough**: non-numeric strings are returned unchanged.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { GeneralizeOptions } from \"../types.js\";\n\n/**\n * Generalize `value` by replacing exact numeric values with a range bucket.\n * Non-numeric strings are returned without modification.\n *\n * @param value - The value to generalize.\n * @param options - Generalization configuration.\n * @returns A generalized string representation.\n *\n * @throws {@link ValidationError} When `bucketSize` is not a positive integer.\n *\n * @example\n * ```ts\n * import { generalize } from \"anonyma\";\n *\n * generalize(\"27\"); // \"20-29\"\n * generalize(\"30\"); // \"30-39\"\n * generalize(\"72\"); // \"70-79\"\n * generalize(\"27\", { bucketSize: 5 }); // \"25-29\"\n * generalize(\"not-a-number\"); // \"not-a-number\" (passthrough)\n * ```\n */\nexport function generalize(value: string, options: GeneralizeOptions = {}): string {\n const { bucketSize = 10 } = options;\n\n if (!Number.isInteger(bucketSize) || bucketSize < 1) {\n throw new ValidationError(\"bucketSize\", \"must be a positive integer\");\n }\n\n const parsed = Number(value);\n\n if (!Number.isFinite(parsed)) {\n // Non-numeric value: return as-is (best-effort generalization).\n return value;\n }\n\n const n = Math.floor(parsed);\n const low = Math.floor(n / bucketSize) * bucketSize;\n const high = low + bucketSize - 1;\n\n return `${String(low)}-${String(high)}`;\n}\n","/**\n * @module presets\n * @description Built-in compliance preset configurations for GDPR, LGPD,\n * PIPEDA, CCPA/CPRA, HIPAA, PCI-DSS, SOX, and FERPA. Import from `\"anonyma\"`\n * or extend using the `preset` option in {@link AnonymizeOptions}.\n *\n * A preset selects the categories that the library can detect for an\n * instrument and the strategy applied to them. The legal provisions behind\n * each category, and the data elements each instrument names that no detector\n * covers, are documented in `\"anonyma/compliance\"`.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * // Apply HIPAA preset — redacts the Safe Harbor identifiers that have a detector\n * anonymize(text, { preset: \"hipaa\" });\n *\n * // Extend GDPR preset with API key detection (anonymize() uses the preset's categories)\n * import { compilePipeline } from \"anonyma/engine\";\n * compilePipeline({ preset: \"gdpr\", categories: [...getPreset(\"gdpr\").categories, \"api-key\"] });\n * ```\n */\n\nimport { PresetNotFoundError } from \"./errors.js\";\nimport type { CompliancePreset, PiiCategory, StrategyOptions, AnonymizationRule } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Preset definition type\n// ---------------------------------------------------------------------------\n\n/**\n * A compliance preset configuration.\n */\nexport interface PresetConfig {\n /** Display name of the preset. */\n readonly name: CompliancePreset;\n /** Description of what the preset covers. */\n readonly description: string;\n /**\n * PII categories this preset activates.\n * The anonymizer will detect and redact these categories.\n */\n readonly categories: readonly PiiCategory[];\n /**\n * Default strategy applied to all categories in this preset.\n */\n readonly defaultStrategy: StrategyOptions;\n /**\n * Per-category strategy overrides (optional).\n */\n readonly rules?: readonly AnonymizationRule[];\n}\n\n// ---------------------------------------------------------------------------\n// Individual preset definitions\n// ---------------------------------------------------------------------------\n\n/**\n * GDPR — EU General Data Protection Regulation.\n * Covers all personal data that can identify an EU natural person.\n * Default strategy: pseudonymize (allows data utility while protecting identity).\n */\nconst GDPR_PRESET: PresetConfig = {\n name: \"gdpr\",\n description:\n \"EU General Data Protection Regulation — Covers all categories of personal data \" +\n \"that can identify a natural person.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"iban\",\n \"bank-account\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"social-media\",\n \"cryptocurrency\",\n \"tax-id\",\n ],\n defaultStrategy: { strategy: \"pseudonymize\" },\n};\n\n/**\n * HIPAA — US Health Insurance Portability and Accountability Act.\n * Covers the HIPAA Safe Harbor identifiers that can be detected in text.\n * Default strategy: redact (no reconstructability).\n *\n * The 18 Safe Harbor identifiers are listed below. City, county, ZIP code,\n * dates other than birth dates, ages over 89, device identifiers, biometrics\n * and photographs have no detector and need field-level rules:\n * 1. Names, 2. Geographic data, 3. Dates (except year), 4. Phone numbers,\n * 5. Fax numbers, 6. Email addresses, 7. SSNs, 8. MRN, 9. Health plan beneficiary numbers,\n * 10. Account numbers, 11. Certificate/license numbers, 12. VINs, 13. Device identifiers,\n * 14. URLs, 15. IP addresses, 16. Biometric identifiers, 17. Full-face photos,\n * 18. Unique identifying numbers/codes (NPI, DEA, etc.)\n */\nconst HIPAA_PRESET: PresetConfig = {\n name: \"hipaa\",\n description:\n \"US HIPAA Safe Harbor — Redacts the identifiers of 45 CFR 164.514(b)(2)(i) that can be \" +\n \"detected in text. City, county, ZIP code, dates other than birth dates, ages over 89, \" +\n \"device identifiers, biometrics and photographs need field-level rules.\",\n categories: [\n \"name\",\n \"address\",\n \"date-of-birth\",\n \"phone\",\n \"email\",\n \"ssn\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"bank-account\",\n \"credit-card\",\n \"iban\",\n \"drivers-license\",\n \"passport\",\n \"vin\",\n \"license-plate\",\n \"url\",\n \"ipv4\",\n \"ipv6\",\n \"national-id\",\n \"tax-id\",\n \"social-media\",\n \"company-registration\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * CCPA — California Consumer Privacy Act.\n * Covers consumer data categories defined by CCPA.\n * Default strategy: redact.\n */\nconst CCPA_PRESET: PresetConfig = {\n name: \"ccpa\",\n description:\n \"California Consumer Privacy Act — Covers personal information categories defined \" +\n \"by CCPA, including identifiers, financial data, and online activity.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"credit-card\",\n \"tax-id\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"date-of-birth\",\n \"medical-record\",\n \"health-insurance\",\n \"api-key\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * LGPD — Lei Geral de Proteção de Dados Pessoais (Brazil, Lei nº 13.709/2018).\n * Covers dados pessoais and the identifiers that lead to dados pessoais sensíveis.\n * Default strategy: redact (anonymisation in the sense of Art. 5, XI).\n */\nconst LGPD_PRESET: PresetConfig = {\n name: \"lgpd\",\n description:\n \"Brazilian Lei Geral de Proteção de Dados — Covers personal data that identifies a \" +\n \"natural person. CPF is detected in its punctuated form; CNPJ, RG, CNH and CEP need \" +\n \"custom patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"tax-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"cryptocurrency\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"license-plate\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PIPEDA — Personal Information Protection and Electronic Documents Act (Canada).\n * Covers information about an identifiable individual.\n * Default strategy: redact.\n */\nconst PIPEDA_PRESET: PresetConfig = {\n name: \"pipeda\",\n description:\n \"Canadian PIPEDA — Covers information about an identifiable individual, including the \" +\n \"Social Insurance Number. Provincial health card numbers and postal codes need custom \" +\n \"patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"ssn\",\n \"passport\",\n \"drivers-license\",\n \"tax-id\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"social-media\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PCI-DSS — Payment Card Industry Data Security Standard.\n * Covers the card number and the cardholder data around it. Sensitive\n * authentication data (card verification codes, track data, PINs) has no\n * detector.\n * Default strategy: redact. Card and bank account numbers are masked with\n * the last 4 digits visible (industry standard).\n */\nconst PCI_DSS_PRESET: PresetConfig = {\n name: \"pci-dss\",\n description:\n \"PCI-DSS Cardholder Data — Covers credit/debit card numbers, bank accounts, \" +\n \"and associated cardholder identifiers.\",\n categories: [\"credit-card\", \"bank-account\", \"name\", \"address\", \"email\", \"phone\"],\n defaultStrategy: { strategy: \"redact\" },\n rules: [\n {\n category: \"credit-card\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n {\n category: \"bank-account\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n ],\n};\n\n/**\n * SOX — Sarbanes-Oxley Act.\n * Covers financial audit trail and corporate officer identifiers.\n * Default strategy: redact.\n */\nconst SOX_PRESET: PresetConfig = {\n name: \"sox\",\n description:\n \"Sarbanes-Oxley Act — Covers financial records, corporate officer identifiers, \" +\n \"and audit trail data.\",\n categories: [\n \"name\",\n \"email\",\n \"tax-id\",\n \"bank-account\",\n \"company-registration\",\n \"ssn\",\n \"address\",\n \"phone\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * FERPA — Family Educational Rights and Privacy Act.\n * Covers student education records.\n * Default strategy: redact.\n */\nconst FERPA_PRESET: PresetConfig = {\n name: \"ferpa\",\n description:\n \"FERPA — Covers education records and student personally identifiable information (PII).\",\n categories: [\"name\", \"email\", \"phone\", \"address\", \"date-of-birth\", \"ssn\", \"national-id\"],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n// ---------------------------------------------------------------------------\n// Registry & lookup\n// ---------------------------------------------------------------------------\n\n/** All built-in presets keyed by name. */\nexport const PRESET_REGISTRY: Readonly<Record<CompliancePreset, PresetConfig>> = {\n gdpr: GDPR_PRESET,\n lgpd: LGPD_PRESET,\n pipeda: PIPEDA_PRESET,\n hipaa: HIPAA_PRESET,\n ccpa: CCPA_PRESET,\n \"pci-dss\": PCI_DSS_PRESET,\n sox: SOX_PRESET,\n ferpa: FERPA_PRESET,\n} as const;\n\n/**\n * Get a compliance preset configuration by name.\n *\n * @param name - The preset name.\n * @returns The {@link PresetConfig} for the named preset.\n * @throws {@link PresetNotFoundError} if the preset name is not recognised.\n *\n * @example\n * ```ts\n * import { getPreset } from \"anonyma\";\n *\n * const preset = getPreset(\"hipaa\");\n * console.log(preset.categories); // [\"name\", \"address\", ...]\n * ```\n */\nexport function getPreset(name: CompliancePreset): PresetConfig {\n const preset = (PRESET_REGISTRY as Partial<Record<CompliancePreset, PresetConfig>>)[name];\n if (preset === undefined) {\n throw new PresetNotFoundError(name);\n }\n return preset;\n}\n"]}
@@ -110,5 +110,5 @@ exports.toBase32 = toBase32;
110
110
  exports.toBase64Url = toBase64Url;
111
111
  exports.toHex = toHex;
112
112
  exports.utf8 = utf8;
113
- //# sourceMappingURL=chunk-QYD4F6T7.cjs.map
114
- //# sourceMappingURL=chunk-QYD4F6T7.cjs.map
113
+ //# sourceMappingURL=chunk-ROXNQKOA.cjs.map
114
+ //# sourceMappingURL=chunk-ROXNQKOA.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/encoding.ts"],"names":[],"mappings":";;;AAOA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,IAAM,OAAA,GAAU,IAAI,WAAA,CAAY,OAAA,EAAS,EAAE,KAAA,EAAO,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,CAAA;AAEzE,IAAM,cAAA,GAAiB,wE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;AAEA,IAAM,SAAA,GAAY,kCAAA;AAOX,SAAS,QAAA,CAAS,OAAmB,KAAA,EAAuB;AACjE,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAA,GAAU,UAAU,CAAA,GAAK,IAAA;AACzB,IAAA,IAAA,IAAQ,CAAA;AACR,IAAA,OAAO,IAAA,IAAQ,CAAA,IAAK,GAAA,CAAI,MAAA,GAAS,KAAA,EAAO;AACtC,MAAA,IAAA,IAAQ,CAAA;AACR,MAAA,GAAA,IAAO,SAAA,CAAU,MAAA,CAAQ,MAAA,KAAW,IAAA,GAAQ,EAAE,CAAA;AAAA,IAChD;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,KAAA,EAAO;AAC1B,IAAA,MAAA,IAAA,CAAW,KAAK,IAAA,IAAQ,CAAA;AAAA,EAC1B;AACA,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,WAAA,CAAY,QAAgB,MAAA,EAAuB;AACjE,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,MAAM,CAAA;AACjC,EAAA,MAAA,CAAO,gBAAgB,GAAG,CAAA;AAC1B,EAAA,OAAO,GAAA;AACT","file":"chunk-QYD4F6T7.cjs","sourcesContent":["/**\n * @module internal/encoding\n * @description Byte and text encodings shared by the cryptographic modules.\n * They avoid `Buffer` so that they work in every runtime.\n * @internal\n */\n\nconst encoder = new TextEncoder();\n// `ignoreBOM` keeps a leading U+FEFF: a decoded value must equal what was encoded.\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n/** First byte of the fallback encoding of {@link encodeText}; it never starts a UTF-8 sequence. */\nconst UTF16_MARKER = 0xff;\n\n/** Bytes backed by a plain `ArrayBuffer`, as the Web Crypto API requires. */\nexport type Bytes = Uint8Array<ArrayBuffer>;\n\n/**\n * Encode a string as UTF-8.\n * @internal\n */\nexport function utf8(text: string): Bytes {\n const encoded = encoder.encode(text);\n const out = new Uint8Array(encoded.length);\n out.set(encoded);\n return out;\n}\n\n/**\n * Decode UTF-8 bytes. Returns `undefined` when the bytes are not valid UTF-8.\n * @internal\n */\nexport function fromUtf8(bytes: Uint8Array): string | undefined {\n try {\n return decoder.decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether `text` is well-formed UTF-16, that is, has no lone surrogate.\n * @internal\n */\nexport function isWellFormed(text: string): boolean {\n return !LONE_SURROGATE.test(text);\n}\n\n/**\n * Encode a string without loss. Well-formed strings become UTF-8. A string\n * with a lone surrogate, which UTF-8 cannot represent, becomes a marker byte\n * followed by its UTF-16 code units, so that different strings never share an\n * encoding.\n * @internal\n */\nexport function encodeText(text: string): Bytes {\n if (isWellFormed(text)) return utf8(text);\n const out = new Uint8Array(1 + text.length * 2);\n out[0] = UTF16_MARKER;\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n out[1 + i * 2] = unit & 0xff;\n out[2 + i * 2] = unit >>> 8;\n }\n return out;\n}\n\n/**\n * Reverse {@link encodeText}. Returns `undefined` for bytes it did not produce.\n * @internal\n */\nexport function decodeText(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== UTF16_MARKER) return fromUtf8(bytes);\n if (bytes.length % 2 !== 1) return undefined;\n let out = \"\";\n for (let i = 1; i < bytes.length; i += 2) {\n out += String.fromCharCode((bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8));\n }\n return out;\n}\n\n/**\n * Concatenate byte arrays.\n * @internal\n */\nexport function concatBytes(...parts: readonly Uint8Array[]): Bytes {\n let length = 0;\n for (const part of parts) length += part.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * Lower-case hexadecimal encoding.\n * @internal\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * URL-safe base64 without padding (RFC 4648 §5). Encodes in slices so that\n * large inputs never exceed the engine's argument limit.\n * @internal\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The URL-safe base64 alphabet, in value order. */\nconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/**\n * Decode URL-safe base64 without padding. Returns `undefined` for malformed\n * input, including input whose last character carries bits that the encoder\n * would have left at zero: every byte string has exactly one accepted text.\n * @internal\n */\nexport function fromBase64Url(text: string): Bytes | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return undefined;\n const remainder = text.length % 4;\n if (remainder !== 0) {\n const last = BASE64_ALPHABET.indexOf(text.charAt(text.length - 1));\n if ((last & (remainder === 2 ? 0b1111 : 0b11)) !== 0) return undefined;\n }\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * Crockford base32 of the first `chars * 5` bits of `bytes`. The alphabet has\n * no `I`, `L`, `O` or `U`, so identifiers survive being read aloud or retyped.\n * @internal\n */\nexport function toBase32(bytes: Uint8Array, chars: number): string {\n let out = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5 && out.length < chars) {\n bits -= 5;\n out += CROCKFORD.charAt((buffer >>> bits) & 31);\n }\n if (out.length === chars) break;\n buffer &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * `length` cryptographically random bytes.\n * @internal\n */\nexport function randomBytes(crypto: Crypto, length: number): Bytes {\n const out = new Uint8Array(length);\n crypto.getRandomValues(out);\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/encoding.ts"],"names":[],"mappings":";;;AAOA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,IAAM,OAAA,GAAU,IAAI,WAAA,CAAY,OAAA,EAAS,EAAE,KAAA,EAAO,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,CAAA;AAEzE,IAAM,cAAA,GAAiB,wEAAA;AAEvB,IAAM,YAAA,GAAe,GAAA;AASd,SAAS,KAAK,IAAA,EAAqB;AACxC,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA;AACnC,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,OAAA,CAAQ,MAAM,CAAA;AACzC,EAAA,GAAA,CAAI,IAAI,OAAO,CAAA;AACf,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,SAAS,KAAA,EAAuC;AAC9D,EAAA,IAAI;AACF,IAAA,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,SAAS,aAAa,IAAA,EAAuB;AAClD,EAAA,OAAO,CAAC,cAAA,CAAe,IAAA,CAAK,IAAI,CAAA;AAClC;AASO,SAAS,WAAW,IAAA,EAAqB;AAC9C,EAAA,IAAI,YAAA,CAAa,IAAI,CAAA,EAAG,OAAO,KAAK,IAAI,CAAA;AACxC,EAAA,MAAM,MAAM,IAAI,UAAA,CAAW,CAAA,GAAI,IAAA,CAAK,SAAS,CAAC,CAAA;AAC9C,EAAA,G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W,MAAM,CAAA;AACjC,EAAA,MAAA,CAAO,gBAAgB,GAAG,CAAA;AAC1B,EAAA,OAAO,GAAA;AACT","file":"chunk-ROXNQKOA.cjs","sourcesContent":["/**\n * @module internal/encoding\n * @description Byte and text encodings shared by the cryptographic modules.\n * They avoid `Buffer` so that they work in every runtime.\n * @internal\n */\n\nconst encoder = new TextEncoder();\n// `ignoreBOM` keeps a leading U+FEFF: a decoded value must equal what was encoded.\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n/** First byte of the fallback encoding of {@link encodeText}; it never starts a UTF-8 sequence. */\nconst UTF16_MARKER = 0xff;\n\n/** Bytes backed by a plain `ArrayBuffer`, as the Web Crypto API requires. */\nexport type Bytes = Uint8Array<ArrayBuffer>;\n\n/**\n * Encode a string as UTF-8.\n * @internal\n */\nexport function utf8(text: string): Bytes {\n const encoded = encoder.encode(text);\n const out = new Uint8Array(encoded.length);\n out.set(encoded);\n return out;\n}\n\n/**\n * Decode UTF-8 bytes. Returns `undefined` when the bytes are not valid UTF-8.\n * @internal\n */\nexport function fromUtf8(bytes: Uint8Array): string | undefined {\n try {\n return decoder.decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether `text` is well-formed UTF-16, that is, has no lone surrogate.\n * @internal\n */\nexport function isWellFormed(text: string): boolean {\n return !LONE_SURROGATE.test(text);\n}\n\n/**\n * Encode a string without loss. Well-formed strings become UTF-8. A string\n * with a lone surrogate, which UTF-8 cannot represent, becomes a marker byte\n * followed by its UTF-16 code units, so that different strings never share an\n * encoding.\n * @internal\n */\nexport function encodeText(text: string): Bytes {\n if (isWellFormed(text)) return utf8(text);\n const out = new Uint8Array(1 + text.length * 2);\n out[0] = UTF16_MARKER;\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n out[1 + i * 2] = unit & 0xff;\n out[2 + i * 2] = unit >>> 8;\n }\n return out;\n}\n\n/**\n * Reverse {@link encodeText}. Returns `undefined` for bytes it did not produce.\n * @internal\n */\nexport function decodeText(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== UTF16_MARKER) return fromUtf8(bytes);\n if (bytes.length % 2 !== 1) return undefined;\n let out = \"\";\n for (let i = 1; i < bytes.length; i += 2) {\n /* v8 ignore next -- the length is odd, so i and i + 1 are always in range */\n out += String.fromCharCode((bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8));\n }\n return out;\n}\n\n/**\n * Concatenate byte arrays.\n * @internal\n */\nexport function concatBytes(...parts: readonly Uint8Array[]): Bytes {\n let length = 0;\n for (const part of parts) length += part.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * Lower-case hexadecimal encoding.\n * @internal\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * URL-safe base64 without padding (RFC 4648 §5). Encodes in slices so that\n * large inputs never exceed the engine's argument limit.\n * @internal\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The URL-safe base64 alphabet, in value order. */\nconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/**\n * Decode URL-safe base64 without padding. Returns `undefined` for malformed\n * input, including input whose last character carries bits that the encoder\n * would have left at zero: every byte string has exactly one accepted text.\n * @internal\n */\nexport function fromBase64Url(text: string): Bytes | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return undefined;\n const remainder = text.length % 4;\n if (remainder !== 0) {\n const last = BASE64_ALPHABET.indexOf(text.charAt(text.length - 1));\n if ((last & (remainder === 2 ? 0b1111 : 0b11)) !== 0) return undefined;\n }\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * Crockford base32 of the first `chars * 5` bits of `bytes`. The alphabet has\n * no `I`, `L`, `O` or `U`, so identifiers survive being read aloud or retyped.\n * @internal\n */\nexport function toBase32(bytes: Uint8Array, chars: number): string {\n let out = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5 && out.length < chars) {\n bits -= 5;\n out += CROCKFORD.charAt((buffer >>> bits) & 31);\n }\n if (out.length === chars) break;\n buffer &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * `length` cryptographically random bytes.\n * @internal\n */\nexport function randomBytes(crypto: Crypto, length: number): Bytes {\n const out = new Uint8Array(length);\n crypto.getRandomValues(out);\n return out;\n}\n"]}