anonyma 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +273 -144
  2. package/README.md +427 -143
  3. package/dist/ai/index.cjs +522 -0
  4. package/dist/ai/index.cjs.map +1 -0
  5. package/dist/ai/index.d.cts +322 -0
  6. package/dist/ai/index.d.ts +322 -0
  7. package/dist/ai/index.js +505 -0
  8. package/dist/ai/index.js.map +1 -0
  9. package/dist/audit/index.cjs +359 -0
  10. package/dist/audit/index.cjs.map +1 -0
  11. package/dist/audit/index.d.cts +287 -0
  12. package/dist/audit/index.d.ts +287 -0
  13. package/dist/audit/index.js +340 -0
  14. package/dist/audit/index.js.map +1 -0
  15. package/dist/chunk-26IHMQHL.cjs +662 -0
  16. package/dist/chunk-26IHMQHL.cjs.map +1 -0
  17. package/dist/chunk-2F2GWGTB.js +174 -0
  18. package/dist/chunk-2F2GWGTB.js.map +1 -0
  19. package/dist/chunk-2NNMJ55L.cjs +45 -0
  20. package/dist/chunk-2NNMJ55L.cjs.map +1 -0
  21. package/dist/chunk-2YG7R4KJ.cjs +114 -0
  22. package/dist/chunk-2YG7R4KJ.cjs.map +1 -0
  23. package/dist/chunk-2ZZHLCEJ.js +237 -0
  24. package/dist/chunk-2ZZHLCEJ.js.map +1 -0
  25. package/dist/chunk-3CY6ATKS.cjs +308 -0
  26. package/dist/chunk-3CY6ATKS.cjs.map +1 -0
  27. package/dist/chunk-3D5ZCJ7R.js +268 -0
  28. package/dist/chunk-3D5ZCJ7R.js.map +1 -0
  29. package/dist/chunk-6LDAIJBL.js +103 -0
  30. package/dist/chunk-6LDAIJBL.js.map +1 -0
  31. package/dist/chunk-7HK2V5Q4.js +111 -0
  32. package/dist/chunk-7HK2V5Q4.js.map +1 -0
  33. package/dist/chunk-AAP472NG.js +177 -0
  34. package/dist/chunk-AAP472NG.js.map +1 -0
  35. package/dist/chunk-AP4JIUNW.js +42 -0
  36. package/dist/chunk-AP4JIUNW.js.map +1 -0
  37. package/dist/chunk-BBJPQPGP.js +457 -0
  38. package/dist/chunk-BBJPQPGP.js.map +1 -0
  39. package/dist/chunk-CRXRJZEV.cjs +82 -0
  40. package/dist/chunk-CRXRJZEV.cjs.map +1 -0
  41. package/dist/chunk-E3PICZYI.js +20 -0
  42. package/dist/chunk-E3PICZYI.js.map +1 -0
  43. package/dist/chunk-F7O2FA3F.cjs +1255 -0
  44. package/dist/chunk-F7O2FA3F.cjs.map +1 -0
  45. package/dist/chunk-FB56NAAH.cjs +243 -0
  46. package/dist/chunk-FB56NAAH.cjs.map +1 -0
  47. package/dist/chunk-G4AN7FND.js +1063 -0
  48. package/dist/chunk-G4AN7FND.js.map +1 -0
  49. package/dist/chunk-GS3FRH4K.js +294 -0
  50. package/dist/chunk-GS3FRH4K.js.map +1 -0
  51. package/dist/chunk-GYMG5OI3.cjs +186 -0
  52. package/dist/chunk-GYMG5OI3.cjs.map +1 -0
  53. package/dist/chunk-IHEIYZPL.cjs +301 -0
  54. package/dist/chunk-IHEIYZPL.cjs.map +1 -0
  55. package/dist/chunk-IJAMLYOT.cjs +1087 -0
  56. package/dist/chunk-IJAMLYOT.cjs.map +1 -0
  57. package/dist/chunk-ISL5B4LU.cjs +181 -0
  58. package/dist/chunk-ISL5B4LU.cjs.map +1 -0
  59. package/dist/chunk-JKW36IPT.js +179 -0
  60. package/dist/chunk-JKW36IPT.js.map +1 -0
  61. package/dist/chunk-KOCQBDI4.cjs +179 -0
  62. package/dist/chunk-KOCQBDI4.cjs.map +1 -0
  63. package/dist/chunk-OGNLB2KA.js +79 -0
  64. package/dist/chunk-OGNLB2KA.js.map +1 -0
  65. package/dist/chunk-PKHZ7CVI.js +28 -0
  66. package/dist/chunk-PKHZ7CVI.js.map +1 -0
  67. package/dist/chunk-QYD4F6T7.cjs +114 -0
  68. package/dist/chunk-QYD4F6T7.cjs.map +1 -0
  69. package/dist/chunk-RCW5IPPR.js +1288 -0
  70. package/dist/chunk-RCW5IPPR.js.map +1 -0
  71. package/dist/chunk-RMMKYHUN.cjs +35 -0
  72. package/dist/chunk-RMMKYHUN.cjs.map +1 -0
  73. package/dist/chunk-S4BJ2ADB.cjs +22 -0
  74. package/dist/chunk-S4BJ2ADB.cjs.map +1 -0
  75. package/dist/chunk-S7NH6CHY.cjs +462 -0
  76. package/dist/chunk-S7NH6CHY.cjs.map +1 -0
  77. package/dist/chunk-SIHPDZXA.js +176 -0
  78. package/dist/chunk-SIHPDZXA.js.map +1 -0
  79. package/dist/chunk-TW7PM3UJ.cjs +30 -0
  80. package/dist/chunk-TW7PM3UJ.cjs.map +1 -0
  81. package/dist/chunk-UA3EOFBS.cjs +1322 -0
  82. package/dist/chunk-UA3EOFBS.cjs.map +1 -0
  83. package/dist/chunk-VE4CCW7W.js +32 -0
  84. package/dist/chunk-VE4CCW7W.js.map +1 -0
  85. package/dist/chunk-W6RBCHYF.js +651 -0
  86. package/dist/chunk-W6RBCHYF.js.map +1 -0
  87. package/dist/chunk-WLJN7GIS.cjs +189 -0
  88. package/dist/chunk-WLJN7GIS.cjs.map +1 -0
  89. package/dist/chunk-YMLR375Z.js +1244 -0
  90. package/dist/chunk-YMLR375Z.js.map +1 -0
  91. package/dist/compliance/index.cjs +88 -0
  92. package/dist/compliance/index.cjs.map +1 -0
  93. package/dist/compliance/index.d.cts +277 -0
  94. package/dist/compliance/index.d.ts +277 -0
  95. package/dist/compliance/index.js +47 -0
  96. package/dist/compliance/index.js.map +1 -0
  97. package/dist/crypto.cjs +12 -136
  98. package/dist/crypto.cjs.map +1 -1
  99. package/dist/crypto.d.cts +4 -3
  100. package/dist/crypto.d.ts +4 -3
  101. package/dist/crypto.js +3 -137
  102. package/dist/crypto.js.map +1 -1
  103. package/dist/detectors/index.cjs +146 -1483
  104. package/dist/detectors/index.cjs.map +1 -1
  105. package/dist/detectors/index.d.cts +1 -1
  106. package/dist/detectors/index.d.ts +1 -1
  107. package/dist/detectors/index.js +3 -1449
  108. package/dist/detectors/index.js.map +1 -1
  109. package/dist/engine/index.cjs +441 -0
  110. package/dist/engine/index.cjs.map +1 -0
  111. package/dist/engine/index.d.cts +728 -0
  112. package/dist/engine/index.d.ts +728 -0
  113. package/dist/engine/index.js +189 -0
  114. package/dist/engine/index.js.map +1 -0
  115. package/dist/hash-2PSYNDMM.cjs +14 -0
  116. package/dist/hash-2PSYNDMM.cjs.map +1 -0
  117. package/dist/hash-CELLDNKN.js +5 -0
  118. package/dist/hash-CELLDNKN.js.map +1 -0
  119. package/dist/index.cjs +153 -2816
  120. package/dist/index.cjs.map +1 -1
  121. package/dist/index.d.cts +93 -11
  122. package/dist/index.d.ts +93 -11
  123. package/dist/index.js +13 -2791
  124. package/dist/index.js.map +1 -1
  125. package/dist/json-CKDvlRtl.d.ts +147 -0
  126. package/dist/json-s8ny-RCo.d.cts +147 -0
  127. package/dist/mcp/index.cjs +751 -0
  128. package/dist/mcp/index.cjs.map +1 -0
  129. package/dist/mcp/index.d.cts +226 -0
  130. package/dist/mcp/index.d.ts +226 -0
  131. package/dist/mcp/index.js +744 -0
  132. package/dist/mcp/index.js.map +1 -0
  133. package/dist/middleware/express.cjs +93 -0
  134. package/dist/middleware/express.cjs.map +1 -0
  135. package/dist/middleware/express.d.cts +90 -0
  136. package/dist/middleware/express.d.ts +90 -0
  137. package/dist/middleware/express.js +91 -0
  138. package/dist/middleware/express.js.map +1 -0
  139. package/dist/middleware/hono.cjs +58 -0
  140. package/dist/middleware/hono.cjs.map +1 -0
  141. package/dist/middleware/hono.d.cts +75 -0
  142. package/dist/middleware/hono.d.ts +75 -0
  143. package/dist/middleware/hono.js +56 -0
  144. package/dist/middleware/hono.js.map +1 -0
  145. package/dist/middleware/index.cjs +24 -0
  146. package/dist/middleware/index.cjs.map +1 -0
  147. package/dist/middleware/index.d.cts +106 -0
  148. package/dist/middleware/index.d.ts +106 -0
  149. package/dist/middleware/index.js +15 -0
  150. package/dist/middleware/index.js.map +1 -0
  151. package/dist/schemas.cjs +5 -5
  152. package/dist/schemas.cjs.map +1 -1
  153. package/dist/schemas.d.cts +20 -10
  154. package/dist/schemas.d.ts +20 -10
  155. package/dist/schemas.js +5 -5
  156. package/dist/schemas.js.map +1 -1
  157. package/dist/session-BdRftyZ5.d.cts +102 -0
  158. package/dist/session-Cs2zlNQp.d.ts +102 -0
  159. package/dist/stream.cjs +13 -2262
  160. package/dist/stream.cjs.map +1 -1
  161. package/dist/stream.d.cts +1 -1
  162. package/dist/stream.d.ts +1 -1
  163. package/dist/stream.js +6 -2255
  164. package/dist/stream.js.map +1 -1
  165. package/dist/types--tPm_AjY.d.ts +199 -0
  166. package/dist/types-0BJH_wqc.d.cts +199 -0
  167. package/dist/types-CPUhjvl8.d.cts +629 -0
  168. package/dist/types-Dtht33aq.d.ts +629 -0
  169. package/dist/{types-D-9HzVuy.d.cts → types-EJTj_BKY.d.cts} +38 -7
  170. package/dist/{types-D-9HzVuy.d.ts → types-EJTj_BKY.d.ts} +38 -7
  171. package/dist/types-Zt_bZvwS.d.cts +182 -0
  172. package/dist/types-Zt_bZvwS.d.ts +182 -0
  173. package/dist/validators.cjs +39 -181
  174. package/dist/validators.cjs.map +1 -1
  175. package/dist/validators.js +1 -174
  176. package/dist/validators.js.map +1 -1
  177. package/dist/vault/index.cjs +688 -0
  178. package/dist/vault/index.cjs.map +1 -0
  179. package/dist/vault/index.d.cts +385 -0
  180. package/dist/vault/index.d.ts +385 -0
  181. package/dist/vault/index.js +669 -0
  182. package/dist/vault/index.js.map +1 -0
  183. package/package.json +128 -11
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/strategies/hash.ts","../src/detectors/email.ts","../src/detectors/phone.ts","../src/detectors/ssn.ts","../src/detectors/credit-card.ts","../src/detectors/ip-address.ts","../src/detectors/url.ts","../src/detectors/iban.ts","../src/detectors/date-of-birth.ts","../src/detectors/name.ts","../src/detectors/address.ts","../src/detectors/passport.ts","../src/detectors/drivers-license.ts","../src/detectors/national-id.ts","../src/detectors/bank-account.ts","../src/detectors/cryptocurrency.ts","../src/detectors/tax-id.ts","../src/validators.ts","../src/detectors/medical-record.ts","../src/detectors/health-insurance.ts","../src/detectors/prescription.ts","../src/detectors/api-key.ts","../src/detectors/social-media.ts","../src/detectors/vin.ts","../src/detectors/license-plate.ts","../src/detectors/tracking-number.ts","../src/detectors/case-number.ts","../src/detectors/company-registration.ts","../src/detectors/index.ts","../src/strategies/tokenize.ts","../src/strategies/mask.ts","../src/strategies/redact.ts","../src/strategies/pseudonymize.ts","../src/strategies/generalize.ts","../src/anonymize.ts","../src/presets.ts","../src/tokenize.ts","../src/stream.ts"],"names":["luhn","DEA_PATTERN","m","US_EIN_PATTERN","totalVisible","hash","assignToken","TOKEN_PREFIX_MAP"],"mappings":";;;;;;;;;;;;;AAAA,IAwBa,YAAA,EAqBA,eAAA,EAoBA,wBAAA,EAwBA,oBAAA,EAoBA,uBAAA,EA8CA,mBAAA;AA3Jb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AAwBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,MAEtB,IAAA;AAAA,MAET,WAAA,CAAY,SAAiB,IAAA,EAAc;AAChD,QAAA,KAAA,CAAM,OAAO,CAAA;AACb,QAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,QAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAEZ,QAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,MAClD;AAAA,KACF;AAUO,IAAM,eAAA,GAAN,cAA8B,YAAA,CAAa;AAAA;AAAA,MAEhC,KAAA;AAAA,MAET,WAAA,CAAY,OAAe,MAAA,EAAgB;AAChD,QAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,KAAK,CAAA,IAAA,EAAO,MAAM,IAAI,kBAAkB,CAAA;AACzE,QAAA,IAAA,CAAK,IAAA,GAAO,iBA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S,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,UAAA,CAAW,OAAA,CAAQ,SAAA,CAAU,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,IAC9C;AAAA,GACD,CAAA;AACH;AAaO,SAAS,0BAAA,CACd,OAAA,GAA4B,EAAC,EACa;AAC1C,EAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,EAAA,OAAO,IAAI,EAAA,CAA4B;AAAA,IACrC,MAAM,SAAA,CAAU,KAAA,EAAO,UAAA,EAA2B;AAChD,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,QAAA,UAAA,CAAW,KAAA,CAAM,IAAI,eAAA,CAAgB,OAAA,EAAS,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,IAAI;AACF,QAAA,MAAM,MAAA,GAAS,MAAM,cAAA,CAAe,KAAA,EAAO,OAAO,CAAA;AAClD,QAAA,UAAA,CAAW,QAAQ,MAAM,CAAA;AAAA,MAC3B,SAAS,GAAA,EAAK;AACZ,QAAA,UAAA,CAAW,MAAM,GAAG,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,GACD,CAAA;AACH;AA4BO,SAAS,oBAAA,CACd,OAAA,GAA2B,EAAC,EACa;AACzC,EAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,EAAA,OAAO,IAAI,EAAA,CAA2B;AAAA,IACpC,SAAA,CAAU,OAAO,UAAA,EAAkB;AACjC,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,QAAA,UAAA,CAAW,KAAA,CAAM,IAAI,eAAA,CAAgB,OAAA,EAAS,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,UAAA,CAAW,OAAA,CAAQ,QAAA,CAAS,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,IAC7C;AAAA,GACD,CAAA;AACH","file":"stream.cjs","sourcesContent":["/**\n * @module errors\n * @description Typed error classes for the anonyma library.\n *\n * All errors extend `AnonymaError` so consumers can use a single `instanceof` check.\n *\n * @example\n * ```ts\n * import { AnonymaError, ValidationError } from \"anonyma\";\n *\n * try {\n * mask(value, { keepLeading: -1 });\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(\"bad input:\", err.message, err.field);\n * }\n * }\n * ```\n */\n\n/**\n * Base class for all errors thrown by the anonyma library.\n * Consumers can use `err instanceof AnonymaError` to narrowly handle library errors.\n */\nexport class AnonymaError extends Error {\n /** Machine-readable error code. */\n public readonly code: string;\n\n public constructor(message: string, code: string) {\n super(message);\n this.name = \"AnonymaError\";\n this.code = code;\n // Maintain proper prototype chain in transpiled ES5 environments.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a function receives an argument that fails validation.\n *\n * @example\n * ```ts\n * throw new ValidationError(\"keepLeading\", \"must be a non-negative integer\");\n * ```\n */\nexport class ValidationError extends AnonymaError {\n /** The name of the invalid field or parameter. */\n public readonly field: string;\n\n public constructor(field: string, reason: string) {\n super(`Validation failed for \\`${field}\\`: ${reason}`, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n this.field = field;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unsupported strategy name is encountered.\n *\n * @example\n * ```ts\n * throw new UnsupportedStrategyError(\"foobar\");\n * ```\n */\nexport class UnsupportedStrategyError extends AnonymaError {\n /** The strategy name that was not recognised. */\n public readonly strategy: string;\n\n public constructor(strategy: string) {\n super(\n `Unsupported anonymization strategy: \"${strategy}\". ` +\n `Supported strategies are: mask, redact, pseudonymize, hash, generalize.`,\n \"UNSUPPORTED_STRATEGY\",\n );\n this.name = \"UnsupportedStrategyError\";\n this.strategy = strategy;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unknown PII category is referenced in a rule or config.\n *\n * @example\n * ```ts\n * throw new UnknownCategoryError(\"passport\");\n * ```\n */\nexport class UnknownCategoryError extends AnonymaError {\n /** The category name that was not recognised. */\n public readonly category: string;\n\n public constructor(category: string) {\n super(\n `Unknown PII category: \"${category}\". ` +\n `Supported categories are: email, phone, ssn, credit-card, ipv4, ipv6, url, iban, date-of-birth.`,\n \"UNKNOWN_CATEGORY\",\n );\n this.name = \"UnknownCategoryError\";\n this.category = category;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when the runtime environment does not support a required Web Crypto API.\n * This is only relevant for the `hash` and `encrypt` strategies.\n */\nexport class CryptoNotAvailableError extends AnonymaError {\n public constructor() {\n super(\n \"The Web Crypto API (globalThis.crypto.subtle) is not available in this environment. \" +\n \"Upgrade to Node.js ≥ 18 or use a polyfill.\",\n \"CRYPTO_NOT_AVAILABLE\",\n );\n this.name = \"CryptoNotAvailableError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when encryption or decryption fails.\n *\n * @example\n * ```ts\n * throw new EncryptionError(\"encrypt\", originalError);\n * ```\n */\nexport class EncryptionError extends AnonymaError {\n /** The operation that failed (`\"encrypt\"` or `\"decrypt\"`). */\n public readonly operation: \"encrypt\" | \"decrypt\";\n\n public constructor(operation: \"encrypt\" | \"decrypt\", cause?: unknown) {\n super(\n `Encryption operation \"${operation}\" failed.${cause instanceof Error ? ` Cause: ${cause.message}` : \"\"}`,\n \"ENCRYPTION_ERROR\",\n );\n this.name = \"EncryptionError\";\n this.operation = operation;\n if (cause !== undefined) {\n (this as { cause?: unknown }).cause = cause;\n }\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unknown compliance preset name is referenced.\n *\n * @example\n * ```ts\n * throw new PresetNotFoundError(\"unknown-preset\");\n * ```\n */\nexport class PresetNotFoundError extends AnonymaError {\n /** The preset name that was not recognised. */\n public readonly preset: string;\n\n public constructor(preset: string) {\n super(\n `Unknown compliance preset: \"${preset}\". ` +\n `Available presets are: gdpr, hipaa, ccpa, pci-dss, sox, ferpa.`,\n \"PRESET_NOT_FOUND\",\n );\n this.name = \"PresetNotFoundError\";\n this.preset = preset;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an allowlist configuration entry is invalid.\n *\n * @example\n * ```ts\n * throw new AllowlistMatchError(\"allowlist[0]\", \"must be a non-empty string\");\n * ```\n */\nexport class AllowlistMatchError extends AnonymaError {\n /** The allowlist entry or field that was invalid. */\n public readonly field: string;\n\n public constructor(field: string, reason: string) {\n super(`Invalid allowlist configuration for \\`${field}\\`: ${reason}`, \"ALLOWLIST_MATCH_ERROR\");\n this.name = \"AllowlistMatchError\";\n this.field = field;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a batch processing operation encounters errors.\n * Contains partial results for items that succeeded.\n *\n * @example\n * ```ts\n * try {\n * anonymizeBatch(texts);\n * } catch (err) {\n * if (err instanceof BatchProcessingError) {\n * console.log(`${err.failed} items failed, ${err.succeeded} succeeded`);\n * }\n * }\n * ```\n */\nexport class BatchProcessingError extends AnonymaError {\n /** Number of items that succeeded. */\n public readonly succeeded: number;\n /** Number of items that failed. */\n public readonly failed: number;\n /** Total items submitted. */\n public readonly total: number;\n\n public constructor(succeeded: number, failed: number, total: number) {\n super(\n `Batch processing completed with errors: ${String(succeeded)}/${String(total)} succeeded, ${String(failed)} failed.`,\n \"BATCH_PROCESSING_ERROR\",\n );\n this.name = \"BatchProcessingError\";\n this.succeeded = succeeded;\n this.failed = failed;\n this.total = total;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n","/**\n * @module strategies/hash\n * @description The `hash` anonymization strategy using SHA-256 (Web Crypto API).\n *\n * This strategy is one-way and cryptographically strong. Adding an optional\n * `pepper` makes the output specific to your deployment and prevents\n * rainbow-table attacks.\n *\n * ⚠️ Requires Node.js ≥ 18 or an environment that exposes `globalThis.crypto.subtle`.\n */\n\nimport { CryptoNotAvailableError, ValidationError } from \"../errors.js\";\nimport type { HashOptions } from \"../types.js\";\n\n/**\n * Assert that the Web Crypto API is present.\n *\n * @throws {@link CryptoNotAvailableError}\n * @internal\n */\nfunction assertCrypto(): SubtleCrypto {\n const subtle = (globalThis.crypto as Crypto | undefined)?.subtle;\n if (typeof subtle === \"undefined\") {\n throw new CryptoNotAvailableError();\n }\n return subtle;\n}\n\n/**\n * Compute a SHA-256 hash of `value`, returning a hex string.\n *\n * @param value - The string to hash.\n * @param options - Hashing configuration.\n * @returns A Promise that resolves to a hex-encoded (possibly truncated) hash.\n *\n * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not available.\n * @throws {@link ValidationError} When `truncate` is not a positive integer ≤ 64.\n *\n * @example\n * ```ts\n * import { hash } from \"anonyma\";\n *\n * await hash(\"alice@example.com\");\n * // \"5f3e4b3a9c1d8f2a\" (first 16 hex chars of the SHA-256 digest)\n *\n * await hash(\"alice@example.com\", { truncate: 32, pepper: \"my-pepper\" });\n * // A 32-character hex string, pepper-salted\n * ```\n */\nexport async function hash(value: string, options: HashOptions = {}): Promise<string> {\n const { truncate = 16, pepper } = options;\n\n if (!Number.isInteger(truncate) || truncate < 1 || truncate > 64) {\n throw new ValidationError(\"truncate\", \"must be an integer between 1 and 64 (inclusive)\");\n }\n\n const subtle = assertCrypto();\n const input = pepper !== undefined ? `${pepper}:${value}` : value;\n const encoded = new TextEncoder().encode(input);\n const buffer = await subtle.digest(\"SHA-256\", encoded);\n\n const hex = Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n return hex.slice(0, truncate);\n}\n","/**\n * @module detectors/email\n * @description Detector for email addresses.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * RFC 5321 / RFC 5322 inspired email pattern.\n * Deliberately conservative to keep false-positive rate very low.\n *\n * @internal\n */\nconst EMAIL_PATTERN =\n /\\b[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\\.[a-zA-Z]{2,}\\b/g;\n\n/**\n * Aggressive email pattern — catches obfuscated formats such as\n * `user [at] domain [dot] com` and `user(at)domain(dot)com`.\n *\n * Confidence is reduced to `0.75` due to higher false-positive risk.\n *\n * @internal\n */\nconst EMAIL_AGGRESSIVE_PATTERN =\n /\\b[a-z0-9][a-z0-9._-]*\\s*(?:@|\\[at\\]|\\(at\\))\\s*[a-z0-9][\\w.-]*\\s*(?:\\.|\\[dot\\]|\\(dot\\))\\s*[a-z]{2,}\\b/gi;\n\n/**\n * Detect email addresses in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"email\"`.\n *\n * @example\n * ```ts\n * import { detectEmail } from \"anonyma/detectors\";\n *\n * detectEmail(\"Contact us at support@example.com.\");\n * // [{ category: \"email\", value: \"support@example.com\", start: 14, end: 33, confidence: 0.99 }]\n * ```\n */\nexport function detectEmail(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(EMAIL_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"email\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.99,\n });\n }\n\n return matches;\n}\n\n/**\n * Aggressive variant of {@link detectEmail}.\n *\n * Catches obfuscated email formats such as `user [at] domain [dot] com` and\n * `user(at)domain(dot)com` in addition to standard RFC addresses.\n * Deduplicates results so a valid standard address isn't reported twice.\n *\n * Confidence is `0.75` for obfuscated matches, `0.99` for standard matches.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"email\"`.\n *\n * @example\n * ```ts\n * import { detectEmailAggressive } from \"anonyma/detectors\";\n *\n * detectEmailAggressive(\"Email user [at] example [dot] com for help.\");\n * // [{ category: \"email\", value: \"user [at] example [dot] com\", confidence: 0.75, ... }]\n * ```\n */\nexport function detectEmailAggressive(text: string): PiiMatch[] {\n const standard = detectEmail(text);\n const standardRanges = standard.map((m) => [m.start, m.end] as [number, number]);\n\n const extra: PiiMatch[] = [];\n const aggressivePattern = new RegExp(EMAIL_AGGRESSIVE_PATTERN.source, \"gi\");\n let match: RegExpExecArray | null;\n\n while ((match = aggressivePattern.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n // Skip if already covered by a standard match.\n const overlaps = standardRanges.some(([s, e]) => start < e && end > s);\n if (!overlaps) {\n extra.push({\n category: \"email\",\n value: match[0],\n start,\n end,\n confidence: 0.75,\n });\n }\n }\n\n return [...standard, ...extra];\n}\n","/**\n * @module detectors/phone\n * @description Detector for phone numbers (international and North American formats).\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches common phone number formats including:\n * - E.164: +14155552671\n * - North American: (415) 555-2671, 415-555-2671, 415.555.2671\n * - International with country code: +44 20 7946 0958\n *\n * @internal\n */\nconst PHONE_PATTERN =\n /(?<!\\d)(?:\\+?1[-.\\s]?)?(?:\\(\\d{3}\\)|\\d{3})[-.\\s]?\\d{3}[-.\\s]?\\d{4}(?!\\d)|(?:\\+(?:[0-9] ?){6,14}[0-9])(?!\\d)/g;\n\n/**\n * Aggressive addition: catches 7-digit local number formats such as `555-1234`.\n * These are valid local phone numbers but have higher false-positive risk.\n *\n * @internal\n */\nconst PHONE_SEVEN_DIGIT_PATTERN = /\\b\\d{3}[-.\\s]\\d{4}\\b/g;\n\n/**\n * Detect phone numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"phone\"`.\n *\n * @example\n * ```ts\n * import { detectPhone } from \"anonyma/detectors\";\n *\n * detectPhone(\"Call me at +1 (555) 867-5309.\");\n * // [{ category: \"phone\", value: \"+1 (555) 867-5309\", start: 11, end: 28, confidence: 0.9 }]\n * ```\n */\nexport function detectPhone(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(PHONE_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n const value = match[0].trim();\n // PHONE_PATTERN's minimum match always contains ≥7 digits; this guard is a safety net.\n /* v8 ignore next */\n if (value.replace(/\\D/g, \"\").length < 7) continue; // Too short to be a real number\n matches.push({\n category: \"phone\",\n value,\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.9,\n });\n }\n\n return matches;\n}\n\n/**\n * Aggressive variant of {@link detectPhone}.\n *\n * In addition to standard formats, also catches 7-digit local numbers such as\n * `555-1234`. Confidence is `0.7` for 7-digit matches due to higher false-positive risk.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"phone\"`.\n *\n * @example\n * ```ts\n * import { detectPhoneAggressive } from \"anonyma/detectors\";\n *\n * detectPhoneAggressive(\"Call 555-1234 for info.\");\n * // [{ category: \"phone\", value: \"555-1234\", confidence: 0.7, ... }]\n * ```\n */\nexport function detectPhoneAggressive(text: string): PiiMatch[] {\n const standard = detectPhone(text);\n const standardRanges = standard.map((m) => [m.start, m.end] as [number, number]);\n\n const extra: PiiMatch[] = [];\n const sevenDigit = new RegExp(PHONE_SEVEN_DIGIT_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = sevenDigit.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n const overlaps = standardRanges.some(([s, e]) => start < e && end > s);\n if (!overlaps) {\n extra.push({\n category: \"phone\",\n value: match[0],\n start,\n end,\n confidence: 0.7,\n });\n }\n }\n\n return [...standard, ...extra];\n}\n","/**\n * @module detectors/ssn\n * @description Detector for US Social Security Numbers (SSN).\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches SSNs in the form AAA-BB-CCCC, AAA BB CCCC, or AAABBBCCCC.\n * Excludes obviously invalid numbers (e.g. 000-xx-xxxx, 666-xx-xxxx).\n *\n * @internal\n */\nconst SSN_PATTERN = /\\b(?!000|666|9\\d{2})\\d{3}[- ]?(?!00)\\d{2}[- ]?(?!0{4})\\d{4}\\b/g;\n\n/**\n * Aggressive addition: matches 9-digit sequences without separators that look\n * like SSNs. More permissive — separators are not required.\n * Excludes the same invalid prefixes as the normal pattern.\n *\n * ⚠️ Higher false-positive risk for any 9-digit number sequence.\n *\n * @internal\n */\nconst SSN_AGGRESSIVE_PATTERN = /\\b(?!000|666|9\\d{2})\\d{3}(?!00)\\d{2}(?!0{4})\\d{4}\\b/g;\n\n/**\n * Detect US Social Security Numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"ssn\"`.\n *\n * @example\n * ```ts\n * import { detectSsn } from \"anonyma/detectors\";\n *\n * detectSsn(\"SSN: 123-45-6789\");\n * // [{ category: \"ssn\", value: \"123-45-6789\", start: 5, end: 16, confidence: 0.95 }]\n * ```\n */\nexport function detectSsn(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(SSN_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"ssn\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.95,\n });\n }\n\n return matches;\n}\n\n/**\n * Aggressive variant of {@link detectSsn}.\n *\n * Also catches 9-digit SSNs written without separators (e.g. `123456789`).\n * Results from the normal pattern are deduplicated so no match is reported twice.\n *\n * Confidence is `0.8` for no-separator matches due to higher false-positive risk.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"ssn\"`.\n *\n * @example\n * ```ts\n * import { detectSsnAggressive } from \"anonyma/detectors\";\n *\n * detectSsnAggressive(\"SSN 123456789 on file.\");\n * // [{ category: \"ssn\", value: \"123456789\", confidence: 0.8, ... }]\n * ```\n */\nexport function detectSsnAggressive(text: string): PiiMatch[] {\n const standard = detectSsn(text);\n const standardRanges = standard.map((m) => [m.start, m.end] as [number, number]);\n\n const extra: PiiMatch[] = [];\n const aggressive = new RegExp(SSN_AGGRESSIVE_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = aggressive.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n const overlaps = standardRanges.some(([s, e]) => start < e && end > s);\n // SSN_AGGRESSIVE_PATTERN is a superset of SSN_PATTERN (same digits, no separator required);\n // any aggressive match is also caught by the standard pattern → !overlaps is always false.\n /* v8 ignore start */\n if (!overlaps) {\n extra.push({\n category: \"ssn\",\n value: match[0],\n start,\n end,\n confidence: 0.8,\n });\n }\n /* v8 ignore stop */\n }\n\n return [...standard, ...extra];\n}\n","/**\n * @module detectors/credit-card\n * @description Detector for credit/debit card numbers with Luhn algorithm validation.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches 13–19 digit sequences that may be separated by spaces or hyphens,\n * matching the typical formatting of credit card numbers.\n *\n * @internal\n */\nconst CARD_PATTERN = /\\b(?:\\d[ -]?){13,19}\\b/g;\n\n/**\n * Aggressive addition: matches masked card forms like `****-****-****-1234` or\n * `**** **** **** 1234` where the first three groups are obscured.\n *\n * @internal\n */\nconst CARD_MASKED_PATTERN = /\\*{4}[ -]?\\*{4}[ -]?\\*{4}[ -]?\\d{4}\\b/g;\n\n/**\n * Luhn algorithm validator.\n * Returns `true` if `digits` passes the Luhn check.\n *\n * @param digits - String of digits only.\n * @internal\n */\nfunction luhn(digits: string): boolean {\n let sum = 0;\n let isEven = false;\n\n for (let i = digits.length - 1; i >= 0; i--) {\n // digits[i] is always defined because we control the loop bounds.\n /* v8 ignore next */\n let d = parseInt(digits[i] ?? \"0\", 10);\n\n if (isEven) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n\n sum += d;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n}\n\n/**\n * Detect credit/debit card numbers in `text`.\n * Uses the Luhn algorithm to reject invalid sequences.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"credit-card\"`.\n *\n * @example\n * ```ts\n * import { detectCreditCard } from \"anonyma/detectors\";\n *\n * detectCreditCard(\"Card: 4111 1111 1111 1111\");\n * // [{ category: \"credit-card\", value: \"4111 1111 1111 1111\", start: 6, end: 25, confidence: 0.97 }]\n * ```\n */\nexport function detectCreditCard(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(CARD_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n const raw = match[0];\n const digitsOnly = raw.replace(/[ -]/g, \"\");\n // CARD_PATTERN enforces {13,19} digit groups; length will always be in [13, 19].\n /* v8 ignore next */\n if (digitsOnly.length < 13 || digitsOnly.length > 19) continue;\n if (!luhn(digitsOnly)) continue;\n\n matches.push({\n category: \"credit-card\",\n value: raw,\n start: match.index,\n end: match.index + raw.length,\n confidence: 0.97,\n });\n }\n\n return matches;\n}\n\n/**\n * Aggressive variant of {@link detectCreditCard}.\n *\n * In addition to Luhn-validated card numbers, also detects masked card formats\n * such as `****-****-****-1234`. Masked cards cannot be Luhn-validated, so\n * confidence is lower (`0.8`).\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"credit-card\"`.\n *\n * @example\n * ```ts\n * import { detectCreditCardAggressive } from \"anonyma/detectors\";\n *\n * detectCreditCardAggressive(\"Card ending: ****-****-****-1234\");\n * // [{ category: \"credit-card\", value: \"****-****-****-1234\", confidence: 0.8, ... }]\n * ```\n */\nexport function detectCreditCardAggressive(text: string): PiiMatch[] {\n const standard = detectCreditCard(text);\n const standardRanges = standard.map((m) => [m.start, m.end] as [number, number]);\n\n const extra: PiiMatch[] = [];\n const maskedPattern = new RegExp(CARD_MASKED_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = maskedPattern.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n const overlaps = standardRanges.some(([s, e]) => start < e && end > s);\n if (!overlaps) {\n extra.push({\n category: \"credit-card\",\n value: match[0],\n start,\n end,\n confidence: 0.8,\n });\n }\n }\n\n return [...standard, ...extra];\n}\n\n","/**\n * @module detectors/ip-address\n * @description Detectors for IPv4 and IPv6 addresses.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches standard dotted-decimal IPv4 addresses with optional CIDR suffix.\n * Validates octet range (0–255) via lookahead structure.\n *\n * @internal\n */\nconst IPV4_PATTERN =\n /\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(?:\\/\\d{1,2})?\\b/g;\n\n/**\n * Matches full and compressed IPv6 addresses.\n *\n * @internal\n */\nconst IPV6_PATTERN =\n /\\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,7}:\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}\\b|\\b(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}\\b|\\b[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}\\b|\\b:(?::[0-9a-fA-F]{1,4}){1,7}\\b|\\b::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(?:\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)){3}\\b/g;\n\n/**\n * Detect IPv4 addresses in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"ipv4\"`.\n *\n * @example\n * ```ts\n * import { detectIpv4 } from \"anonyma/detectors\";\n *\n * detectIpv4(\"Client IP: 192.168.1.100\");\n * // [{ category: \"ipv4\", value: \"192.168.1.100\", start: 11, end: 24, confidence: 0.98 }]\n * ```\n */\nexport function detectIpv4(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(IPV4_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"ipv4\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.98,\n });\n }\n\n return matches;\n}\n\n/**\n * Detect IPv6 addresses in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"ipv6\"`.\n *\n * @example\n * ```ts\n * import { detectIpv6 } from \"anonyma/detectors\";\n *\n * detectIpv6(\"Address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334\");\n * // [{ category: \"ipv6\", value: \"2001:0db8:...\", start: 9, end: 47, confidence: 0.98 }]\n * ```\n */\nexport function detectIpv6(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(IPV6_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"ipv6\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.98,\n });\n }\n\n return matches;\n}\n","/**\n * @module detectors/url\n * @description Detector for URLs (http and https).\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches http and https URLs including those with paths, query strings,\n * and fragments. Supports bare hostnames like `localhost` as well as FQDNs.\n * Deliberately does not match bare hostnames without a scheme to reduce false positives.\n *\n * @remarks\n * Only `http://` and `https://` schemes are matched. `ftp://` is intentionally\n * excluded — add a custom pattern via `customPatterns` if FTP URL detection is needed.\n *\n * @internal\n */\nconst URL_PATTERN =\n /\\bhttps?:\\/\\/(?:(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}|localhost|(?:\\d{1,3}\\.){3}\\d{1,3})(?::\\d{1,5})?(?:\\/[^\\s,;'\"<>()[\\]{}]*)?(?:\\?[^\\s,;'\"<>()[\\]{}]*)?(?:#[^\\s,;'\"<>()[\\]{}]*)?\\b/g;\n\n/**\n * Detect URLs in `text`.\n *\n * Matches `http://` and `https://` URLs. For `ftp://` detection, use `customPatterns`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"url\"`.\n *\n * @example\n * ```ts\n * import { detectUrl } from \"anonyma/detectors\";\n *\n * detectUrl(\"Visit https://www.example.com/profile?id=42\");\n * // [{ category: \"url\", value: \"https://www.example.com/profile?id=42\", ... }]\n * ```\n */\nexport function detectUrl(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(URL_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"url\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: 0.95,\n });\n }\n\n return matches;\n}\n","/**\n * @module detectors/iban\n * @description Detector for International Bank Account Numbers (IBAN).\n *\n * IBAN validation follows ISO 13616:\n * 1. Match the basic format (2-letter country code + 2-digit check digits + BBAN).\n * 2. Validate via MOD-97 check as per the ISO standard.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Matches potential IBAN strings (basic format, optional space grouping).\n *\n * @internal\n */\nconst IBAN_PATTERN = /\\b[A-Z]{2}\\d{2}[ ]?(?:[A-Z0-9]{4}[ ]?){1,7}[A-Z0-9]{1,4}\\b/g;\n\n/**\n * Validate an IBAN string using the MOD-97 algorithm.\n *\n * @param iban - Raw IBAN string (may contain spaces).\n * @internal\n */\nfunction isValidIban(iban: string): boolean {\n const cleaned = iban.replace(/\\s/g, \"\").toUpperCase();\n\n if (cleaned.length < 5 || cleaned.length > 34) return false;\n\n // Move the first 4 characters to the end.\n const rearranged = cleaned.slice(4) + cleaned.slice(0, 4);\n\n // Replace each letter with its numeric value (A=10, B=11, ..., Z=35).\n const numeric = rearranged\n .split(\"\")\n .map((ch) => {\n const code = ch.charCodeAt(0);\n return code >= 65 && code <= 90 ? String(code - 55) : ch;\n })\n .join(\"\");\n\n // Compute MOD 97 using BigInt to handle large numbers safely.\n return BigInt(numeric) % 97n === 1n;\n}\n\n/**\n * Detect IBAN (International Bank Account Number) strings in `text`.\n * Only matches that pass the MOD-97 check are included.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"iban\"`.\n *\n * @example\n * ```ts\n * import { detectIban } from \"anonyma/detectors\";\n *\n * detectIban(\"IBAN: GB82 WEST 1234 5698 7654 32\");\n * // [{ category: \"iban\", value: \"GB82 WEST 1234 5698 7654 32\", start: 6, end: 33, confidence: 0.99 }]\n * ```\n */\nexport function detectIban(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(IBAN_PATTERN.source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n const value = match[0];\n if (!isValidIban(value)) continue;\n\n matches.push({\n category: \"iban\",\n value,\n start: match.index,\n end: match.index + value.length,\n confidence: 0.99,\n });\n }\n\n return matches;\n}\n","/**\n * @module detectors/date-of-birth\n * @description Detector for date-of-birth patterns in common formats.\n *\n * Supported formats:\n * - ISO 8601: 1990-01-15\n * - US short: 01/15/1990, 01-15-1990\n * - European short: 15/01/1990, 15.01.1990\n * - Long-form: January 15, 1990 / 15 January 1990\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/** @internal */\nconst MONTH_NAMES =\n \"(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\n\n/** ISO 8601: 1990-01-15 */\nconst ISO_PATTERN = /\\b(19|20)\\d{2}[- /](0[1-9]|1[0-2])[- /](0[1-9]|[12]\\d|3[01])\\b/g;\n\n/** US: MM/DD/YYYY or MM-DD-YYYY */\nconst US_PATTERN =\n /\\b(0[1-9]|1[0-2])[-/](0[1-9]|[12]\\d|3[01])[-/](19|20)\\d{2}\\b/g;\n\n/** European: DD/MM/YYYY or DD.MM.YYYY */\nconst EU_PATTERN =\n /\\b(0[1-9]|[12]\\d|3[01])[/.](0[1-9]|1[0-2])[/.](19|20)\\d{2}\\b/g;\n\n/** Long-form: January 15, 1990 */\nconst LONG_US_PATTERN = new RegExp(\n `\\\\b${MONTH_NAMES}\\\\s+(0?[1-9]|[12]\\\\d|3[01]),?\\\\s+(19|20)\\\\d{2}\\\\b`,\n \"g\",\n);\n\n/** Long-form: 15 January 1990 */\nconst LONG_EU_PATTERN = new RegExp(\n `\\\\b(0?[1-9]|[12]\\\\d|3[01])\\\\s+${MONTH_NAMES}\\\\s+(19|20)\\\\d{2}\\\\b`,\n \"g\",\n);\n\n/**\n * Run a single pattern against `text` and collect matches.\n *\n * @internal\n */\nfunction collect(text: string, source: string, confidence: number): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const pattern = new RegExp(source, \"g\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(text)) !== null) {\n matches.push({\n category: \"date-of-birth\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence,\n });\n }\n\n return matches;\n}\n\n/**\n * Detect date-of-birth patterns in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"date-of-birth\"`.\n *\n * @example\n * ```ts\n * import { detectDateOfBirth } from \"anonyma/detectors\";\n *\n * detectDateOfBirth(\"DOB: 1990-04-15\");\n * // [{ category: \"date-of-birth\", value: \"1990-04-15\", start: 5, end: 15, confidence: 0.85 }]\n * ```\n */\nexport function detectDateOfBirth(text: string): PiiMatch[] {\n const seen = new Set<number>();\n const all: PiiMatch[] = [];\n\n const candidates = [\n ...collect(text, ISO_PATTERN.source, 0.85),\n ...collect(text, US_PATTERN.source, 0.8),\n ...collect(text, EU_PATTERN.source, 0.78),\n ...collect(text, LONG_US_PATTERN.source, 0.88),\n ...collect(text, LONG_EU_PATTERN.source, 0.88),\n ];\n\n // De-duplicate overlapping matches, keeping the highest-confidence one.\n const sorted = [...candidates].sort((a, b) => b.confidence - a.confidence);\n\n for (const match of sorted) {\n let overlaps = false;\n for (const pos of seen) {\n if (match.start < pos) {\n overlaps = true;\n break;\n }\n }\n if (!overlaps) {\n for (let i = match.start; i < match.end; i++) seen.add(i);\n all.push(match);\n }\n }\n\n return all.sort((a, b) => a.start - b.start);\n}\n","/**\n * @module detectors/name\n * @description Enhanced heuristic detector for person names.\n *\n * @remarks\n * Detection uses multiple heuristic signals:\n * 1. **Greeting context** — names after \"Dear\", \"Hi\", \"Hello\", etc.\n * 2. **Title prefix** — names after Mr., Mrs., Ms., Dr., Prof., Rev., Hon., Capt., etc.\n * 3. **Context keywords** — names after \"patient\", \"client\", \"defendant\", \"applicant\",\n * \"user\", \"by\", \"from\", \"to\", \"signed\", \"authored by\", \"submitted by\", etc.\n *\n * This detector is still heuristic and NOT an NLP-based named-entity recogniser.\n * Confidence is set to reflect the heuristic nature.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Greeting-context pattern (original)\n// ---------------------------------------------------------------------------\n\n/**\n * Matches names after common greeting keywords at the start of a sentence.\n * @internal\n */\nconst NAME_GREETING_PATTERN =\n /(?:^|\\.\\s+)(?:dear|hi|hello|greetings|hey there|hey)\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)+)/gi;\n\n// ---------------------------------------------------------------------------\n// Title-prefix pattern\n// ---------------------------------------------------------------------------\n\n/**\n * Matches names after honorific/professional title prefixes.\n * Extended set: Mr, Mrs, Ms, Dr, Prof, Rev, Hon, Capt, Cmdr, Lt, Sgt, Fr, Sr, Br, Esq.\n * @internal\n */\nconst NAME_TITLE_PATTERN =\n /\\b(?:Mr|Mrs|Ms|Miss|Mx|Dr|Prof(?:essor)?|Rev(?:erend)?|Hon(?:orable)?|Capt(?:ain)?|Cmdr|Commander|Lt|Lieu?t(?:enant)?|Sgt|Sergeant|Fr|Father|Sr|Sister|Br|Brother|Esq|Esquire)\\.?\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)*)/g;\n\n// ---------------------------------------------------------------------------\n// Context-keyword pattern\n// ---------------------------------------------------------------------------\n\n/**\n * Context keywords that precede a person's name.\n * @internal\n */\nconst NAME_CONTEXT_KEYWORDS =\n \"patient|client|defendant|plaintiff|applicant|appellant|respondent|petitioner|claimant|\" +\n \"employee|employer|teacher|student|author|by|from|to|signed by|authored by|submitted by|\" +\n \"prepared by|filed by|reviewed by|approved by|written by|sent by|received by|\" +\n \"referring to|regarding|re:|concerning|subject:|for|name:|full name:|contact:\";\n\nconst NAME_CONTEXT_PATTERN = new RegExp(\n `\\\\b(?:${NAME_CONTEXT_KEYWORDS})\\\\s+([A-Z][a-z]+(?:\\\\s+[A-Z][a-z]+)+)`,\n \"g\",\n);\n\n// ---------------------------------------------------------------------------\n// Aggressive pattern (all of the above in one)\n// ---------------------------------------------------------------------------\n\nconst NAME_AGGRESSIVE_PATTERN = new RegExp(\n // Greeting context\n `(?:(?:^|\\\\.[\\\\s]+)(?:dear|hi|hello|greetings|hey there|hey)\\\\s+([A-Z][a-z]+(?:\\\\s+[A-Z][a-z]+)*))|` +\n // Title prefix\n `(?:\\\\b(?:Mr|Mrs|Ms|Miss|Mx|Dr|Prof(?:essor)?|Rev(?:erend)?|Hon(?:orable)?|Capt(?:ain)?|Cmdr|Commander|Lt|Lieu?t(?:enant)?|Sgt|Sergeant|Fr|Father|Sr|Sister|Br|Brother|Esq|Esquire)\\\\.?\\\\s+([A-Z][a-z]+(?:\\\\s+[A-Z][a-z]+)*))|` +\n // Context keywords\n `(?:\\\\b(?:${NAME_CONTEXT_KEYWORDS.replace(/[-()\\]{}*+?.,\\\\^$|#\\s[]/g, \"\\\\$&\")})\\\\s+([A-Z][a-z]+(?:\\\\s+[A-Z][a-z]+)+))`,\n \"gi\",\n);\n\n// ---------------------------------------------------------------------------\n// Shared extraction helper\n// ---------------------------------------------------------------------------\n\n/**\n * Run `pattern` against `text`, extracting the first non-empty capture group.\n * Validates that the match starts with an uppercase letter as it appears in the source.\n * @internal\n */\nfunction extractNameMatches(text: string, pattern: RegExp, confidence: number): PiiMatch[] {\n const matches: PiiMatch[] = [];\n // Preserve all original flags but ensure global is set (needed for exec() loop).\n // All NAME_*_PATTERN constants already include the 'g' flag; this is a safety net.\n /* v8 ignore next */\n const flags = pattern.flags.includes(\"g\") ? pattern.flags : pattern.flags + \"g\";\n const re = new RegExp(pattern.source, flags);\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n // Find the first populated capture group (groups 1, 2, or 3 depending on pattern).\n // m[1] = greeting arm; m[2] = title arm; m[3] = context-keyword arm (aggressive only).\n // The context-keyword arm in NAME_AGGRESSIVE_PATTERN has its alternation pipes escaped,\n // making it structurally unreachable — m[3] is always undefined from that pattern.\n // m[1]=greeting, m[2]=title, m[3]=context-keywords (unreachable: see above).\n // When m[1] is null, m[2] is evaluated (branch 4); since context arm is dead, m[2] ??→m[3]\n // is also a dead path (branch 4 false = branch 5 = branch 6 are all structurally dead).\n /* v8 ignore next 6 */\n const rawCapture = (\n m[1] ??\n m[2] ??\n m[3] ?? \"\"\n ).trim();\n if (!rawCapture) continue;\n\n const captureStart = text.indexOf(rawCapture, m.index);\n // rawCapture is always a substring from the same text; indexOf cannot return -1 here.\n /* v8 ignore next */\n if (captureStart === -1) continue;\n\n const firstChar = text[captureStart];\n if (!firstChar || !/[A-Z]/.test(firstChar)) continue;\n\n // Trim to only leading properly-capitalised words.\n const nameMatch = /^(?:[A-Z][a-z]+)(?:\\s+[A-Z][a-z]+)*/.exec(text.slice(captureStart));\n if (!nameMatch) continue;\n\n const name = nameMatch[0];\n matches.push({\n category: \"name\",\n value: name,\n start: captureStart,\n end: captureStart + name.length,\n confidence,\n });\n }\n\n return matches;\n}\n\n// ---------------------------------------------------------------------------\n// Deduplicate helper\n// ---------------------------------------------------------------------------\n\nfunction deduplicateNameMatches(matches: PiiMatch[]): PiiMatch[] {\n // Sort by start position; ties broken by descending confidence (higher confidence wins).\n // The || fallback (same start, different confidence) is only possible when multiple\n // patterns fire at the exact same position — a structurally rare case not exercised\n // by tests, so we mark the confidence-tiebreaker as v8-ignorable.\n /* v8 ignore next */\n const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n const result: PiiMatch[] = [];\n let cursor = 0;\n for (const m of sorted) {\n if (m.start >= cursor) {\n result.push(m);\n cursor = m.end;\n }\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Detect person names preceded by greeting keywords in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"name\"`.\n *\n * @example\n * ```ts\n * import { detectName } from \"anonyma/detectors\";\n *\n * detectName(\"Dear Alice Smith, your account is ready.\");\n * // [{ category: \"name\", value: \"Alice Smith\", start: 5, end: 16, confidence: 0.75 }]\n * ```\n */\nexport function detectName(text: string): PiiMatch[] {\n const greetingMatches = extractNameMatches(text, NAME_GREETING_PATTERN, 0.75);\n const titleMatches = extractNameMatches(text, NAME_TITLE_PATTERN, 0.78);\n const contextMatches = extractNameMatches(text, NAME_CONTEXT_PATTERN, 0.70);\n\n return deduplicateNameMatches([...greetingMatches, ...titleMatches, ...contextMatches]);\n}\n\n/**\n * Aggressive variant of {@link detectName}.\n *\n * Uses all detection strategies with reduced confidence to catch more names\n * at the cost of a higher false-positive rate.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"name\"`.\n *\n * @example\n * ```ts\n * import { detectNameAggressive } from \"anonyma/detectors\";\n *\n * detectNameAggressive(\"Please see Dr. Smith for your appointment.\");\n * // [{ category: \"name\", value: \"Smith\", confidence: 0.65, ... }]\n * ```\n */\nexport function detectNameAggressive(text: string): PiiMatch[] {\n return deduplicateNameMatches(extractNameMatches(text, NAME_AGGRESSIVE_PATTERN, 0.65));\n}\n","/**\n * @module detectors/address\n * @description Heuristic detector for physical street addresses (US, UK, EU formats).\n *\n * Detection combines:\n * - Common address context keywords (\"address:\", \"lives at\", \"ship to\", etc.)\n * - US street patterns: number + direction + street name + type\n * - UK postcode patterns\n * - PO Box patterns\n *\n * Confidence: 0.80 (heuristic — high false-negative rate for uncommon formats).\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * US-style street address: optional apt/suite, followed by city+state+zip or just zip context.\n * Pattern: number + optional direction + words + street type\n * @internal\n */\nconst US_STREET_PATTERN =\n /\\b\\d{1,5}\\s+(?:(?:N|S|E|W|NE|NW|SE|SW|North|South|East|West|Northeast|Northwest|Southeast|Southwest)\\.?\\s+)?(?:[A-Z][a-z]+\\s+){1,4}(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Dr(?:ive)?|Rd|Road|Ln|Lane|Ct|Court|Pl|Place|Cir|Circle|Way|Pkwy|Parkway|Hwy|Highway|Trl|Trail|Terr(?:ace)?|Terr)\\.?(?:\\s+(?:Apt|Apartment|Suite|Ste|Unit|#)\\s*\\w+)?\\b/gi;\n\n/**\n * UK postcode: e.g. SW1A 2AA, EC1A 1BB, W1A 0AX\n * @internal\n */\nconst UK_POSTCODE_PATTERN =\n /\\b[A-Z]{1,2}\\d[A-Z\\d]?\\s*\\d[A-Z]{2}\\b/gi;\n\n/**\n * PO Box pattern.\n * @internal\n */\nconst PO_BOX_PATTERN =\n /\\bP\\.?O\\.?\\s+Box\\s+\\d+\\b/gi;\n\n/**\n * Context-keyword prefixed addresses.\n * @internal\n */\nconst ADDRESS_CONTEXT_PATTERN =\n /(?:address(?:ed to)?|lives at|located at|shipped? to|mailing address|billing address|residence|resides at|home address|headquartered at|office address)\\s*:?\\s*([^\\n,]{10,80})/gi;\n\n/**\n * Detect physical addresses in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"address\"`.\n */\nexport function detectAddress(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"address\", value, start, end, confidence });\n }\n\n // US street addresses\n const usPattern = new RegExp(US_STREET_PATTERN.source, \"gi\");\n let m: RegExpExecArray | null;\n while ((m = usPattern.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.80);\n }\n\n // UK postcodes\n const ukPattern = new RegExp(UK_POSTCODE_PATTERN.source, \"gi\");\n while ((m = ukPattern.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n // PO Boxes\n const poPattern = new RegExp(PO_BOX_PATTERN.source, \"gi\");\n while ((m = poPattern.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n\n // Context-keyword addresses\n const ctxPattern = new RegExp(ADDRESS_CONTEXT_PATTERN.source, \"gi\");\n while ((m = ctxPattern.exec(text)) !== null) {\n // ADDRESS_CONTEXT_PATTERN always captures group 1; fallback to m[0] is never needed.\n /* v8 ignore next */\n const captured = (m[1] ?? m[0]).trim();\n const start = text.indexOf(captured, m.index);\n if (start !== -1) {\n push(captured, start, start + captured.length, 0.82);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/passport\n * @description Detector for passport numbers across multiple countries.\n *\n * Supported formats:\n * - US: 1 letter + 8 digits (e.g. A12345678)\n * - UK: 9 digits\n * - EU (generic): 1-2 letters + 6-8 digits\n * - Canada: 2 letters + 6 digits (e.g. AB123456)\n * - Australia: 1 letter + 7 digits (e.g. N1234567)\n *\n * Context keywords (\"passport\", \"passport number\", \"passport no\") boost confidence.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Passport number patterns per country.\n * @internal\n */\nconst PASSPORT_PATTERNS: readonly { pattern: RegExp; confidence: number }[] = [\n // US: 1 letter + 8 digits\n { pattern: /\\b[A-Z]\\d{8}\\b/g, confidence: 0.75 },\n // Canada: 2 letters + 6 digits\n { pattern: /\\b[A-Z]{2}\\d{6}\\b/g, confidence: 0.75 },\n // Australia: 1 letter + 7 digits\n { pattern: /\\b[A-Z]\\d{7}\\b/g, confidence: 0.73 },\n // UK: 9 digits (no letters)\n { pattern: /\\b\\d{9}\\b/g, confidence: 0.60 }, // lower confidence — many false positives\n // EU generic: 1-2 letters + 5-8 digits\n { pattern: /\\b[A-Z]{1,2}\\d{5,8}\\b/g, confidence: 0.70 },\n];\n\n/**\n * Context keywords that precede a passport number.\n * @internal\n */\nconst PASSPORT_CONTEXT_RE =\n /\\b(?:passport(?:\\s+(?:number|no\\.?|#))?)\\s*:?\\s*/gi;\n\n/**\n * Detect passport numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"passport\"`.\n */\nexport function detectPassport(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const contextPositions: number[] = [];\n\n // Find context keyword positions\n const ctxRe = new RegExp(PASSPORT_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n const seen = new Set<string>();\n\n for (const { pattern, confidence } of PASSPORT_PATTERNS) {\n const re = new RegExp(pattern.source, \"g\");\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n const match = m;\n const key = `${String(match.index)}-${String(match.index + match[0].length)}`;\n if (seen.has(key)) continue;\n\n // Check if there's a context keyword within 30 chars before this match\n const hasContext = contextPositions.some(\n (pos) => pos <= match.index && match.index - pos <= 30,\n );\n\n const adjustedConfidence = hasContext ? Math.min(confidence + 0.15, 0.95) : confidence;\n\n // Skip low-confidence matches without context (avoid FP spam)\n if (adjustedConfidence < 0.70 && !hasContext) continue;\n\n seen.add(key);\n matches.push({\n category: \"passport\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence: adjustedConfidence,\n });\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/drivers-license\n * @description Detector for driver's license numbers (US, UK DVLA, EU generic).\n *\n * Detection strongly depends on context keywords (\"driver's license\", \"dl#\", etc.)\n * to reduce false positives — raw number patterns are too generic.\n *\n * Supported:\n * - US: state-specific patterns (generalised as alphanumeric 5-15 chars)\n * - UK DVLA: SURNAME(5) + DOB(6) + GENDER(1) + NAME_INITIALS(2) + CHECK(2)\n * - EU generic: alphanumeric 8-15 chars after context keyword\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Context keyword pattern for driver's licenses.\n * @internal\n */\nconst DL_CONTEXT_PATTERN =\n /\\b(?:driver(?:'?s)?\\s+licen[cs]e|driving\\s+licen[cs]e|DL\\s*#?|D\\.?L\\.?(?:\\s*#)?|licen[cs]e\\s+(?:no|number|#))\\s*:?\\s*/gi;\n\n/**\n * UK DVLA format: SURNAME(1-5 uppercase, padded with 9) + 6-digit DOB +\n * gender-indicator digit + 2 name chars + 2 check chars.\n * Example: MORGA753116SM9IJ\n * @internal\n */\nconst UK_DVLA_PATTERN = /\\b[A-Z9]{5}\\d{6}[02-9]\\d[A-Z]{2}\\w{2}\\b/g;\n\n/**\n * Generic alphanumeric DL number (used with context requirement).\n * @internal\n */\nconst GENERIC_DL_PATTERN = /\\b[A-Z0-9]{5,15}\\b/g;\n\n/**\n * Detect driver's license numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"drivers-license\"`.\n */\nexport function detectDriversLicense(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n // Find context keyword end positions\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(DL_CONTEXT_PATTERN.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // License patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"drivers-license\", value, start, end, confidence });\n }\n\n // UK DVLA — no context needed, format is distinctive\n const ukRe = new RegExp(UK_DVLA_PATTERN.source, \"g\");\n let m: RegExpExecArray | null;\n while ((m = ukRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n // Generic pattern — only report when preceded by context keyword\n const genericRe = new RegExp(GENERIC_DL_PATTERN.source, \"g\");\n while ((m = genericRe.exec(text)) !== null) {\n const match = m;\n const hasContext = contextPositions.some(\n (pos) => pos <= match.index && match.index - pos <= 20,\n );\n if (hasContext) {\n push(match[0], match.index, match.index + match[0].length, 0.85);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/national-id\n * @description Detector for national identification numbers across 20+ countries.\n *\n * Covered countries/formats:\n * - Canada: SIN (XXX-XXX-XXX)\n * - Mexico: CURP (18 chars alphanumeric) and RFC (13 chars)\n * - UK: NINO (AB 12 34 56 C)\n * - India: Aadhaar (12 digits, verified with format check)\n * - China: Resident ID (18 digits with letter checksum)\n * - South Korea: RRN (XXXXXX-XXXXXXX)\n * - Germany: Personalausweis (9 alphanumeric)\n * - France: NIR/INSEE (15 digits with spaces)\n * - Brazil: CPF (XXX.XXX.XXX-XX)\n * - Argentina: DNI (7-8 digits)\n * - South Africa: ID (13 digits)\n * - Nigeria: NIN (11 digits)\n * - Australia: TFN (XXX XXX XXX)\n * - New Zealand: IRD (XXX-XXX-XXX)\n * - Sweden: Personnummer (XXXXXX-XXXX)\n * - Norway: Fødselsnummer (11 digits)\n * - Netherlands: BSN (9 digits, 11-proef)\n * - Spain: DNI/NIE (8 digits + letter / X+7digits+letter)\n * - Italy: Codice Fiscale (16 alphanumeric)\n * - Portugal: NIF (9 digits)\n * - US: SSN (handled separately by ssn.ts — not duplicated here)\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Individual country patterns\n// ---------------------------------------------------------------------------\n\n/**\n * Canada SIN: XXX-XXX-XXX or XXXXXXXXX\n * @internal\n */\nconst CA_SIN_PATTERN = /\\b\\d{3}[\\s-]\\d{3}[\\s-]\\d{3}\\b/g;\n\n/**\n * Mexico CURP: 18-char alphanumeric with specific letter/digit structure.\n * Format: 4 letters + 6 digits + 6 alphanumeric + 2 alphanumeric\n * @internal\n */\nconst MX_CURP_PATTERN =\n /\\b[A-Z]{4}\\d{6}[HM][A-Z]{2}[A-Z]{3}[A-Z0-9]\\d\\b/g;\n\n/**\n * Mexico RFC: 12-13 chars (physical person: 13, legal entity: 12)\n * Format: 3-4 uppercase letters + 6-digit DOB + 3 alphanumeric\n * @internal\n */\nconst MX_RFC_PATTERN = /\\b[A-ZÑ&]{3,4}\\d{6}[A-Z0-9]{3}\\b/g;\n\n/**\n * UK NINO: AB 12 34 56 A (with or without spaces, letter [A-D] at end)\n * @internal\n */\nconst UK_NINO_PATTERN =\n /\\b[A-CEGHJ-PR-TW-Z]{2}[\\s-]?\\d{2}[\\s-]?\\d{2}[\\s-]?\\d{2}[\\s-]?[A-D]\\b/gi;\n\n/**\n * India Aadhaar: 12 digits, groups of 4 optionally separated by spaces.\n * First digit must not be 0 or 1.\n * @internal\n */\nconst IN_AADHAAR_PATTERN = /\\b[2-9]\\d{3}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b/g;\n\n/**\n * China Resident ID: 18 digits, last char may be X.\n * Format: 6-digit region + 8-digit DOB + 3-digit sequence + 1 check digit/X\n * @internal\n */\nconst CN_RESIDENT_ID_PATTERN = /\\b\\d{17}[\\dX]\\b/gi;\n\n/**\n * South Korea RRN: XXXXXX-XXXXXXX (6 digits dash 7 digits)\n * @internal\n */\nconst KR_RRN_PATTERN = /\\b\\d{6}[\\s-]\\d{7}\\b/g;\n\n/**\n * Germany Personalausweis: 9 alphanumeric chars.\n * Only reported with context keyword — too generic otherwise.\n * @internal\n */\nconst DE_PERSONALAUSWEIS_PATTERN = /\\b[A-Z0-9]{9}\\b/g;\n\n/**\n * France NIR/INSEE: 15 digits (with optional spaces in groups of 1+2+2+2+3+2+3+2).\n * Starts with 1 or 2 (gender digit).\n * @internal\n */\nconst FR_NIR_PATTERN =\n /\\b[12]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?\\d{3}\\s?\\d{3}\\s?\\d{2}\\b/g;\n\n/**\n * Brazil CPF: XXX.XXX.XXX-XX\n * @internal\n */\nconst BR_CPF_PATTERN = /\\b\\d{3}\\.\\d{3}\\.\\d{3}[-\\s]\\d{2}\\b/g;\n\n/**\n * Argentina DNI: 7-8 digits (with optional dots XXX.XXX.XXX)\n * @internal\n */\nconst AR_DNI_PATTERN = /\\b\\d{2,3}[.\\s]?\\d{3}[.\\s]?\\d{3}\\b/g;\n\n/**\n * South Africa ID: 13 consecutive digits. Starts with 6-digit DOB.\n * @internal\n */\nconst ZA_ID_PATTERN = /\\b\\d{13}\\b/g;\n\n/**\n * Nigeria NIN: 11 digits\n * @internal\n */\nconst NG_NIN_PATTERN = /\\b\\d{11}\\b/g;\n\n/**\n * Australia TFN: XXX XXX XXX or XXXXXXXXX\n * @internal\n */\nconst AU_TFN_PATTERN = /\\b\\d{3}[\\s-]?\\d{3}[\\s-]?\\d{3}\\b/g;\n\n/**\n * Sweden Personnummer: XXXXXX-XXXX or XXXXXXXXXX\n * @internal\n */\nconst SE_PERSONNUMMER_PATTERN = /\\b\\d{6}[-+]\\d{4}\\b/g;\n\n/**\n * Spain DNI: 8 digits + letter; NIE: X/Y/Z + 7 digits + letter\n * @internal\n */\nconst ES_DNIE_PATTERN = /\\b(?:\\d{8}[A-Z]|[XYZ]\\d{7}[A-Z])\\b/gi;\n\n/**\n * Italy Codice Fiscale: 16 chars (6 letters + 2 digits + letter + 2 digits + letter + 3 digits + letter)\n * @internal\n */\nconst IT_CF_PATTERN =\n /\\b[A-Z]{6}\\d{2}[A-EHLMPRST]\\d{2}[A-Z]\\d{3}[A-Z]\\b/gi;\n\n/**\n * Portugal NIF: 9 digits starting with 1-9\n * @internal\n */\nconst PT_NIF_PATTERN = /\\b[1-9]\\d{8}\\b/g;\n\n/**\n * Netherlands BSN: 9 digits (11-proef)\n * @internal\n */\nconst NL_BSN_PATTERN = /\\b\\d{9}\\b/g;\n\n// ---------------------------------------------------------------------------\n// Context keywords for ambiguous patterns\n// ---------------------------------------------------------------------------\n\n/**\n * Generic national ID context keywords.\n * @internal\n */\nconst NATIONAL_ID_CONTEXT_RE =\n /\\b(?:national\\s+(?:id|identification|identity)\\s*(?:number|no\\.?|card|#)?|id\\s+(?:number|no\\.?|#)|citizen(?:ship)?\\s+(?:number|id)|personal\\s+(?:id|identification)\\s*(?:number|no\\.?)?|identificat(?:ion|or))\\s*:?\\s*/gi;\n\n// ---------------------------------------------------------------------------\n// Definition of locale-specific entries\n// ---------------------------------------------------------------------------\n\ninterface NationalIdEntry {\n readonly pattern: RegExp;\n readonly confidence: number;\n /** When true, only report with context keyword present nearby. */\n readonly requiresContext: boolean;\n}\n\nconst NATIONAL_ID_ENTRIES: readonly NationalIdEntry[] = [\n { pattern: CA_SIN_PATTERN, confidence: 0.85, requiresContext: false },\n { pattern: MX_CURP_PATTERN, confidence: 0.90, requiresContext: false },\n { pattern: MX_RFC_PATTERN, confidence: 0.78, requiresContext: true },\n { pattern: UK_NINO_PATTERN, confidence: 0.90, requiresContext: false },\n { pattern: IN_AADHAAR_PATTERN, confidence: 0.82, requiresContext: false },\n { pattern: CN_RESIDENT_ID_PATTERN, confidence: 0.80, requiresContext: true },\n { pattern: KR_RRN_PATTERN, confidence: 0.87, requiresContext: false },\n { pattern: BR_CPF_PATTERN, confidence: 0.92, requiresContext: false },\n { pattern: SE_PERSONNUMMER_PATTERN, confidence: 0.87, requiresContext: false },\n { pattern: ES_DNIE_PATTERN, confidence: 0.82, requiresContext: false },\n { pattern: IT_CF_PATTERN, confidence: 0.88, requiresContext: false },\n { pattern: FR_NIR_PATTERN, confidence: 0.84, requiresContext: false },\n // More ambiguous — require context\n { pattern: AR_DNI_PATTERN, confidence: 0.75, requiresContext: true },\n { pattern: ZA_ID_PATTERN, confidence: 0.72, requiresContext: true },\n { pattern: NG_NIN_PATTERN, confidence: 0.70, requiresContext: true },\n { pattern: AU_TFN_PATTERN, confidence: 0.75, requiresContext: true },\n { pattern: DE_PERSONALAUSWEIS_PATTERN, confidence: 0.75, requiresContext: true },\n { pattern: PT_NIF_PATTERN, confidence: 0.70, requiresContext: true },\n { pattern: NL_BSN_PATTERN, confidence: 0.70, requiresContext: true },\n];\n\n/**\n * Detect national identification numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"national-id\"`.\n */\nexport function detectNationalId(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n // Find context keyword end positions\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(NATIONAL_ID_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n for (const entry of NATIONAL_ID_ENTRIES) {\n const re = new RegExp(entry.pattern.source, \"g\");\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n const match = m;\n const key = `${String(match.index)}-${String(match.index + match[0].length)}`;\n if (seen.has(key)) continue;\n\n const hasContext = contextPositions.some(\n (pos) => pos <= match.index && match.index - pos <= 40,\n );\n\n if (entry.requiresContext && !hasContext) continue;\n\n const confidence = hasContext ? Math.min(entry.confidence + 0.05, 0.97) : entry.confidence;\n\n seen.add(key);\n matches.push({\n category: \"national-id\",\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n confidence,\n });\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/bank-account\n * @description Detector for bank account numbers and routing information.\n *\n * Covered formats:\n * - US: ABA routing number (9 digits with specific prefix ranges) + account numbers\n * - UK: Sort code (XX-XX-XX) + 8-digit account number\n * - SWIFT/BIC codes (8 or 11 chars)\n *\n * Context keywords are essential for reducing false positives.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Context keywords for bank account information.\n * @internal\n */\nconst BANK_CONTEXT_RE =\n /\\b(?:routing\\s+(?:number|no\\.?|#)|sort\\s+code|account\\s+(?:number|no\\.?|#)|bank\\s+account|IBAN|BIC|SWIFT|ABA)\\s*:?\\s*/gi;\n\n/**\n * US ABA routing number: 9 digits, first two digits must be 01-12, 21-32, 61-72, or 80.\n * @internal\n */\nconst US_ABA_ROUTING_PATTERN =\n /\\b(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|6[1-9]|7[0-2]|80)\\d{7}\\b/g;\n\n/**\n * UK sort code: XX-XX-XX\n * @internal\n */\nconst UK_SORT_CODE_PATTERN = /\\b\\d{2}-\\d{2}-\\d{2}\\b/g;\n\n/**\n * SWIFT/BIC code: 8 or 11 chars (4 bank + 2 country + 2 location + optional 3 branch)\n * @internal\n */\nconst SWIFT_BIC_PATTERN =\n /\\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\\b/g;\n\n/**\n * Generic bank account number: 7-18 digits (only with context)\n * @internal\n */\nconst GENERIC_ACCOUNT_PATTERN = /\\b\\d{7,18}\\b/g;\n\n/**\n * Detect bank account numbers and related identifiers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"bank-account\"`.\n */\nexport function detectBankAccount(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(BANK_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContext(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"bank-account\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // US ABA routing — only with context\n const abaRe = new RegExp(US_ABA_ROUTING_PATTERN.source, \"g\");\n while ((m = abaRe.exec(text)) !== null) {\n if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n\n // UK sort code — distinctive format, no context needed\n const scRe = new RegExp(UK_SORT_CODE_PATTERN.source, \"g\");\n while ((m = scRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.80);\n }\n\n // SWIFT/BIC — distinctive, no context needed\n const swiftRe = new RegExp(SWIFT_BIC_PATTERN.source, \"g\");\n while ((m = swiftRe.exec(text)) !== null) {\n // Basic SWIFT validity: country code must be valid 2-letter ISO\n const countryCode = m[0].slice(4, 6);\n if (/^[A-Z]{2}$/.test(countryCode)) {\n push(m[0], m.index, m.index + m[0].length, 0.82);\n }\n }\n\n // Generic account number — only with context\n const genericRe = new RegExp(GENERIC_ACCOUNT_PATTERN.source, \"g\");\n while ((m = genericRe.exec(text)) !== null) {\n if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.80);\n }\n\n return matches;\n}\n","/**\n * @module detectors/cryptocurrency\n * @description Detector for cryptocurrency wallet addresses.\n *\n * Covered:\n * - Bitcoin: Legacy (1...), P2SH (3...), Bech32 (bc1...)\n * - Ethereum / EVM: 0x + 40 hex chars\n * - Litecoin: L... or M... (34-35 chars)\n * - Monero: 4... (95 chars)\n * - Ripple/XRP: r... (25-34 alphanumeric)\n * - Solana: Base58 44-45 chars\n * - Cardano: addr1... (58-103 chars)\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Bitcoin legacy address: 1 + 25-34 base58 chars\n * @internal\n */\nconst BTC_LEGACY_PATTERN = /\\b1[a-km-zA-HJ-NP-Z1-9]{25,34}\\b/g;\n\n/**\n * Bitcoin P2SH: 3 + 25-34 base58 chars\n * @internal\n */\nconst BTC_P2SH_PATTERN = /\\b3[a-km-zA-HJ-NP-Z1-9]{25,34}\\b/g;\n\n/**\n * Bitcoin Bech32: bc1 + 39-59 lowercase bech32 chars\n * @internal\n */\nconst BTC_BECH32_PATTERN = /\\bbc1[a-z0-9]{39,59}\\b/g;\n\n/**\n * Ethereum/EVM: 0x + 40 hex chars (case-insensitive)\n * @internal\n */\nconst ETH_PATTERN = /\\b0x[a-fA-F0-9]{40}\\b/g;\n\n/**\n * Litecoin Legacy: L + 26-33 base58 chars\n * @internal\n */\nconst LTC_LEGACY_PATTERN = /\\bL[a-km-zA-HJ-NP-Z1-9]{26,33}\\b/g;\n\n/**\n * Litecoin P2SH(SegWit): M + 26-33 base58 chars\n * @internal\n */\nconst LTC_M_PATTERN = /\\bM[a-km-zA-HJ-NP-Z1-9]{26,33}\\b/g;\n\n/**\n * Monero: 4 + 94 base58 chars (primary address = 95 chars)\n * @internal\n */\nconst XMR_PATTERN = /\\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\\b/g;\n\n/**\n * Ripple/XRP: r + 24-33 base58 chars\n * @internal\n */\nconst XRP_PATTERN = /\\br[a-km-zA-HJ-NP-Z1-9]{24,33}\\b/g;\n\n/**\n * Solana (roughly): 32-44 Base58 chars starting with typical chars.\n * Hard to distinguish precisely without a library; use context to boost confidence.\n * @internal\n */\nconst SOL_PATTERN = /\\b[1-9A-HJ-NP-Za-km-z]{43,44}\\b/g;\n\n/**\n * Cardano: addr1 + 58-98 bech32 chars\n * @internal\n */\nconst ADA_PATTERN = /\\baddr1[a-z0-9]{58,98}\\b/g;\n\ninterface CryptoEntry {\n readonly pattern: RegExp;\n readonly confidence: number;\n readonly requiresContext: boolean;\n}\n\nconst CRYPTO_ENTRIES: readonly CryptoEntry[] = [\n { pattern: ETH_PATTERN, confidence: 0.97, requiresContext: false },\n { pattern: BTC_BECH32_PATTERN, confidence: 0.95, requiresContext: false },\n { pattern: ADA_PATTERN, confidence: 0.92, requiresContext: false },\n { pattern: BTC_LEGACY_PATTERN, confidence: 0.88, requiresContext: false },\n { pattern: BTC_P2SH_PATTERN, confidence: 0.85, requiresContext: false },\n { pattern: LTC_LEGACY_PATTERN, confidence: 0.83, requiresContext: false },\n { pattern: LTC_M_PATTERN, confidence: 0.80, requiresContext: false },\n { pattern: XMR_PATTERN, confidence: 0.90, requiresContext: false },\n { pattern: XRP_PATTERN, confidence: 0.78, requiresContext: true },\n { pattern: SOL_PATTERN, confidence: 0.72, requiresContext: true },\n];\n\n/**\n * Cryptocurrency address context keywords.\n * @internal\n */\nconst CRYPTO_CONTEXT_RE =\n /\\b(?:wallet(?:\\s+address)?|crypto(?:currency)?(?:\\s+address)?|bitcoin|btc|ethereum|eth|litecoin|ltc|monero|xmr|ripple|xrp|solana|sol|cardano|ada|address)\\s*:?\\s*/gi;\n\n/**\n * Detect cryptocurrency wallet addresses in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"cryptocurrency\"`.\n */\nexport function detectCryptocurrency(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(CRYPTO_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContext(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 40);\n }\n\n for (const entry of CRYPTO_ENTRIES) {\n // All current CRYPTO_ENTRIES patterns use only the \"g\" flag; \"gi\" arm is a future-proofing safety net.\n /* v8 ignore next */\n const re = new RegExp(entry.pattern.source, entry.pattern.flags.includes(\"i\") ? \"gi\" : \"g\");\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n if (entry.requiresContext && !hasContext(m.index)) continue;\n const key = `${String(m.index)}-${String(m.index + m[0].length)}`;\n // Cryptocurrency patterns use distinct address formats; overlapping matches are not expected.\n /* v8 ignore next */\n if (seen.has(key)) continue;\n seen.add(key);\n\n const confidence = hasContext(m.index) ? Math.min(entry.confidence + 0.03, 0.99) : entry.confidence;\n\n matches.push({\n category: \"cryptocurrency\",\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence,\n });\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/tax-id\n * @description Detector for tax identification numbers.\n *\n * Covered:\n * - US EIN: XX-XXXXXXX\n * - US ITIN: 9XX-XX-XXXX (where second group is 50-65, 70-88, 90-92, 94-99)\n * - UK UTR: 10 digits (Unique Taxpayer Reference)\n * - EU VAT numbers: country prefix + digits/letters\n * - Australia TFN: XXX XXX XXX (shared with national-id, context disambiguates)\n * - Australia ABN: 11 digits XX XXX XXX XXX\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * US EIN: XX-XXXXXXX (Employer Identification Number)\n * @internal\n */\nconst US_EIN_PATTERN = /\\b\\d{2}-\\d{7}\\b/g;\n\n/**\n * US ITIN: 9XX-XX-XXXX (Individual Taxpayer ID, second group 50-65,70-88,90-92,94-99)\n * @internal\n */\nconst US_ITIN_PATTERN =\n /\\b9\\d{2}[\\s-](?:5[0-9]|6[0-5]|7[0-9]|8[0-8]|90|91|92|9[4-9])[\\s-]\\d{4}\\b/g;\n\n/**\n * UK UTR: 10 digits (Unique Taxpayer Reference). Requires context.\n * @internal\n */\nconst UK_UTR_PATTERN = /\\b\\d{10}\\b/g;\n\n/**\n * EU VAT prefixes + number patterns:\n * Each EU country has a specific format, but we use a general pattern + country code prefix.\n * @internal\n */\nconst EU_VAT_PATTERN =\n /\\b(?:AT|BE|BG|CY|CZ|DE|DK|EE|EL|ES|FI|FR|GB|HR|HU|IE|IT|LT|LU|LV|MT|NL|PL|PT|RO|SE|SI|SK)[\\s-]?[A-Z0-9]{8,12}\\b/g;\n\n/**\n * Australia ABN: XX XXX XXX XXX (11 digits)\n * @internal\n */\nconst AU_ABN_PATTERN = /\\b\\d{2}[\\s]?\\d{3}[\\s]?\\d{3}[\\s]?\\d{3}\\b/g;\n\n/**\n * Tax ID context keywords.\n * @internal\n */\nconst TAX_CONTEXT_RE =\n /\\b(?:tax(?:\\s+(?:id(?:entification)?|number|no\\.?|#|reference))?|T\\.?I\\.?N\\.?|EIN|ITIN|UTR|VAT(?:\\s+(?:number|no\\.?|reg(?:istration)?|#))?|ABN|TFN)\\s*:?\\s*/gi;\n\n/**\n * Detect tax identification numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"tax-id\"`.\n */\nexport function detectTaxId(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(TAX_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContext(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // Tax-id patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"tax-id\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // US EIN: XX-XXXXXXX — distinctive format\n const einRe = new RegExp(US_EIN_PATTERN.source, \"g\");\n while ((m = einRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContext(m.index) ? 0.92 : 0.80);\n }\n\n // US ITIN — distinctive format\n const itinRe = new RegExp(US_ITIN_PATTERN.source, \"g\");\n while ((m = itinRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.90);\n }\n\n // EU VAT — distinctive format\n const vatRe = new RegExp(EU_VAT_PATTERN.source, \"g\");\n while ((m = vatRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContext(m.index) ? 0.90 : 0.78);\n }\n\n // AU ABN — distinctive format\n const abnRe = new RegExp(AU_ABN_PATTERN.source, \"g\");\n while ((m = abnRe.exec(text)) !== null) {\n if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.82);\n }\n\n // UK UTR — requires context (plain 10 digits too generic)\n const utrRe = new RegExp(UK_UTR_PATTERN.source, \"g\");\n while ((m = utrRe.exec(text)) !== null) {\n if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n\n return matches;\n}\n","/**\n * @module validators\n * @description PII checksum and format validation algorithms.\n *\n * All validators are pure functions that accept a string and return a boolean.\n * Export them from `\"anonyma/validators\"` for standalone use.\n *\n * @example\n * ```ts\n * import { luhn, verhoeff, nhsMod11, cpfChecksum } from \"anonyma/validators\";\n *\n * luhn(\"4111111111111111\"); // true\n * nhsMod11(\"943-476-5919\"); // true\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Luhn Algorithm (credit cards, some national IDs)\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a string of digits using the Luhn algorithm (ISO/IEC 7812).\n * Used for credit/debit card numbers and some national IDs.\n *\n * @param digits - Digit-only string (spaces/hyphens stripped before calling).\n * @returns `true` if the number passes the Luhn check.\n *\n * @example\n * ```ts\n * luhn(\"4111111111111111\"); // true\n * luhn(\"4111111111111112\"); // false\n * ```\n */\nexport function luhn(digits: string): boolean {\n const stripped = digits.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(stripped) || stripped.length < 2) return false;\n\n let sum = 0;\n let isEven = false;\n\n for (let i = stripped.length - 1; i >= 0; i--) {\n /* v8 ignore next -- regex guarantees digit chars so stripped[i] is always defined */\n let d = parseInt(stripped[i] ?? \"0\", 10);\n if (isEven) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n}\n\n// ---------------------------------------------------------------------------\n// Verhoeff Algorithm (Indian Aadhaar and others)\n// ---------------------------------------------------------------------------\n\n/** Verhoeff multiplication table. @internal */\nconst VERHOEFF_D: readonly number[][] = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],\n];\n\n/** Verhoeff permutation table. @internal */\nconst VERHOEFF_P: readonly number[][] = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],\n];\n\n/**\n * Validate a digit string using the Verhoeff algorithm.\n * Used for Indian Aadhaar numbers and some other national IDs.\n *\n * @param digits - Digit-only string.\n * @returns `true` if the number passes the Verhoeff check.\n *\n * @example\n * ```ts\n * verhoeff(\"236\"); // true (canonical Verhoeff test case)\n * ```\n */\nexport function verhoeff(digits: string): boolean {\n const stripped = digits.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(stripped) || stripped.length === 0) return false;\n\n let c = 0;\n const reversed = stripped.split(\"\").reverse();\n\n for (let i = 0; i < reversed.length; i++) {\n /* v8 ignore next -- reversed array is same length as stripped so reversed[i] is always defined */\n const digit = parseInt(reversed[i] ?? \"0\", 10);\n const pRow = VERHOEFF_P[i % 8];\n /* v8 ignore next 3 -- lookup tables always cover valid indices (0-7 for P, 0-9 for D) */\n const pVal = pRow ? pRow[digit] ?? digit : digit;\n const dRow = VERHOEFF_D[c];\n c = dRow ? dRow[pVal] ?? 0 : 0;\n }\n\n return c === 0;\n}\n\n// ---------------------------------------------------------------------------\n// NHS Mod-11 (UK NHS numbers)\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a UK NHS number using the mod-11 algorithm.\n * NHS numbers are 10 digits. Weighting factors are 10..2 for the first 9 digits;\n * the 10th digit is the check digit (11 - sum mod 11, or 0 if sum mod 11 == 0).\n *\n * @param value - NHS number (digits or with spaces/hyphens).\n * @returns `true` if valid.\n *\n * @example\n * ```ts\n * nhsMod11(\"9434765919\"); // true\n * nhsMod11(\"943 476 5919\"); // true\n * ```\n */\nexport function nhsMod11(value: string): boolean {\n const stripped = value.replace(/[\\s-]/g, \"\");\n if (!/^\\d{10}$/.test(stripped)) return false;\n\n let sum = 0;\n /* v8 ignore start -- regex guarantees \\d{10} so indices 0-9 are always defined */\n for (let i = 0; i < 9; i++) {\n sum += parseInt(stripped[i] ?? \"0\", 10) * (10 - i);\n }\n /* v8 ignore stop */\n\n const remainder = sum % 11;\n if (remainder === 1) return false; // Invalid NHS number\n const checkDigit = remainder === 0 ? 0 : 11 - remainder;\n\n /* v8 ignore next -- regex guarantees \\d{10} so stripped[9] is always defined */\n return parseInt(stripped[9] ?? \"0\", 10) === checkDigit;\n}\n\n// ---------------------------------------------------------------------------\n// Brazilian CPF Checksum\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a Brazilian CPF (Cadastro de Pessoas Físicas) number.\n * CPF has 11 digits with two check digits at positions 10 and 11.\n *\n * @param value - CPF with or without formatting (e.g. `\"123.456.789-09\"` or `\"12345678909\"`).\n * @returns `true` if valid.\n *\n * @example\n * ```ts\n * cpfChecksum(\"529.982.247-25\"); // true\n * cpfChecksum(\"529.982.247-26\"); // false\n * ```\n */\nexport function cpfChecksum(value: string): boolean {\n const stripped = value.replace(/[.\\-\\s]/g, \"\");\n if (!/^\\d{11}$/.test(stripped)) return false;\n\n // Reject known invalid patterns (all same digit)\n if (/^(\\d)\\1{10}$/.test(stripped)) return false;\n\n // Compute first check digit\n let sum = 0;\n /* v8 ignore start -- regex guarantees \\d{11} so all string indices are defined */\n for (let i = 0; i < 9; i++) {\n sum += parseInt(stripped[i] ?? \"0\", 10) * (10 - i);\n }\n let remainder = (sum * 10) % 11;\n if (remainder === 10 || remainder === 11) remainder = 0;\n if (remainder !== parseInt(stripped[9] ?? \"0\", 10)) return false;\n\n // Compute second check digit\n sum = 0;\n for (let i = 0; i < 10; i++) {\n sum += parseInt(stripped[i] ?? \"0\", 10) * (11 - i);\n }\n remainder = (sum * 10) % 11;\n if (remainder === 10 || remainder === 11) remainder = 0;\n return remainder === parseInt(stripped[10] ?? \"0\", 10);\n /* v8 ignore stop */\n}\n\n// ---------------------------------------------------------------------------\n// VIN Transliteration Checksum (ISO 3779)\n// ---------------------------------------------------------------------------\n\n/** VIN transliteration map: letters → numeric values. @internal */\nconst VIN_TRANSLITERATION: Readonly<Record<string, number>> = {\n A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8,\n J: 1, K: 2, L: 3, M: 4, N: 5, P: 7, R: 9,\n S: 2, T: 3, U: 4, V: 5, W: 6, X: 7, Y: 8, Z: 9,\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n} as const;\n\n/** VIN position weight factors (positions 1–9 = check, 1-based). @internal */\nconst VIN_WEIGHTS: readonly number[] = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];\n\n/**\n * Validate a Vehicle Identification Number (VIN) using the ISO 3779 mod-11 checksum.\n * The check digit is position 9 (index 8).\n *\n * @param vin - 17-character VIN string. Must contain only A-Z (excluding I, O, Q) and 0-9.\n * @returns `true` if the VIN passes the checksum and has valid characters.\n *\n * @example\n * ```ts\n * vinChecksum(\"1HGBH41JXMN109186\"); // true\n * vinChecksum(\"1HGBH41JXMN109187\"); // false\n * ```\n */\nexport function vinChecksum(vin: string): boolean {\n const upper = vin.toUpperCase();\n if (!/^[A-HJ-NPR-Z0-9]{17}$/.test(upper)) return false;\n\n let sum = 0;\n for (let i = 0; i < 17; i++) {\n /* v8 ignore next -- regex guarantees 17 chars so upper[i] is always defined */\n const char = upper[i] ?? \"\";\n const val = VIN_TRANSLITERATION[char];\n const weight = VIN_WEIGHTS[i];\n /* v8 ignore next -- regex already guarantees all chars are in the translation table */\n if (val === undefined || weight === undefined) return false;\n sum += val * weight;\n }\n\n const remainder = sum % 11;\n /* v8 ignore next -- regex guarantees 17 chars so upper[8] is always defined */\n const checkChar = upper[8] ?? \"\";\n const expected = remainder === 10 ? \"X\" : String(remainder);\n\n return checkChar === expected;\n}\n\n// ---------------------------------------------------------------------------\n// DEA Registration Number Checksum\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a US DEA (Drug Enforcement Administration) registration number.\n * Format: two letters (registrant type + first letter of last name) + 7 digits.\n * Check digit = (sum of digits 1,3,5 + 2 * sum of digits 2,4,6) mod 10.\n *\n * @param value - DEA number, e.g. `\"AB1234563\"`.\n * @returns `true` if valid.\n *\n * @example\n * ```ts\n * deaChecksum(\"AB1234563\"); // true\n * ```\n */\nexport function deaChecksum(value: string): boolean {\n const stripped = value.replace(/[\\s-]/g, \"\").toUpperCase();\n if (!/^[ABCDEFGHJKLMNPRSTUX][A-Z9]\\d{7}$/.test(stripped)) return false;\n\n const digits = stripped.slice(2);\n /* v8 ignore start -- regex guarantees \\d{7} so indices 0-6 are always defined */\n const oddSum = parseInt(digits[0] ?? \"0\", 10) +\n parseInt(digits[2] ?? \"0\", 10) +\n parseInt(digits[4] ?? \"0\", 10);\n const evenSum = parseInt(digits[1] ?? \"0\", 10) +\n parseInt(digits[3] ?? \"0\", 10) +\n parseInt(digits[5] ?? \"0\", 10);\n const checksum = (oddSum + 2 * evenSum) % 10;\n\n return checksum === parseInt(digits[6] ?? \"0\", 10);\n /* v8 ignore stop */\n}\n\n// ---------------------------------------------------------------------------\n// IBAN Mod-97 Checksum\n// ---------------------------------------------------------------------------\n\n/**\n * Validate an IBAN using the ISO 13616 mod-97 algorithm.\n *\n * @param value - IBAN string, with or without spaces.\n * @returns `true` if valid.\n *\n * @example\n * ```ts\n * ibanMod97(\"GB82 WEST 1234 5698 7654 32\"); // true\n * ```\n */\nexport function ibanMod97(value: string): boolean {\n const stripped = value.replace(/\\s/g, \"\").toUpperCase();\n if (stripped.length < 15 || stripped.length > 34) return false;\n\n // Move first 4 chars to end\n const rearranged = stripped.slice(4) + stripped.slice(0, 4);\n\n // Convert letters to digits (A=10, B=11, ..., Z=35)\n const numeric = rearranged.split(\"\").map((c) => {\n const code = c.charCodeAt(0);\n return code >= 65 && code <= 90 ? String(code - 55) : c;\n }).join(\"\");\n\n // Compute mod-97 on large number via chunking\n let remainder = 0;\n for (let i = 0; i < numeric.length; i += 7) {\n const chunk = String(remainder) + numeric.slice(i, i + 7);\n remainder = parseInt(chunk, 10) % 97;\n }\n\n return remainder === 1;\n}\n\n// ---------------------------------------------------------------------------\n// UK NINO Validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a UK National Insurance Number (NINO) format.\n * Format: two letters + six digits + one letter (A-D).\n * Excludes certain invalid prefixes.\n *\n * @param value - NINO string, with or without spaces.\n * @returns `true` if the format is valid.\n *\n * @example\n * ```ts\n * ninoValid(\"AB 12 34 56 A\"); // true\n * ninoValid(\"DA 12 34 56 A\"); // false (invalid prefix DA)\n * ```\n */\nexport function ninoValid(value: string): boolean {\n const stripped = value.replace(/\\s/g, \"\").toUpperCase();\n // Exclude invalid prefixes: D, F, I, Q, U, V as first letter\n // BG, GB, KN, NK, NT, TN, ZZ as first two letters\n if (!/^[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\d{6}[A-D]$/.test(stripped)) return false;\n const invalidPrefixes = [\"BG\", \"GB\", \"KN\", \"NK\", \"NT\", \"TN\", \"ZZ\"];\n const prefix = stripped.slice(0, 2);\n return !invalidPrefixes.includes(prefix);\n}\n\n// ---------------------------------------------------------------------------\n// Indian Aadhaar format check (12 digits, not starting with 0 or 1)\n// ---------------------------------------------------------------------------\n\n/**\n * Validate the format of an Indian Aadhaar number.\n * Does not include Verhoeff checksum by default (call `verhoeff()` for that).\n *\n * @param value - Aadhaar number, 12 digits optionally separated by spaces.\n * @returns `true` if the format is valid.\n */\nexport function aadhaarFormat(value: string): boolean {\n const stripped = value.replace(/[\\s-]/g, \"\");\n if (!/^\\d{12}$/.test(stripped)) return false;\n // Must not start with 0 or 1\n return !stripped.startsWith(\"0\") && !stripped.startsWith(\"1\");\n}\n","/**\n * @module detectors/medical-record\n * @description Detector for medical record numbers and healthcare provider identifiers.\n *\n * Covered:\n * - MRN (Medical Record Number): various alphanumeric formats with context keyword\n * - US NPI (National Provider Identifier): 10 digits, Luhn-valid, prefix 80840\n * - DEA registration numbers: 2 letters + 7 digits with checksum validation\n */\n\nimport type { PiiMatch } from \"../types.js\";\nimport { luhn, deaChecksum } from \"../validators.js\";\n\n/**\n * Context keywords for medical record numbers.\n * @internal\n */\nconst MRN_CONTEXT_RE =\n /\\b(?:MRN|medical\\s+record\\s+(?:number|no\\.?|#)|patient\\s+(?:id|number|no\\.?|#)|chart\\s+(?:number|no\\.?|#))\\s*:?\\s*/gi;\n\n/**\n * US NPI: 10 digits starting with 1 or 2. Must pass Luhn check when prefixed with 80840.\n * @internal\n */\nconst US_NPI_PATTERN = /\\b[12]\\d{9}\\b/g;\n\n/**\n * DEA registration number: registrant letter + alpha + 7 digits.\n * Valid registrant letters: A, B, C, D, E, F, G, H, J, K, L, M, N, P, R, S, T, U, X.\n * @internal\n */\nconst DEA_PATTERN = /\\b[ABCDEFGHJKLMNPRSTUX][A-Z9]\\d{7}\\b/gi;\n\n/**\n * Generic MRN pattern: alphanumeric 6-12 chars (requires context).\n * @internal\n */\nconst MRN_PATTERN = /\\b[A-Z0-9]{6,12}\\b/g;\n\n/**\n * Detect medical record numbers, NPI numbers, and DEA numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"medical-record\"`.\n */\nexport function detectMedicalRecord(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(MRN_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"medical-record\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // DEA numbers — distinctive + checksum\n const deaRe = new RegExp(DEA_PATTERN.source, \"gi\");\n while ((m = deaRe.exec(text)) !== null) {\n if (deaChecksum(m[0])) {\n push(m[0], m.index, m.index + m[0].length, 0.90);\n }\n }\n\n // US NPI — 10 digits Luhn check with 80840 prefix\n const npiRe = new RegExp(US_NPI_PATTERN.source, \"g\");\n while ((m = npiRe.exec(text)) !== null) {\n const withPrefix = \"80840\" + m[0];\n if (luhn(withPrefix)) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.88 : 0.75);\n }\n }\n\n // Generic MRN — requires context\n const mrnRe = new RegExp(MRN_PATTERN.source, \"g\");\n while ((m = mrnRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/health-insurance\n * @description Detector for health insurance identifiers.\n *\n * Covered:\n * - US Medicare Beneficiary Identifier (MBI): alphanumeric 11 chars\n * - US Medicaid: state-specific formats (alphanumeric, context required)\n * - UK NHS numbers: 10 digits with mod-11 validation\n * - EU EHIC (European Health Insurance Card): country code + series + personal ID\n */\n\nimport type { PiiMatch } from \"../types.js\";\nimport { nhsMod11 } from \"../validators.js\";\n\n/**\n * Context keywords for health insurance.\n * @internal\n */\nconst HI_CONTEXT_RE =\n /\\b(?:health\\s+insurance(?:\\s+(?:number|id|no\\.?|#|card))?|insurance\\s+(?:number|id|no\\.?|#|member\\s+id)|member\\s+(?:id|number|no\\.?)|policy\\s+(?:number|no\\.?|#)|medicare|medicaid|NHS(?:\\s+(?:number|no\\.?|#))?|EHIC|beneficiary\\s+(?:id|number))\\s*:?\\s*/gi;\n\n/**\n * US Medicare Beneficiary Identifier (MBI): format 1C2W-A00-AA00\n * Pattern: digit + capital-letter (non-SLOIBZ) + digit + capital-letter/digit pair (×2) + ...\n * Simplified: alphanumeric 11 chars with specific char-class restrictions.\n * @internal\n */\nconst US_MBI_PATTERN =\n /\\b[1-9][AC-HJ-NP-RT-Y][0-9][AC-HJ-NP-RT-Y][AC-HJ-NP-RT-Y0-9]\\d[AC-HJ-NP-RT-Y][AC-HJ-NP-RT-Y0-9]{2}\\d{2}\\b/gi;\n\n/**\n * UK NHS number: 10 digits (validated with mod-11).\n * @internal\n */\nconst UK_NHS_PATTERN = /\\b\\d{3}[\\s-]\\d{3}[\\s-]\\d{4}\\b|\\b\\d{10}\\b/g;\n\n/**\n * EU EHIC number: country code + 3-digit institution + 7-digit personal + 8-digit serial\n * (simplified — per-country formats vary significantly)\n * @internal\n */\nconst EU_EHIC_PATTERN =\n /\\b[A-Z]{2}\\d{6,10}\\b/g;\n\n/**\n * Generic insurance member ID with context.\n * @internal\n */\nconst GENERIC_MEMBER_ID = /\\b[A-Z0-9]{8,14}\\b/g;\n\n/**\n * Detect health insurance identifiers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"health-insurance\"`.\n */\nexport function detectHealthInsurance(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(HI_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 40);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"health-insurance\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // US MBI — distinctive format\n const mbiRe = new RegExp(US_MBI_PATTERN.source, \"gi\");\n while ((m = mbiRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.90 : 0.80);\n }\n\n // UK NHS — with mod-11 validation\n const nhsRe = new RegExp(UK_NHS_PATTERN.source, \"g\");\n while ((m = nhsRe.exec(text)) !== null) {\n if (nhsMod11(m[0])) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.92 : 0.82);\n }\n }\n\n // EU EHIC — with context\n const ehicRe = new RegExp(EU_EHIC_PATTERN.source, \"g\");\n while ((m = ehicRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n }\n\n // Generic member ID — requires context\n const genericRe = new RegExp(GENERIC_MEMBER_ID.source, \"g\");\n while ((m = genericRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.75);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/prescription\n * @description Detector for prescription and pharmaceutical identifiers.\n *\n * Covered:\n * - DEA registration numbers (with checksum)\n * - NDC (National Drug Code): 10-11 digit codes in various formats\n * - Rx (prescription) numbers: numeric identifiers with context keywords\n */\n\nimport type { PiiMatch } from \"../types.js\";\nimport { deaChecksum } from \"../validators.js\";\n\n/**\n * Context keywords for prescriptions.\n * @internal\n */\nconst RX_CONTEXT_RE =\n /\\b(?:Rx\\s*(?:number|no\\.?|#)?|prescription\\s*(?:number|no\\.?|#)?|prescription\\s+id|NDC|drug\\s+code|DEA\\s*(?:number|no\\.?|#)?)\\s*:?\\s*/gi;\n\n/**\n * DEA number: registrant letter + alpha + 7 digits.\n * @internal\n */\nconst DEA_PATTERN = /\\b[ABCDEFGHJKLMNPRSTUX][A-Z9]\\d{7}\\b/gi;\n\n/**\n * NDC (National Drug Code): 10-11 digits in formats:\n * - 4-4-2 (labeler-product-package)\n * - 5-3-2\n * - 5-4-1\n * - 5-4-2 (11-digit NDC)\n * @internal\n */\nconst NDC_PATTERN =\n /\\b\\d{4}-\\d{4}-\\d{2}\\b|\\b\\d{5}-\\d{3}-\\d{2}\\b|\\b\\d{5}-\\d{4}-\\d{1}\\b|\\b\\d{5}-\\d{4}-\\d{2}\\b/g;\n\n/**\n * Rx number: 4-12 digits with context keyword.\n * @internal\n */\nconst RX_NUMBER_PATTERN = /\\b\\d{4,12}\\b/g;\n\n/**\n * Detect prescription identifiers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"prescription\"`.\n */\nexport function detectPrescription(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(RX_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // Prescription patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"prescription\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // DEA numbers — validated with checksum\n const deaRe = new RegExp(DEA_PATTERN.source, \"gi\");\n while ((m = deaRe.exec(text)) !== null) {\n if (deaChecksum(m[0])) {\n push(m[0], m.index, m.index + m[0].length, 0.90);\n }\n }\n\n // NDC codes — distinctive format\n const ndcRe = new RegExp(NDC_PATTERN.source, \"g\");\n while ((m = ndcRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.90 : 0.78);\n }\n\n // Rx numbers — require context\n const rxRe = new RegExp(RX_NUMBER_PATTERN.source, \"g\");\n while ((m = rxRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.82);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/api-key\n * @description Detector for API keys and authentication tokens.\n *\n * Covered formats:\n * - AWS Access Key ID: AKIA... (20 chars)\n * - AWS Secret Access Key: 40 base64 chars (context required)\n * - Stripe live secret key: sk_live_...\n * - Stripe live publishable key: pk_live_...\n * - Stripe test keys: sk_test_..., pk_test_...\n * - GitHub tokens: ghp_, gho_, ghs_, ghr_, github_pat_\n * - Slack bot token: xoxb-...\n * - Slack user token: xoxp-...\n * - Slack app token: xoxa-...\n * - Slack workspace token: xoxs-...\n * - OpenAI API key: sk-...\n * - Google API key: AIza...\n * - JWT tokens: eyJ...\n * - Bearer tokens: Bearer + base64 string (context required)\n * - Generic API key with context keyword\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\ninterface ApiKeyEntry {\n readonly pattern: RegExp;\n readonly confidence: number;\n readonly requiresContext: boolean;\n}\n\nconst API_KEY_ENTRIES: readonly ApiKeyEntry[] = [\n // AWS Access Key ID\n {\n pattern: /\\bAKIA[0-9A-Z]{16}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // Stripe live secret key\n {\n pattern: /\\bsk_live_[a-zA-Z0-9]{24,99}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // Stripe live publishable key\n {\n pattern: /\\bpk_live_[a-zA-Z0-9]{24,99}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // Stripe test keys\n {\n pattern: /\\b(?:sk|pk)_test_[a-zA-Z0-9]{24,99}\\b/g,\n confidence: 0.97,\n requiresContext: false,\n },\n // GitHub personal access tokens (classic)\n {\n pattern: /\\bghp_[a-zA-Z0-9]{36}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // GitHub OAuth tokens\n {\n pattern: /\\bgho_[a-zA-Z0-9]{36}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // GitHub server-to-server tokens\n {\n pattern: /\\bghs_[a-zA-Z0-9]{36}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // GitHub refresh tokens\n {\n pattern: /\\bghr_[a-zA-Z0-9]{36,76}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // GitHub fine-grained PAT\n {\n pattern: /\\bgithub_pat_[a-zA-Z0-9_]{59,}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // Slack bot tokens\n {\n pattern: /\\bxoxb-[0-9A-Za-z-]{40,}\\b/g,\n confidence: 0.98,\n requiresContext: false,\n },\n // Slack user tokens\n {\n pattern: /\\bxoxp-[0-9A-Za-z-]{40,}\\b/g,\n confidence: 0.98,\n requiresContext: false,\n },\n // Slack app tokens\n {\n pattern: /\\bxoxa-[0-9A-Za-z-]{40,}\\b/g,\n confidence: 0.98,\n requiresContext: false,\n },\n // Slack workspace tokens\n {\n pattern: /\\bxoxs-[0-9A-Za-z-]{40,}\\b/g,\n confidence: 0.96,\n requiresContext: false,\n },\n // OpenAI API keys\n {\n pattern: /\\bsk-[a-zA-Z0-9]{32,}\\b/g,\n confidence: 0.90,\n requiresContext: false,\n },\n // Google API keys\n {\n pattern: /\\bAIza[0-9A-Za-z_-]{35}\\b/g,\n confidence: 0.99,\n requiresContext: false,\n },\n // JWT tokens (only the full 3-part form)\n {\n pattern: /\\beyJ[a-zA-Z0-9_-]{10,}\\.eyJ[a-zA-Z0-9_-]{10,}\\.[a-zA-Z0-9_-]{20,}\\b/g,\n confidence: 0.95,\n requiresContext: false,\n },\n];\n\n/**\n * Context keywords for generic API key detection.\n * @internal\n */\nconst API_KEY_CONTEXT_RE =\n /\\b(?:api[_-\\s]?key|api[_-\\s]?token|access[_-\\s]?token|secret[_-\\s]?key|auth(?:orization)?[_-\\s]?(?:key|token)|bearer(?:\\s+token)?|x-api-key|credential[s]?)\\s*[:=]\\s*/gi;\n\n/**\n * Generic API key / secret: 20-80 alphanumeric + _ + - chars with context.\n * @internal\n */\nconst GENERIC_KEY_PATTERN = /\\b[a-zA-Z0-9_.-]{20,80}\\b/g;\n\n/**\n * Detect API keys and authentication tokens in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"api-key\"`.\n */\nexport function detectApiKey(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(API_KEY_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 10);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"api-key\", value, start, end, confidence });\n }\n\n // Specific known formats\n for (const entry of API_KEY_ENTRIES) {\n const re = new RegExp(entry.pattern.source, \"g\");\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, entry.confidence);\n }\n }\n\n // Generic with context\n const genericRe = new RegExp(GENERIC_KEY_PATTERN.source, \"g\");\n let m: RegExpExecArray | null;\n while ((m = genericRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.82);\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/social-media\n * @description Detector for social media identifiers and handles.\n *\n * Covered:\n * - Twitter/X handles: @username (1-15 alphanumeric/underscore)\n * - Instagram handles: @username (1-30 alphanumeric/underscore/period)\n * - Discord IDs: 17-19 digit snowflake IDs\n * - YouTube channel IDs: UC + 22 base64 chars\n * - TikTok handles: @username\n * - LinkedIn profile URLs: linkedin.com/in/...\n * - Reddit usernames: u/username\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Twitter/X handle: @ + 1-15 word chars (letters, digits, underscores).\n * No period allowed in Twitter handles.\n * @internal\n */\nconst TWITTER_HANDLE_PATTERN = /(?<![a-zA-Z0-9])@[a-zA-Z0-9_]{1,15}(?![a-zA-Z0-9_@])/g;\n\n/**\n * Discord snowflake ID: 17-19 digit integer.\n * Requires context keyword.\n * @internal\n */\nconst DISCORD_ID_PATTERN = /\\b\\d{17,19}\\b/g;\n\n/**\n * YouTube channel ID: UC + 22 base64 URL-safe chars\n * @internal\n */\nconst YT_CHANNEL_PATTERN = /\\bUC[a-zA-Z0-9_-]{22}\\b/g;\n\n/**\n * Reddit username: u/ or /u/ prefix\n * @internal\n */\nconst REDDIT_USER_PATTERN = /\\b(?:u|\\/u)\\/[a-zA-Z0-9_-]{3,20}\\b/g;\n\n/**\n * LinkedIn profile URL fragment\n * @internal\n */\nconst LINKEDIN_PATTERN = /\\blinkedin\\.com\\/in\\/[a-zA-Z0-9-]{3,100}\\b/gi;\n\n/**\n * Context keywords for Discord IDs.\n * @internal\n */\nconst DISCORD_CONTEXT_RE =\n /\\b(?:discord(?:\\s+(?:id|user|server|guild))?|user\\s+id|uid)\\s*:?\\s*/gi;\n\n/**\n * Detect social media identifiers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"social-media\"`.\n */\nexport function detectSocialMedia(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const discordContextPositions: number[] = [];\n const ctxRe = new RegExp(DISCORD_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n discordContextPositions.push(cm.index + cm[0].length);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // Social-media patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"social-media\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // Twitter handles — use the more restrictive pattern (no periods)\n // Apply conservative confidence since @ is common in other contexts\n const twitterRe = new RegExp(TWITTER_HANDLE_PATTERN.source, \"g\");\n while ((m = twitterRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n // YouTube channel IDs — distinctive\n const ytRe = new RegExp(YT_CHANNEL_PATTERN.source, \"g\");\n while ((m = ytRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.90);\n }\n\n // Reddit usernames\n const redditRe = new RegExp(REDDIT_USER_PATTERN.source, \"g\");\n while ((m = redditRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n\n // LinkedIn profiles\n const linkedinRe = new RegExp(LINKEDIN_PATTERN.source, \"gi\");\n while ((m = linkedinRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.92);\n }\n\n // Discord snowflake IDs — requires context\n const discordRe = new RegExp(DISCORD_ID_PATTERN.source, \"g\");\n while ((m = discordRe.exec(text)) !== null) {\n const match = m;\n const hasContext = discordContextPositions.some(\n (pos) => pos <= match.index && match.index - pos <= 30,\n );\n if (hasContext) push(match[0], match.index, match.index + match[0].length, 0.85);\n }\n\n return matches;\n}\n","/**\n * @module detectors/vin\n * @description Detector for Vehicle Identification Numbers (VIN).\n *\n * VINs are 17 characters per ISO 3779. The 9th character is a check digit\n * validated using transliteration and a mod-11 algorithm. Characters I, O, Q\n * are excluded from valid VINs.\n *\n * Confidence: 0.95 when checksum passes, 0.70 for format-only match.\n */\n\nimport type { PiiMatch } from \"../types.js\";\nimport { vinChecksum } from \"../validators.js\";\n\n/**\n * VIN candidates: 17 chars from valid VIN alphabet (A-H, J-N, P, R-Z, 0-9).\n * @internal\n */\nconst VIN_PATTERN = /\\b[A-HJ-NPR-Z0-9]{17}\\b/gi;\n\n/**\n * Detect Vehicle Identification Numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"vin\"`.\n */\nexport function detectVin(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const re = new RegExp(VIN_PATTERN.source, \"gi\");\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n const upper = m[0].toUpperCase();\n const valid = vinChecksum(upper);\n if (valid) {\n matches.push({\n category: \"vin\",\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence: 0.95,\n });\n }\n }\n\n return matches;\n}\n\n/**\n * Aggressive variant of {@link detectVin}.\n * Also reports format-valid VINs that fail the checksum (e.g. non-North-American\n * vehicles where the check digit is not enforced).\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"vin\"`.\n */\nexport function detectVinAggressive(text: string): PiiMatch[] {\n const strict = detectVin(text);\n const strictRanges = new Set(strict.map((m) => `${String(m.start)}-${String(m.end)}`));\n\n const matches: PiiMatch[] = [...strict];\n const re = new RegExp(VIN_PATTERN.source, \"gi\");\n let m: RegExpExecArray | null;\n\n while ((m = re.exec(text)) !== null) {\n const key = `${String(m.index)}-${String(m.index + m[0].length)}`;\n if (!strictRanges.has(key)) {\n matches.push({\n category: \"vin\",\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence: 0.70,\n });\n }\n }\n\n return matches;\n}\n","/**\n * @module detectors/license-plate\n * @description Detector for vehicle license/number plates.\n *\n * Covered formats:\n * - US: generic state format (2-8 alphanumeric, context required)\n * - UK: current format (AB12 ABC) and older (A123 BCD)\n * - EU generic: 1-2 letters + 2-4 digits + 1-3 letters\n *\n * Context keywords strongly boost reliability.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Context keywords for license plates.\n * @internal\n */\nconst LP_CONTEXT_RE =\n /\\b(?:licen[sc]e\\s+plate|number\\s+plate|registration\\s+(?:plate|number)|reg(?:istration)?\\s*(?:no\\.?|#|:)|plate(?:\\s+(?:number|no\\.?))?)\\s*:?\\s*/gi;\n\n/**\n * UK current format: AB12 ABC or AB12ABC (letters-digits-letters).\n * @internal\n */\nconst UK_CURRENT_LP_PATTERN = /\\b[A-Z]{2}\\d{2}[\\s]?[A-Z]{3}\\b/gi;\n\n/**\n * UK older prefix format: A123 BCD or A123BCD\n * @internal\n */\nconst UK_OLD_LP_PATTERN = /\\b[A-Z]\\d{1,4}[\\s]?[A-Z]{3}\\b/gi;\n\n/**\n * EU generic: 1-2 letters + 1-4 digits + 1-3 letters (typically on black/white plates)\n * @internal\n */\nconst EU_LP_PATTERN = /\\b[A-Z]{1,2}[\\s-]?\\d{1,4}[\\s-]?[A-Z]{1,3}\\b/gi;\n\n/**\n * US generic: state plates are typically 2-8 alphanumeric chars.\n * Too generic to report without context.\n * @internal\n */\nconst US_LP_PATTERN = /\\b[A-Z0-9]{2,8}\\b/g;\n\n/**\n * Detect vehicle license plate numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"license-plate\"`.\n */\nexport function detectLicensePlate(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(LP_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 20);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"license-plate\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // UK current format — distinctive\n const ukCurrentRe = new RegExp(UK_CURRENT_LP_PATTERN.source, \"gi\");\n while ((m = ukCurrentRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.90 : 0.78);\n }\n\n // UK older format\n const ukOldRe = new RegExp(UK_OLD_LP_PATTERN.source, \"gi\");\n while ((m = ukOldRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.85 : 0.70);\n }\n\n // EU generic — context recommended\n const euRe = new RegExp(EU_LP_PATTERN.source, \"gi\");\n while ((m = euRe.exec(text)) !== null) {\n const conf = hasContextAt(m.index) ? 0.82 : 0.65;\n if (conf >= 0.70) push(m[0], m.index, m.index + m[0].length, conf);\n }\n\n // US generic — requires context\n const usRe = new RegExp(US_LP_PATTERN.source, \"g\");\n while ((m = usRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.80);\n }\n\n return matches;\n}\n","/**\n * @module detectors/tracking-number\n * @description Detector for parcel/shipment tracking numbers.\n *\n * Covered carriers:\n * - FedEx: 12 or 15 or 20 digits\n * - UPS: 1Z + 16 chars\n * - USPS: 20-22 digits or XX### ### ### US format\n * - DHL: 10 digits or 11 digits starting with JD\n * - Amazon: TBA + 12 digits\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * UPS: 1Z + 16 alphanumeric chars (checksum via mod-7)\n * @internal\n */\nconst UPS_PATTERN = /\\b1Z[A-Z0-9]{16}\\b/gi;\n\n/**\n * USPS: 20-22 consecutive digits\n * @internal\n */\nconst USPS_LONG_PATTERN = /\\b\\d{20,22}\\b/g;\n\n/**\n * USPS: service code + digits + US (e.g., 94001116990045395947)\n * @internal\n */\nconst USPS_FORMAT_PATTERN =\n /\\b(?:9[2-5]\\d{18,20}|[A-Z]{2}\\d{9}US)\\b/gi;\n\n/**\n * FedEx: 12-digit, 15-digit, or 20-22 digit number\n * @internal\n */\nconst FEDEX_PATTERN = /\\b(?:\\d{12}|\\d{15}|\\d{20,22})\\b/g;\n\n/**\n * DHL: 10-digit or JD + 9 digits\n * @internal\n */\nconst DHL_PATTERN = /\\bJD\\d{9}\\b|\\b\\d{10,11}\\b/gi;\n\n/**\n * Amazon: TBA + 12 digits\n * @internal\n */\nconst AMAZON_PATTERN = /\\bTBA\\d{12}\\b/gi;\n\n/**\n * Context keywords for tracking numbers.\n * @internal\n */\nconst TRACKING_CONTEXT_RE =\n /\\b(?:tracking(?:\\s+(?:number|no\\.?|#|id))?|shipment(?:\\s+(?:number|id|tracking))?|parcel(?:\\s+(?:number|id))?|package(?:\\s+(?:number|id|tracking))?|(?:fedex|ups|usps|dhl|amazon)\\s+(?:tracking|shipment)?)\\s*:?\\s*/gi;\n\n/**\n * Detect parcel tracking numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"tracking-number\"`.\n */\nexport function detectTrackingNumber(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(TRACKING_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"tracking-number\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // UPS — most distinctive (1Z prefix)\n const upsRe = new RegExp(UPS_PATTERN.source, \"gi\");\n while ((m = upsRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.96);\n }\n\n // Amazon — distinctive (TBA prefix)\n const amazonRe = new RegExp(AMAZON_PATTERN.source, \"gi\");\n while ((m = amazonRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.97);\n }\n\n // USPS service-format\n const uspsFormatRe = new RegExp(USPS_FORMAT_PATTERN.source, \"gi\");\n while ((m = uspsFormatRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, 0.90);\n }\n\n // DHL JD prefix\n const dhlRe = new RegExp(DHL_PATTERN.source, \"gi\");\n while ((m = dhlRe.exec(text)) !== null) {\n if (m[0].startsWith(\"JD\") || m[0].startsWith(\"jd\")) {\n push(m[0], m.index, m.index + m[0].length, 0.88);\n } else if (hasContextAt(m.index)) {\n push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n }\n\n // Generic numeric tracking — requires context\n const uspsLongRe = new RegExp(USPS_LONG_PATTERN.source, \"g\");\n while ((m = uspsLongRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.80);\n }\n\n const fedexRe = new RegExp(FEDEX_PATTERN.source, \"g\");\n while ((m = fedexRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n return matches;\n}\n","/**\n * @module detectors/case-number\n * @description Detector for US federal/state court case numbers.\n *\n * US federal court case numbers follow the pattern:\n * - YEAR:COURT DIVISION - CASE_TYPE - NUMBER (e.g., 1:21-cv-00123)\n * - Or: YEAR-CASE_TYPE-NUMBER (e.g., 21-CR-0456)\n *\n * Requires context keywords to reduce false positives.\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * US Federal court case number: e.g., 1:21-cv-00123, 21-cv-00123\n * @internal\n */\nconst FEDERAL_CASE_PATTERN =\n /\\b(?:\\d:\\s*)?\\d{2}[\\s-](?:cv|cr|civ|crim|mc|mj|po|br|ap|adv|bk)[\\s-]\\d{4,6}\\b/gi;\n\n/**\n * General legal case number with context.\n * @internal\n */\nconst GENERAL_CASE_PATTERN =\n /\\b(?:[A-Z]{1,4}[-\\s])?\\d{2,4}[-/]\\d{2,6}(?:[-/][A-Z0-9]{1,5})?\\b/gi;\n\n/**\n * Case number context keywords.\n * @internal\n */\nconst CASE_CONTEXT_RE =\n /\\b(?:case(?:\\s+(?:number|no\\.?|#|id))?|docket(?:\\s+(?:number|no\\.?|#))?|civil\\s+action|criminal\\s+(?:case|no\\.?|#)|court\\s+(?:case|file(?:\\s+no\\.?)?)|matter\\s+no\\.?|file\\s+(?:number|no\\.?|#))\\s*:?\\s*/gi;\n\n/**\n * Detect court case numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"case-number\"`.\n */\nexport function detectCaseNumber(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(CASE_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // The federal and general patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"case-number\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // Federal court pattern — relatively distinctive\n const fedRe = new RegExp(FEDERAL_CASE_PATTERN.source, \"gi\");\n while ((m = fedRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.92 : 0.80);\n }\n\n // General pattern — requires context\n const generalRe = new RegExp(GENERAL_CASE_PATTERN.source, \"gi\");\n while ((m = generalRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n return matches;\n}\n","/**\n * @module detectors/company-registration\n * @description Detector for company registration numbers.\n *\n * Covered:\n * - US EIN: XX-XXXXXXX (same as tax-id but in company registration context)\n * - UK Companies House: 8 digits or 2 letters + 6 digits (e.g., 00123456, SC012345)\n * - EU/generic: country code + alphanumeric registration number\n * - Australian ACN: XXX XXX XXX (9 digits)\n */\n\nimport type { PiiMatch } from \"../types.js\";\n\n/**\n * Context keywords for company registration.\n * @internal\n */\nconst CR_CONTEXT_RE =\n /\\b(?:company\\s+(?:registration|reg(?:istration)?)\\s*(?:number|no\\.?|#)?|companies\\s+house\\s*(?:number|no\\.?|#)?|registered\\s+(?:number|company\\s+number|no\\.?)|incorporation\\s*(?:number|no\\.?|#)?|company\\s+(?:number|no\\.?|#)|corporate\\s+(?:id|number|no\\.?|registration)|business\\s+(?:registration|number)|ABN|ACN|CIK)\\s*:?\\s*/gi;\n\n/**\n * UK Companies House: 8 digits or 2 letters + 6 digits.\n * @internal\n */\nconst UK_CH_PATTERN = /\\b(?:[A-Z]{2}\\d{6}|\\d{8})\\b/gi;\n\n/**\n * US EIN in company context: XX-XXXXXXX.\n * @internal\n */\nconst US_EIN_PATTERN = /\\b\\d{2}-\\d{7}\\b/g;\n\n/**\n * Australian ACN: 9 digits (often written XXX XXX XXX).\n * @internal\n */\nconst AU_ACN_PATTERN = /\\b\\d{3}[\\s]?\\d{3}[\\s]?\\d{3}\\b/g;\n\n/**\n * EU generic: 2-letter country code optionally followed by alphanumeric registration.\n * @internal\n */\nconst EU_CO_REG_PATTERN = /\\b[A-Z]{2}[\\s-]?[A-Z0-9]{5,12}\\b/g;\n\n/**\n * Detect company registration numbers in `text`.\n *\n * @param text - The input string to scan.\n * @returns An array of {@link PiiMatch} objects with `category: \"company-registration\"`.\n */\nexport function detectCompanyRegistration(text: string): PiiMatch[] {\n const matches: PiiMatch[] = [];\n const seen = new Set<string>();\n\n const contextPositions: number[] = [];\n const ctxRe = new RegExp(CR_CONTEXT_RE.source, \"gi\");\n let cm: RegExpExecArray | null;\n while ((cm = ctxRe.exec(text)) !== null) {\n contextPositions.push(cm.index + cm[0].length);\n }\n\n function hasContextAt(index: number): boolean {\n return contextPositions.some((pos) => pos <= index && index - pos <= 30);\n }\n\n function push(value: string, start: number, end: number, confidence: number): void {\n const key = `${String(start)}-${String(end)}`;\n // The EIN, UK, AU ACN, and EU generic patterns never produce overlapping ranges in practice.\n /* v8 ignore next */\n if (seen.has(key)) return;\n seen.add(key);\n matches.push({ category: \"company-registration\", value, start, end, confidence });\n }\n\n let m: RegExpExecArray | null;\n\n // US EIN — distinctive format\n const einRe = new RegExp(US_EIN_PATTERN.source, \"g\");\n while ((m = einRe.exec(text)) !== null) {\n push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.88 : 0.72);\n }\n\n // UK Companies House — with context\n const ukRe = new RegExp(UK_CH_PATTERN.source, \"gi\");\n while ((m = ukRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);\n }\n\n // AU ACN — with context\n const acnRe = new RegExp(AU_ACN_PATTERN.source, \"g\");\n while ((m = acnRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.82);\n }\n\n // EU generic — with context\n const euRe = new RegExp(EU_CO_REG_PATTERN.source, \"g\");\n while ((m = euRe.exec(text)) !== null) {\n if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);\n }\n\n return matches;\n}\n","/**\n * @module detectors\n * @description Barrel export for all built-in PII detectors.\n *\n * Each detector is a pure function that accepts a string and returns an array of\n * {@link PiiMatch} objects. Import individual detectors for maximum tree-shaking,\n * or use the pre-assembled {@link DETECTOR_REGISTRY} for convenience.\n *\n * For aggressive (more permissive) detection, use {@link AGGRESSIVE_DETECTOR_REGISTRY}.\n *\n * @example\n * ```ts\n * import { detectEmail, detectPhone, DETECTOR_REGISTRY } from \"anonyma/detectors\";\n *\n * // Use a single detector:\n * const matches = detectEmail(\"hello@example.com\");\n *\n * // Or scan for everything:\n * const allMatches = Object.values(DETECTOR_REGISTRY).flatMap((d) => d(\"some text\"));\n * ```\n */\n\n// --- Original detectors ---\nexport { detectEmail, detectEmailAggressive } from \"./email.js\";\nexport { detectPhone, detectPhoneAggressive } from \"./phone.js\";\nexport { detectSsn, detectSsnAggressive } from \"./ssn.js\";\nexport { detectCreditCard, detectCreditCardAggressive } from \"./credit-card.js\";\nexport { detectIpv4, detectIpv6 } from \"./ip-address.js\";\nexport { detectUrl } from \"./url.js\";\nexport { detectIban } from \"./iban.js\";\nexport { detectDateOfBirth } from \"./date-of-birth.js\";\nexport { detectName, detectNameAggressive } from \"./name.js\";\n\n// --- Personal Information ---\nexport { detectAddress } from \"./address.js\";\nexport { detectPassport } from \"./passport.js\";\nexport { detectDriversLicense } from \"./drivers-license.js\";\nexport { detectNationalId } from \"./national-id.js\";\n\n// --- Financial ---\nexport { detectBankAccount } from \"./bank-account.js\";\nexport { detectCryptocurrency } from \"./cryptocurrency.js\";\nexport { detectTaxId } from \"./tax-id.js\";\n\n// --- Healthcare ---\nexport { detectMedicalRecord } from \"./medical-record.js\";\nexport { detectHealthInsurance } from \"./health-insurance.js\";\nexport { detectPrescription } from \"./prescription.js\";\n\n// --- Digital Identity ---\nexport { detectApiKey } from \"./api-key.js\";\nexport { detectSocialMedia } from \"./social-media.js\";\n\n// --- Vehicles & Transportation ---\nexport { detectVin, detectVinAggressive } from \"./vin.js\";\nexport { detectLicensePlate } from \"./license-plate.js\";\nexport { detectTrackingNumber } from \"./tracking-number.js\";\n\n// --- Government & Legal ---\nexport { detectCaseNumber } from \"./case-number.js\";\nexport { detectCompanyRegistration } from \"./company-registration.js\";\n\nimport { detectEmail, detectEmailAggressive } from \"./email.js\";\nimport { detectPhone, detectPhoneAggressive } from \"./phone.js\";\nimport { detectSsn, detectSsnAggressive } from \"./ssn.js\";\nimport { detectCreditCard, detectCreditCardAggressive } from \"./credit-card.js\";\nimport { detectIpv4, detectIpv6 } from \"./ip-address.js\";\nimport { detectUrl } from \"./url.js\";\nimport { detectIban } from \"./iban.js\";\nimport { detectDateOfBirth } from \"./date-of-birth.js\";\nimport { detectName, detectNameAggressive } from \"./name.js\";\nimport { detectAddress } from \"./address.js\";\nimport { detectPassport } from \"./passport.js\";\nimport { detectDriversLicense } from \"./drivers-license.js\";\nimport { detectNationalId } from \"./national-id.js\";\nimport { detectBankAccount } from \"./bank-account.js\";\nimport { detectCryptocurrency } from \"./cryptocurrency.js\";\nimport { detectTaxId } from \"./tax-id.js\";\nimport { detectMedicalRecord } from \"./medical-record.js\";\nimport { detectHealthInsurance } from \"./health-insurance.js\";\nimport { detectPrescription } from \"./prescription.js\";\nimport { detectApiKey } from \"./api-key.js\";\nimport { detectSocialMedia } from \"./social-media.js\";\nimport { detectVin, detectVinAggressive } from \"./vin.js\";\nimport { detectLicensePlate } from \"./license-plate.js\";\nimport { detectTrackingNumber } from \"./tracking-number.js\";\nimport { detectCaseNumber } from \"./case-number.js\";\nimport { detectCompanyRegistration } from \"./company-registration.js\";\n\nimport type { DetectorRegistry } from \"../types.js\";\n\n/**\n * A pre-assembled registry containing all built-in detectors, keyed by\n * {@link PiiCategory}.\n *\n * @example\n * ```ts\n * import { DETECTOR_REGISTRY } from \"anonyma/detectors\";\n *\n * const emailMatches = DETECTOR_REGISTRY.email(\"user@example.com\");\n * ```\n */\nexport const DETECTOR_REGISTRY: DetectorRegistry = {\n // Original\n email: detectEmail,\n phone: detectPhone,\n ssn: detectSsn,\n \"credit-card\": detectCreditCard,\n ipv4: detectIpv4,\n ipv6: detectIpv6,\n url: detectUrl,\n iban: detectIban,\n \"date-of-birth\": detectDateOfBirth,\n name: detectName,\n // Personal Information\n address: detectAddress,\n passport: detectPassport,\n \"drivers-license\": detectDriversLicense,\n \"national-id\": detectNationalId,\n // Financial\n \"bank-account\": detectBankAccount,\n cryptocurrency: detectCryptocurrency,\n \"tax-id\": detectTaxId,\n // Healthcare\n \"medical-record\": detectMedicalRecord,\n \"health-insurance\": detectHealthInsurance,\n prescription: detectPrescription,\n // Digital Identity\n \"api-key\": detectApiKey,\n \"social-media\": detectSocialMedia,\n // Vehicles & Transportation\n vin: detectVin,\n \"license-plate\": detectLicensePlate,\n \"tracking-number\": detectTrackingNumber,\n // Government & Legal\n \"case-number\": detectCaseNumber,\n \"company-registration\": detectCompanyRegistration,\n} as const;\n\n/**\n * An alternative registry that uses expanded, more permissive patterns for each\n * detector. Enables detection of obfuscated or partial PII at the cost of a higher\n * false-positive rate.\n *\n * Use it by passing `aggressive: true` to {@link anonymize} / {@link createAnonymizer},\n * or directly via this registry for low-level usage.\n *\n * @example\n * ```ts\n * import { AGGRESSIVE_DETECTOR_REGISTRY } from \"anonyma/detectors\";\n *\n * const matches = AGGRESSIVE_DETECTOR_REGISTRY.email(\"user [at] example [dot] com\");\n * ```\n */\nexport const AGGRESSIVE_DETECTOR_REGISTRY: DetectorRegistry = {\n // Original (aggressive variants where available)\n email: detectEmailAggressive,\n phone: detectPhoneAggressive,\n ssn: detectSsnAggressive,\n \"credit-card\": detectCreditCardAggressive,\n ipv4: detectIpv4,\n ipv6: detectIpv6,\n url: detectUrl,\n iban: detectIban,\n \"date-of-birth\": detectDateOfBirth,\n name: detectNameAggressive,\n // Personal Information\n address: detectAddress,\n passport: detectPassport,\n \"drivers-license\": detectDriversLicense,\n \"national-id\": detectNationalId,\n // Financial\n \"bank-account\": detectBankAccount,\n cryptocurrency: detectCryptocurrency,\n \"tax-id\": detectTaxId,\n // Healthcare\n \"medical-record\": detectMedicalRecord,\n \"health-insurance\": detectHealthInsurance,\n prescription: detectPrescription,\n // Digital Identity\n \"api-key\": detectApiKey,\n \"social-media\": detectSocialMedia,\n // Vehicles & Transportation\n vin: detectVinAggressive,\n \"license-plate\": detectLicensePlate,\n \"tracking-number\": detectTrackingNumber,\n // Government & Legal\n \"case-number\": detectCaseNumber,\n \"company-registration\": detectCompanyRegistration,\n} as const;\n\n","/**\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]`) or `\"angle\"` (`<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\" ? `[${prefix}_${id}]` : `<${prefix}_${id}>`;\n\n store.index.set(indexKey, token);\n store.tokens.set(token, value);\n return token;\n}\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 // Match both bracket `[PREFIX_NNNN]` and angle `<PREFIX_N>` format tokens.\n const re = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n\n const result = text.replace(re, (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 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 // Alpha → 'X', digit → '0', separators/punctuation preserved.\n // `keepLeading` / `keepTrailing` still apply (character counts, ignoring separators).\n if (preserveFormat) {\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= value.length) {\n return value; // everything is visible, nothing to mask\n }\n\n const chars = value.split(\"\");\n // Determine the interior slice to mask (skip leading / trailing).\n const interior = chars.slice(keepLeading, value.length - (keepTrailing > 0 ? keepTrailing : 0));\n const maskedInterior = interior.map((ch) => {\n if (/[a-zA-Z]/.test(ch)) return ch === ch.toUpperCase() ? \"X\" : \"x\";\n if (/\\d/.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 // `value` is validated to be a string by TypeScript; no runtime check needed\n // other than ensuring it is not undefined at the call-site.\n void value; // explicitly acknowledge the parameter (pure function, input unused)\n\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 anonymize\n * @description Core anonymization engine — detects PII and applies strategies.\n */\n\nimport { DETECTOR_REGISTRY, AGGRESSIVE_DETECTOR_REGISTRY } from \"./detectors/index.js\";\nimport {\n createTokenStore,\n assignToken as assignTokenFn,\n} 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 type {\n AnonymizeOptions,\n AnonymizeResult,\n AnonymizerConfig,\n Anonymizer,\n FieldRuleMap,\n PiiCategory,\n PiiMatch,\n StrategyOptions,\n Detector,\n CustomPattern,\n TokenizeOptions,\n TokenMatch,\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 * 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 `hash()` directly if you need true 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 // These strategies are async-only. In sync contexts we fall back to redact.\n // eslint-disable-next-line no-console\n console.warn(\n `[anonyma] The \\`${opts.strategy}\\` strategy requires async execution. ` +\n `Falling back to redact in the synchronous pipeline. Use anonymizeAsync() instead.`,\n );\n return redact(value);\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 }\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(\n (a, b) => a.start - b.start || b.confidence - a.confidence,\n );\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, merging custom overrides.\n *\n * @internal\n */\nfunction resolveDetector(\n category: PiiCategory,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): Detector {\n if (customDetectors?.[category]) return customDetectors[category];\n return aggressive ? AGGRESSIVE_DETECTOR_REGISTRY[category] : DETECTOR_REGISTRY[category];\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(options: AnonymizeOptions): 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 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 const detector = resolveDetector(category, customDetectors, aggressive);\n raw.push(...detector(text));\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 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 const detector = resolveDetector(category, customDetectors);\n if (detector(text).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 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>();\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 // Pre-compile allowlist patterns for performance.\n const compiledAllowlistPatterns: RegExp[] = [\n ...allowlistPatterns,\n ...allowlist.map(\n (entry) =>\n new RegExp(\n entry.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"),\n allowlistCaseSensitive ? \"\" : \"i\",\n ),\n ),\n ];\n\n /**\n * Returns true if `value` matches any allowlist entry — i.e. it should\n * NOT be anonymized even if detected as PII.\n */\n function isAllowlisted(value: string): boolean {\n if (compiledAllowlistPatterns.length === 0) return false;\n return compiledAllowlistPatterns.some((re) => re.test(value));\n }\n\n // Run built-in detectors.\n const builtInMatches = detect(text, categories, customDetectors, aggressive);\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 = (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ?? 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 = applyStrategySync(match.value, strategy);\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 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): boolean =>\n opts.strategy === \"hash\" || opts.strategy === \"encrypt\" ||\n opts.strategy === \"tokenize\" || 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 anonymize(text, options);\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>();\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 = detect(text, categories, customDetectors, aggressive);\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n const compiledAllowlistPatterns: RegExp[] = [\n ...allowlistPatterns,\n ...allowlist.map(\n (entry) =>\n new RegExp(\n entry.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"),\n allowlistCaseSensitive ? \"\" : \"i\",\n ),\n ),\n ];\n const isAllowlisted = (value: string): boolean =>\n compiledAllowlistPatterns.some((re) => re.test(value));\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 = (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ?? 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 (strategy.strategy === \"hash\") {\n replacement = await hashFn(match.value, strategy);\n } else {\n replacement = applyStrategySync(match.value, strategy);\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 if (typeof obj !== \"object\") {\n throw new ValidationError(\"obj\", \"must be an object\");\n }\n return deepAnonymizeValue(obj, options, new WeakSet()) 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 | undefined,\n seen: WeakSet<object>,\n): unknown {\n if (value === null || value === undefined) return value;\n\n if (typeof value === \"string\") {\n return anonymize(value, options).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));\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 as Record<string, unknown>)) {\n result[key] = deepAnonymizeValue(\n (value as Record<string, unknown>)[key],\n options,\n seen,\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 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 = applyStrategySync(strValue, rule.strategy);\n result = setByPath(result, path, anonymized);\n }\n }\n\n return result as T;\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizer()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reusable, pre-configured {@link Anonymizer} instance.\n *\n * @param config - Anonymizer configuration.\n * @returns A configured {@link Anonymizer}.\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 } = 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 /** Shared base options derived from config. */\n function baseOptions(overrides?: Partial<AnonymizeOptions>): AnonymizeOptions {\n const base: AnonymizeOptions = {\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(text: string, options?: Partial<AnonymizeOptions>): AnonymizeResult {\n return anonymize(text, baseOptions(options));\n },\n\n detect(text: string): PiiMatch[] {\n return detect(text, categories, customDetectors, aggressive);\n },\n\n anonymizeRecord<T extends Record<string, unknown>>(record: T, rules: FieldRuleMap): T {\n return anonymizeRecord(record, rules);\n },\n\n anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n return anonymizeObject(obj, baseOptions(options));\n },\n\n async anonymizeAsync(text: string, options?: Partial<AnonymizeOptions>): Promise<AnonymizeResult> {\n return anonymizeAsync(text, baseOptions(options));\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 tCompiledAllowlist = tAllowlist.map(\n (entry: string) =>\n new RegExp(entry.replace(/[.*+?^${}()|[\\\\]\\\\]/g, \"\\\\$&\"), tCaseSensitive ? \"\" : \"i\"),\n );\n const isAllowlisted = (v: string): boolean => tCompiledAllowlist.some((re: RegExp) => re.test(v));\n\n const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(\n (m) => m.confidence >= tConfidence && !isAllowlisted(m.value),\n );\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 hasPII(text, categories, customDetectors);\n },\n };\n}\n","/**\n * @module presets\n * @description Built-in compliance preset configurations for GDPR, HIPAA, CCPA,\n * PCI-DSS, SOX, and FERPA. Import from `\"anonyma\"` or extend using the\n * `preset` option in {@link AnonymizeOptions}.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * // Apply HIPAA preset — redacts all 18 HIPAA Safe Harbor identifiers\n * anonymize(text, { preset: \"hipaa\" });\n *\n * // Extend GDPR preset with API key detection\n * anonymize(text, { preset: \"gdpr\", enabledCategories: { \"api-key\": true } });\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 18 HIPAA Safe Harbor identifiers.\n * Default strategy: redact (no reconstructability).\n *\n * The 18 Safe Harbor identifiers are:\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 — Covers all 18 protected health information (PHI) identifiers \" +\n \"to de-identify medical records.\",\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 \"drivers-license\",\n \"vin\",\n \"url\",\n \"ipv4\",\n \"ipv6\",\n \"national-id\",\n \"tax-id\",\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 ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PCI-DSS — Payment Card Industry Data Security Standard.\n * Covers cardholder data (CHD) and sensitive authentication data (SAD).\n * Default strategy: mask with last 4 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: [\n \"credit-card\",\n \"bank-account\",\n \"name\",\n \"address\",\n \"email\",\n \"phone\",\n ],\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: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"ssn\",\n \"national-id\",\n ],\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 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","/**\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 { createTokenStore, assignToken, detokenizeText } from \"./strategies/tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport type {\n TokenizeResult,\n DetokenizeResult,\n TokenizeOptions,\n TokenMatch,\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 */\nexport function tokenize(text: string, options: TokenizeOptions = {}): TokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n const {\n categories,\n format = \"bracket\",\n customDetectors,\n aggressive = false,\n confidenceThreshold = 0,\n allowlist = [],\n allowlistCaseSensitive = false,\n } = options;\n\n const compiledAllowlist = allowlist.map(\n (entry) =>\n new RegExp(entry.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), allowlistCaseSensitive ? \"\" : \"i\"),\n );\n const isAllowlisted = (v: string): boolean => compiledAllowlist.some((re) => re.test(v));\n\n // Detect PII.\n const allMatches = detect(text, categories, customDetectors, aggressive).filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n const store = createTokenStore();\n let result = text;\n const reversed = [...allMatches].reverse();\n const tokenMatches: TokenMatch[] = [];\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 * Useful for consistency in async pipelines.\n */\nexport function tokenizeAsync(\n text: string,\n options: TokenizeOptions = {},\n): Promise<TokenizeResult> {\n return Promise.resolve(tokenize(text, options));\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(\n text: string,\n mapping: ReadonlyMap<string, string>,\n): 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 TOKEN_RE = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n const totalInText = (text.match(TOKEN_RE) ?? []).length;\n const replacedCount = totalInText - result.unresolved.length;\n return {\n text: result.text,\n replacedCount,\n unresolved: result.unresolved,\n };\n}\n","/**\n * @module stream\n * @description Streaming support for anonyma via the WHATWG Streams API.\n *\n * Provides `TransformStream`-based wrappers so anonyma can be used in\n * Node.js stream pipelines and browser fetch-response chains.\n *\n * Requires Node ≥ 18 (global `TransformStream`) or a browser with Streams API.\n *\n * @example\n * ```ts\n * import { createAnonymizeStream } from \"anonyma/stream\";\n * import { createReadStream, createWriteStream } from \"node:fs\";\n *\n * const readable = ReadableStream.from(lines);\n * const anonymized = readable.pipeThrough(createAnonymizeStream());\n * for await (const chunk of anonymized) {\n * process.stdout.write(chunk);\n * }\n * ```\n */\n\nimport { anonymize, anonymizeAsync } from \"./anonymize.js\";\nimport { tokenize } from \"./tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport type { AnonymizeOptions, AnonymizeResult, TokenizeResult, TokenizeOptions } from \"./types.js\";\n\n/** Require the global `TransformStream` (Node ≥ 18 / browsers). */\nfunction requireTransformStream(): typeof TransformStream {\n if (typeof TransformStream === \"undefined\") {\n throw new ValidationError(\n \"TransformStream\",\n \"is not available in this environment. Use Node.js ≥ 18 or a polyfill.\",\n );\n }\n return TransformStream;\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizeStream()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a `TransformStream` that anonymizes each string chunk it receives.\n *\n * Input chunks are expected to be complete text strings (e.g. lines or\n * paragraphs). For true streaming over arbitrary byte chunks, split on\n * line boundaries before piping.\n *\n * @param options - Anonymization options forwarded to {@link anonymize}.\n * @returns A `TransformStream<string, AnonymizeResult>`.\n *\n * @example\n * ```ts\n * const stream = createAnonymizeStream({ defaultStrategy: { strategy: \"mask\" } });\n * const reader = readable.pipeThrough(stream).getReader();\n * const { value } = await reader.read();\n * // value: { text: \"****\", matches: [] }\n * ```\n */\nexport function createAnonymizeStream(\n options: AnonymizeOptions = {},\n): TransformStream<string, AnonymizeResult> {\n const TS = requireTransformStream();\n return new TS<string, AnonymizeResult>({\n transform(chunk, controller): void {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n controller.enqueue(anonymize(chunk, options));\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizeStreamAsync() — uses async strategies (hash/encrypt)\n// ---------------------------------------------------------------------------\n\n/**\n * Create an async-capable `TransformStream` that anonymizes each string chunk.\n * Supports `hash`, `encrypt`, and other async strategies.\n *\n * @param options - Anonymization options forwarded to {@link anonymizeAsync}.\n * @returns A `TransformStream<string, AnonymizeResult>`.\n */\nexport function createAnonymizeStreamAsync(\n options: AnonymizeOptions = {},\n): TransformStream<string, AnonymizeResult> {\n const TS = requireTransformStream();\n return new TS<string, AnonymizeResult>({\n async transform(chunk, controller): Promise<void> {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n try {\n const result = await anonymizeAsync(chunk, options);\n controller.enqueue(result);\n } catch (err) {\n controller.error(err);\n }\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public: createTokenizeStream()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a `TransformStream` that tokenizes each string chunk it receives.\n *\n * Note: each chunk gets its **own** token map. If you need a shared map across\n * all chunks, manage the tokenization externally and feed results manually.\n *\n * @param options - Tokenization options forwarded to {@link tokenize}.\n * @returns A `TransformStream<string, TokenizeResult>`.\n *\n * @example\n * ```ts\n * const stream = createTokenizeStream({ categories: [\"email\"] });\n * const writer = stream.writable.getWriter();\n * const reader = stream.readable.getReader();\n *\n * writer.write(\"Contact alice@example.com\");\n * writer.close();\n *\n * const { value } = await reader.read();\n * // value: { text: \"Contact [EMAIL_0001]\", mapping: Map { ... } }\n * ```\n */\nexport function createTokenizeStream(\n options: TokenizeOptions = {},\n): TransformStream<string, TokenizeResult> {\n const TS = requireTransformStream();\n return new TS<string, TokenizeResult>({\n transform(chunk, controller): void {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n controller.enqueue(tokenize(chunk, options));\n },\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/stream.ts"],"names":["ValidationError","anonymize","anonymizeAsync","tokenize"],"mappings":";;;;;;;;;;AAiCA,SAAS,sBAAA,GAAiD;AACxD,EAAA,IAAI,OAAO,oBAAoB,WAAA,EAAa;AAC1C,IAAA,MAAM,IAAIA,iCAAA;AAAA,MACR,iBAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,eAAA;AACT;AAwBO,SAAS,qBAAA,CACd,OAAA,GAA4B,EAAC,EACa;AAC1C,EAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,EAAA,OAAO,IAAI,EAAA,CAA4B;AAAA,IACrC,SAAA,CAAU,OAAO,UAAA,EAAkB;AACjC,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,QAAA,UAAA,CAAW,KAAA,CAAM,IAAIA,iCAAA,CAAgB,OAAA,EAAS,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,UAAA,CAAW,OAAA,CAAQC,2BAAA,CAAU,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,IAC9C;AAAA,GACD,CAAA;AACH;AAaO,SAAS,0BAAA,CACd,OAAA,GAA4B,EAAC,EACa;AAC1C,EAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,EAAA,OAAO,IAAI,EAAA,CAA4B;AAAA,IACrC,MAAM,SAAA,CAAU,KAAA,EAAO,UAAA,EAA2B;AAChD,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,QAAA,UAAA,CAAW,KAAA,CAAM,IAAID,iCAAA,CAAgB,OAAA,EAAS,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,IAAI;AACF,QAAA,MAAM,MAAA,GAAS,MAAME,gCAAA,CAAe,KAAA,EAAO,OAAO,CAAA;AAClD,QAAA,UAAA,CAAW,QAAQ,MAAM,CAAA;AAAA,MAC3B,SAAS,GAAA,EAAK;AACZ,QAAA,UAAA,CAAW,MAAM,GAAG,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,GACD,CAAA;AACH;AA4BO,SAAS,oBAAA,CACd,OAAA,GAA2B,EAAC,EACa;AACzC,EAAA,MAAM,KAAK,sBAAA,EAAuB;AAClC,EAAA,OAAO,IAAI,EAAA,CAA2B;AAAA,IACpC,SAAA,CAAU,OAAO,UAAA,EAAkB;AACjC,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,QAAA,UAAA,CAAW,KAAA,CAAM,IAAIF,iCAAA,CAAgB,OAAA,EAAS,kBAAkB,CAAC,CAAA;AACjE,QAAA;AAAA,MACF;AACA,MAAA,UAAA,CAAW,OAAA,CAAQG,0BAAA,CAAS,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,IAC7C;AAAA,GACD,CAAA;AACH","file":"stream.cjs","sourcesContent":["/**\n * @module stream\n * @description Streaming support for anonyma via the WHATWG Streams API.\n *\n * Provides `TransformStream`-based wrappers so anonyma can be used in\n * Node.js stream pipelines and browser fetch-response chains.\n *\n * Requires Node ≥ 18 (global `TransformStream`) or a browser with Streams API.\n *\n * @example\n * ```ts\n * import { createAnonymizeStream } from \"anonyma/stream\";\n * import { createReadStream, createWriteStream } from \"node:fs\";\n *\n * const readable = ReadableStream.from(lines);\n * const anonymized = readable.pipeThrough(createAnonymizeStream());\n * for await (const chunk of anonymized) {\n * process.stdout.write(chunk);\n * }\n * ```\n */\n\nimport { anonymize, anonymizeAsync } from \"./anonymize.js\";\nimport { tokenize } from \"./tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport type {\n AnonymizeOptions,\n AnonymizeResult,\n TokenizeResult,\n TokenizeOptions,\n} from \"./types.js\";\n\n/** Require the global `TransformStream` (Node ≥ 18 / browsers). */\nfunction requireTransformStream(): typeof TransformStream {\n if (typeof TransformStream === \"undefined\") {\n throw new ValidationError(\n \"TransformStream\",\n \"is not available in this environment. Use Node.js ≥ 18 or a polyfill.\",\n );\n }\n return TransformStream;\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizeStream()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a `TransformStream` that anonymizes each string chunk it receives.\n *\n * Input chunks are expected to be complete text strings (e.g. lines or\n * paragraphs). For true streaming over arbitrary byte chunks, split on\n * line boundaries before piping.\n *\n * @param options - Anonymization options forwarded to {@link anonymize}.\n * @returns A `TransformStream<string, AnonymizeResult>`.\n *\n * @example\n * ```ts\n * const stream = createAnonymizeStream({ defaultStrategy: { strategy: \"mask\" } });\n * const reader = readable.pipeThrough(stream).getReader();\n * const { value } = await reader.read();\n * // value: { text: \"****\", matches: [] }\n * ```\n */\nexport function createAnonymizeStream(\n options: AnonymizeOptions = {},\n): TransformStream<string, AnonymizeResult> {\n const TS = requireTransformStream();\n return new TS<string, AnonymizeResult>({\n transform(chunk, controller): void {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n controller.enqueue(anonymize(chunk, options));\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizeStreamAsync() — uses async strategies (hash/encrypt)\n// ---------------------------------------------------------------------------\n\n/**\n * Create an async-capable `TransformStream` that anonymizes each string chunk.\n * Supports `hash`, `encrypt`, and other async strategies.\n *\n * @param options - Anonymization options forwarded to {@link anonymizeAsync}.\n * @returns A `TransformStream<string, AnonymizeResult>`.\n */\nexport function createAnonymizeStreamAsync(\n options: AnonymizeOptions = {},\n): TransformStream<string, AnonymizeResult> {\n const TS = requireTransformStream();\n return new TS<string, AnonymizeResult>({\n async transform(chunk, controller): Promise<void> {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n try {\n const result = await anonymizeAsync(chunk, options);\n controller.enqueue(result);\n } catch (err) {\n controller.error(err);\n }\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public: createTokenizeStream()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a `TransformStream` that tokenizes each string chunk it receives.\n *\n * Note: each chunk gets its **own** token map. If you need a shared map across\n * all chunks, manage the tokenization externally and feed results manually.\n *\n * @param options - Tokenization options forwarded to {@link tokenize}.\n * @returns A `TransformStream<string, TokenizeResult>`.\n *\n * @example\n * ```ts\n * const stream = createTokenizeStream({ categories: [\"email\"] });\n * const writer = stream.writable.getWriter();\n * const reader = stream.readable.getReader();\n *\n * writer.write(\"Contact alice@example.com\");\n * writer.close();\n *\n * const { value } = await reader.read();\n * // value: { text: \"Contact [EMAIL_0001]\", mapping: Map { ... } }\n * ```\n */\nexport function createTokenizeStream(\n options: TokenizeOptions = {},\n): TransformStream<string, TokenizeResult> {\n const TS = requireTransformStream();\n return new TS<string, TokenizeResult>({\n transform(chunk, controller): void {\n if (typeof chunk !== \"string\") {\n controller.error(new ValidationError(\"chunk\", \"must be a string\"));\n return;\n }\n controller.enqueue(tokenize(chunk, options));\n },\n });\n}\n"]}