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
@@ -0,0 +1,662 @@
1
+ 'use strict';
2
+
3
+ var chunkCRXRJZEV_cjs = require('./chunk-CRXRJZEV.cjs');
4
+ var chunkIHEIYZPL_cjs = require('./chunk-IHEIYZPL.cjs');
5
+ var chunkWLJN7GIS_cjs = require('./chunk-WLJN7GIS.cjs');
6
+
7
+ // src/strategies/tokenize.ts
8
+ function createTokenStore() {
9
+ return {
10
+ tokens: /* @__PURE__ */ new Map(),
11
+ index: /* @__PURE__ */ new Map(),
12
+ counters: /* @__PURE__ */ new Map()
13
+ };
14
+ }
15
+ function assignToken(store, category, value, prefix, format = "bracket") {
16
+ const indexKey = `${prefix}:${value.toLowerCase()}`;
17
+ const existing = store.index.get(indexKey);
18
+ if (existing !== void 0) return existing;
19
+ const count = (store.counters.get(prefix) ?? 0) + 1;
20
+ store.counters.set(prefix, count);
21
+ const id = format === "bracket" ? String(count).padStart(4, "0") : String(count);
22
+ const token = format === "bracket" ? `[${prefix}_${id}]` : `<${prefix}_${id}>`;
23
+ store.index.set(indexKey, token);
24
+ store.tokens.set(token, value);
25
+ return token;
26
+ }
27
+ function detokenizeText(text, store) {
28
+ const unresolved = [];
29
+ const re = /(\[[A-Z_]+_\d+\]|<[A-Z_]+_\d+>)/g;
30
+ const result = text.replace(re, (token) => {
31
+ const original = store.tokens.get(token);
32
+ if (original !== void 0) return original;
33
+ unresolved.push(token);
34
+ return token;
35
+ });
36
+ return { text: result, unresolved };
37
+ }
38
+
39
+ // src/anonymize.ts
40
+ var ALL_CATEGORIES = [
41
+ "email",
42
+ "phone",
43
+ "ssn",
44
+ "credit-card",
45
+ "ipv4",
46
+ "ipv6",
47
+ "url",
48
+ "iban",
49
+ "date-of-birth",
50
+ "name",
51
+ "address",
52
+ "passport",
53
+ "drivers-license",
54
+ "national-id",
55
+ "bank-account",
56
+ "cryptocurrency",
57
+ "tax-id",
58
+ "medical-record",
59
+ "health-insurance",
60
+ "prescription",
61
+ "api-key",
62
+ "social-media",
63
+ "vin",
64
+ "license-plate",
65
+ "tracking-number",
66
+ "case-number",
67
+ "company-registration"
68
+ ];
69
+ var TOKEN_PREFIX_MAP = {
70
+ email: "EMAIL",
71
+ phone: "PHONE",
72
+ ssn: "SSN",
73
+ "credit-card": "CREDIT_CARD",
74
+ ipv4: "IPV4",
75
+ ipv6: "IPV6",
76
+ url: "URL",
77
+ iban: "IBAN",
78
+ "date-of-birth": "DATE",
79
+ name: "PERSON",
80
+ address: "ADDRESS",
81
+ passport: "PASSPORT",
82
+ "drivers-license": "DRIVERS_LICENSE",
83
+ "national-id": "NATIONAL_ID",
84
+ "bank-account": "BANK_ACCOUNT",
85
+ cryptocurrency: "CRYPTO",
86
+ "tax-id": "TAX_ID",
87
+ "medical-record": "MEDICAL_RECORD",
88
+ "health-insurance": "HEALTH_INSURANCE",
89
+ prescription: "PRESCRIPTION",
90
+ "api-key": "API_KEY",
91
+ "social-media": "SOCIAL_MEDIA",
92
+ vin: "VIN",
93
+ "license-plate": "LICENSE_PLATE",
94
+ "tracking-number": "TRACKING_NUMBER",
95
+ "case-number": "CASE_NUMBER",
96
+ "company-registration": "COMPANY_REG"
97
+ };
98
+ function applyStrategySync(value, opts) {
99
+ switch (opts.strategy) {
100
+ case "mask":
101
+ return chunkIHEIYZPL_cjs.mask(value, opts);
102
+ case "redact":
103
+ return chunkIHEIYZPL_cjs.redact(value, opts);
104
+ case "pseudonymize":
105
+ return chunkIHEIYZPL_cjs.pseudonymize(value, opts);
106
+ case "hash":
107
+ console.warn(
108
+ "[anonyma] The `hash` strategy is async and cannot be used in the synchronous `anonymize()` pipeline. Falling back to a deterministic pseudonym. Use `anonymizeAsync()` or `hash()` for SHA-256 output."
109
+ );
110
+ return chunkIHEIYZPL_cjs.pseudonymize(value, { seed: opts.pepper ?? "__hash_fallback__", prefix: "hsh_" });
111
+ case "generalize":
112
+ return chunkIHEIYZPL_cjs.generalize(value, opts);
113
+ case "tokenize":
114
+ case "encrypt":
115
+ case "synthesize":
116
+ console.warn(
117
+ `[anonyma] anonymize() and anonymizeAsync() do not apply the \`${opts.strategy}\` strategy; the value is redacted instead. Use a pipeline of "anonyma/engine" to apply it.`
118
+ );
119
+ return chunkIHEIYZPL_cjs.redact(value);
120
+ default: {
121
+ const _exhaustive = opts;
122
+ throw new chunkWLJN7GIS_cjs.UnsupportedStrategyError(_exhaustive.strategy);
123
+ }
124
+ }
125
+ }
126
+ function deduplicateMatches(matches) {
127
+ const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);
128
+ const result = [];
129
+ let cursor = 0;
130
+ for (const m of sorted) {
131
+ if (m.start >= cursor) {
132
+ result.push(m);
133
+ cursor = m.end;
134
+ }
135
+ }
136
+ return result;
137
+ }
138
+ function resolveDetector(category, customDetectors, aggressive) {
139
+ if (customDetectors?.[category]) return customDetectors[category];
140
+ return aggressive ? chunkCRXRJZEV_cjs.AGGRESSIVE_DETECTOR_REGISTRY[category] : chunkCRXRJZEV_cjs.DETECTOR_REGISTRY[category];
141
+ }
142
+ function detectCustomPatterns(text, customPatterns) {
143
+ const results = [];
144
+ for (const cp of customPatterns) {
145
+ if (!(cp.pattern instanceof RegExp)) {
146
+ throw new chunkWLJN7GIS_cjs.ValidationError("customPatterns[].pattern", "must be a RegExp instance");
147
+ }
148
+ const flags = cp.pattern.flags.includes("g") ? cp.pattern.flags : cp.pattern.flags + "g";
149
+ const re = new RegExp(cp.pattern.source, flags);
150
+ const category = cp.category ?? "custom";
151
+ const confidence = cp.confidence ?? 0.85;
152
+ const label = cp.label ?? "[REDACTED]";
153
+ let m;
154
+ while ((m = re.exec(text)) !== null) {
155
+ results.push({
156
+ category,
157
+ value: m[0],
158
+ start: m.index,
159
+ end: m.index + m[0].length,
160
+ confidence,
161
+ replacement: label
162
+ });
163
+ }
164
+ }
165
+ return results;
166
+ }
167
+ function resolveCategories(options) {
168
+ const { rules = [], enabledCategories } = options;
169
+ if (rules.length > 0) {
170
+ return rules.map((r) => r.category);
171
+ }
172
+ if (enabledCategories) {
173
+ return ALL_CATEGORIES.filter((cat) => enabledCategories[cat] === true);
174
+ }
175
+ return [...ALL_CATEGORIES];
176
+ }
177
+ function detect(text, categories = ALL_CATEGORIES, customDetectors, aggressive) {
178
+ if (typeof text !== "string") {
179
+ throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
180
+ }
181
+ const raw = [];
182
+ for (const category of categories) {
183
+ if (!ALL_CATEGORIES.includes(category)) {
184
+ throw new chunkWLJN7GIS_cjs.UnknownCategoryError(category);
185
+ }
186
+ const detector = resolveDetector(category, customDetectors, aggressive);
187
+ raw.push(...detector(text));
188
+ }
189
+ return deduplicateMatches(raw);
190
+ }
191
+ function hasPII(text, categories = ALL_CATEGORIES, customDetectors) {
192
+ if (typeof text !== "string") {
193
+ throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
194
+ }
195
+ for (const category of categories) {
196
+ if (!ALL_CATEGORIES.includes(category)) {
197
+ throw new chunkWLJN7GIS_cjs.UnknownCategoryError(category);
198
+ }
199
+ const detector = resolveDetector(category, customDetectors);
200
+ if (detector(text).length > 0) return true;
201
+ }
202
+ return false;
203
+ }
204
+ function anonymize(text, options = {}) {
205
+ if (typeof text !== "string") {
206
+ throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
207
+ }
208
+ if (options.globalReplacement?.trim().length === 0) {
209
+ throw new chunkWLJN7GIS_cjs.ValidationError("globalReplacement", "must not be an empty string");
210
+ }
211
+ let resolvedPreset;
212
+ if (options.preset) {
213
+ try {
214
+ resolvedPreset = chunkIHEIYZPL_cjs.getPreset(options.preset);
215
+ } catch {
216
+ throw new chunkWLJN7GIS_cjs.PresetNotFoundError(options.preset);
217
+ }
218
+ }
219
+ const {
220
+ rules = resolvedPreset ? resolvedPreset.categories.map((category) => ({
221
+ category,
222
+ strategy: resolvedPreset.rules?.find((r) => r.category === category)?.strategy ?? resolvedPreset.defaultStrategy
223
+ })) : [],
224
+ defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: "redact" },
225
+ includeMatches = false,
226
+ customDetectors,
227
+ customPatterns = [],
228
+ globalReplacement,
229
+ consistentTokens = false,
230
+ aggressive = false,
231
+ enabledCategories,
232
+ allowlist = [],
233
+ allowlistPatterns = [],
234
+ allowlistCaseSensitive = false,
235
+ confidenceThreshold = 0
236
+ } = options;
237
+ const ruleMap = /* @__PURE__ */ new Map();
238
+ for (const rule of rules) {
239
+ if (!ALL_CATEGORIES.includes(rule.category)) {
240
+ throw new chunkWLJN7GIS_cjs.UnknownCategoryError(rule.category);
241
+ }
242
+ ruleMap.set(rule.category, rule.strategy);
243
+ }
244
+ const categories = resolveCategories({
245
+ rules,
246
+ ...enabledCategories !== void 0 ? { enabledCategories } : {}
247
+ });
248
+ const compiledAllowlistPatterns = [
249
+ ...allowlistPatterns,
250
+ ...allowlist.map(
251
+ (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
252
+ )
253
+ ];
254
+ function isAllowlisted(value) {
255
+ if (compiledAllowlistPatterns.length === 0) return false;
256
+ return compiledAllowlistPatterns.some((re) => re.test(value));
257
+ }
258
+ const builtInMatches = detect(text, categories, customDetectors, aggressive);
259
+ const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
260
+ const filteredBuiltInMatches = builtInMatches.filter(
261
+ (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
262
+ );
263
+ const allRaw = [...filteredBuiltInMatches, ...customMatches];
264
+ const allDeduped = deduplicateMatches(allRaw);
265
+ const tokenMap = /* @__PURE__ */ new Map();
266
+ const tokenCounters = /* @__PURE__ */ new Map();
267
+ function assignToken2(category, value) {
268
+ const prefix = TOKEN_PREFIX_MAP[category] ?? category.toUpperCase();
269
+ const key = `${prefix}:${value.toLowerCase()}`;
270
+ const existing = tokenMap.get(key);
271
+ if (existing) return existing;
272
+ const count = (tokenCounters.get(prefix) ?? 0) + 1;
273
+ tokenCounters.set(prefix, count);
274
+ const token = `${prefix}_${String(count)}`;
275
+ tokenMap.set(key, token);
276
+ return token;
277
+ }
278
+ let result = text;
279
+ const reversed = [...allDeduped].reverse();
280
+ for (const match of reversed) {
281
+ let replacement;
282
+ if (globalReplacement !== void 0) {
283
+ replacement = globalReplacement;
284
+ } else if (consistentTokens) {
285
+ replacement = assignToken2(match.category, match.value);
286
+ } else if ("replacement" in match) {
287
+ replacement = match.replacement;
288
+ } else {
289
+ const strategy = ruleMap.get(match.category) ?? defaultStrategy;
290
+ replacement = applyStrategySync(match.value, strategy);
291
+ }
292
+ result = result.slice(0, match.start) + replacement + result.slice(match.end);
293
+ }
294
+ const reportedMatches = includeMatches ? filteredBuiltInMatches : [];
295
+ return {
296
+ text: result,
297
+ matches: reportedMatches
298
+ };
299
+ }
300
+ async function anonymizeAsync(text, options = {}) {
301
+ if (typeof text !== "string") {
302
+ throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
303
+ }
304
+ const hasAsyncStrategy = (opts) => opts.strategy === "hash" || opts.strategy === "encrypt" || opts.strategy === "tokenize" || opts.strategy === "synthesize";
305
+ const needsAsync = options.defaultStrategy != null && hasAsyncStrategy(options.defaultStrategy) || (options.rules ?? []).some((r) => hasAsyncStrategy(r.strategy));
306
+ if (!needsAsync) {
307
+ return anonymize(text, options);
308
+ }
309
+ const { hash: hashFn } = await import('./hash-2PSYNDMM.cjs');
310
+ let resolvedPreset;
311
+ if (options.preset) {
312
+ try {
313
+ resolvedPreset = chunkIHEIYZPL_cjs.getPreset(options.preset);
314
+ } catch {
315
+ throw new chunkWLJN7GIS_cjs.PresetNotFoundError(options.preset);
316
+ }
317
+ }
318
+ const {
319
+ rules = resolvedPreset ? resolvedPreset.categories.map((category) => ({
320
+ category,
321
+ strategy: resolvedPreset.rules?.find((r) => r.category === category)?.strategy ?? resolvedPreset.defaultStrategy
322
+ })) : [],
323
+ defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: "redact" },
324
+ includeMatches = false,
325
+ customDetectors,
326
+ customPatterns = [],
327
+ globalReplacement,
328
+ consistentTokens = false,
329
+ aggressive = false,
330
+ enabledCategories,
331
+ allowlist = [],
332
+ allowlistPatterns = [],
333
+ allowlistCaseSensitive = false,
334
+ confidenceThreshold = 0
335
+ } = options;
336
+ const ruleMap = /* @__PURE__ */ new Map();
337
+ for (const rule of rules) {
338
+ if (!ALL_CATEGORIES.includes(rule.category)) throw new chunkWLJN7GIS_cjs.UnknownCategoryError(rule.category);
339
+ ruleMap.set(rule.category, rule.strategy);
340
+ }
341
+ const categories = resolveCategories({
342
+ rules,
343
+ ...enabledCategories !== void 0 ? { enabledCategories } : {}
344
+ });
345
+ const builtInMatches = detect(text, categories, customDetectors, aggressive);
346
+ const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
347
+ const compiledAllowlistPatterns = [
348
+ ...allowlistPatterns,
349
+ ...allowlist.map(
350
+ (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
351
+ )
352
+ ];
353
+ const isAllowlisted = (value) => compiledAllowlistPatterns.some((re) => re.test(value));
354
+ const filteredBuiltInMatches = builtInMatches.filter(
355
+ (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
356
+ );
357
+ const allRaw = [...filteredBuiltInMatches, ...customMatches];
358
+ const allDeduped = deduplicateMatches(allRaw);
359
+ const tokenMap = /* @__PURE__ */ new Map();
360
+ const tokenCounters = /* @__PURE__ */ new Map();
361
+ function assignToken2(category, value) {
362
+ const prefix = TOKEN_PREFIX_MAP[category] ?? category.toUpperCase();
363
+ const key = `${prefix}:${value.toLowerCase()}`;
364
+ const existing = tokenMap.get(key);
365
+ if (existing) return existing;
366
+ const count = (tokenCounters.get(prefix) ?? 0) + 1;
367
+ tokenCounters.set(prefix, count);
368
+ const token = `${prefix}_${String(count)}`;
369
+ tokenMap.set(key, token);
370
+ return token;
371
+ }
372
+ let result = text;
373
+ const reversed = [...allDeduped].reverse();
374
+ for (const match of reversed) {
375
+ let replacement;
376
+ if (globalReplacement !== void 0) {
377
+ replacement = globalReplacement;
378
+ } else if (consistentTokens) {
379
+ replacement = assignToken2(match.category, match.value);
380
+ } else if ("replacement" in match) {
381
+ replacement = match.replacement;
382
+ } else {
383
+ const strategy = ruleMap.get(match.category) ?? defaultStrategy;
384
+ if (strategy.strategy === "hash") {
385
+ replacement = await hashFn(match.value, strategy);
386
+ } else {
387
+ replacement = applyStrategySync(match.value, strategy);
388
+ }
389
+ }
390
+ result = result.slice(0, match.start) + replacement + result.slice(match.end);
391
+ }
392
+ return {
393
+ text: result,
394
+ matches: includeMatches ? filteredBuiltInMatches : []
395
+ };
396
+ }
397
+ function anonymizeObject(obj, options) {
398
+ if (typeof obj !== "object") {
399
+ throw new chunkWLJN7GIS_cjs.ValidationError("obj", "must be an object");
400
+ }
401
+ return deepAnonymizeValue(obj, options, /* @__PURE__ */ new WeakSet());
402
+ }
403
+ function deepAnonymizeValue(value, options, seen) {
404
+ if (value === null || value === void 0) return value;
405
+ if (typeof value === "string") {
406
+ return anonymize(value, options).text;
407
+ }
408
+ if (typeof value !== "object") {
409
+ return value;
410
+ }
411
+ if (seen.has(value)) {
412
+ throw new chunkWLJN7GIS_cjs.ValidationError("obj", "contains a circular reference");
413
+ }
414
+ seen.add(value);
415
+ if (Array.isArray(value)) {
416
+ const result2 = value.map((item) => deepAnonymizeValue(item, options, seen));
417
+ seen.delete(value);
418
+ return result2;
419
+ }
420
+ const result = {};
421
+ for (const key of Object.keys(value)) {
422
+ result[key] = deepAnonymizeValue(value[key], options, seen);
423
+ }
424
+ seen.delete(value);
425
+ return result;
426
+ }
427
+ function getByPath(obj, path) {
428
+ const parts = path.split(".");
429
+ let current = obj;
430
+ for (const part of parts) {
431
+ if (current === null || typeof current !== "object" || Array.isArray(current)) {
432
+ return void 0;
433
+ }
434
+ current = current[part];
435
+ }
436
+ return current;
437
+ }
438
+ function setByPath(obj, path, value) {
439
+ const parts = path.split(".");
440
+ if (parts.length === 1) {
441
+ return { ...obj, [path]: value };
442
+ }
443
+ const [head, ...tail] = parts;
444
+ const nested = obj[head] ?? {};
445
+ return {
446
+ ...obj,
447
+ [head]: setByPath(nested, tail.join("."), value)
448
+ };
449
+ }
450
+ function anonymizeRecord(record, rules) {
451
+ if (typeof record !== "object" || Array.isArray(record)) {
452
+ throw new chunkWLJN7GIS_cjs.ValidationError("record", "must be a plain object");
453
+ }
454
+ let result = { ...record };
455
+ for (const [path, rule] of Object.entries(rules)) {
456
+ if (Object.prototype.hasOwnProperty.call(rules, path)) {
457
+ const raw = getByPath(result, path);
458
+ if (raw === void 0 || raw === null) continue;
459
+ if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "boolean") continue;
460
+ const strValue = String(raw);
461
+ const anonymized = applyStrategySync(strValue, rule.strategy);
462
+ result = setByPath(result, path, anonymized);
463
+ }
464
+ }
465
+ return result;
466
+ }
467
+ function createAnonymizer(config = {}) {
468
+ let presetConfig;
469
+ if (config.preset) {
470
+ try {
471
+ presetConfig = chunkIHEIYZPL_cjs.getPreset(config.preset);
472
+ } catch {
473
+ throw new chunkWLJN7GIS_cjs.PresetNotFoundError(config.preset);
474
+ }
475
+ }
476
+ const {
477
+ categories = presetConfig ? presetConfig.categories : [...ALL_CATEGORIES],
478
+ defaultStrategy = presetConfig?.defaultStrategy ?? { strategy: "redact" },
479
+ customDetectors,
480
+ customPatterns,
481
+ globalReplacement,
482
+ consistentTokens,
483
+ aggressive
484
+ } = config;
485
+ for (const cat of categories) {
486
+ if (!ALL_CATEGORIES.includes(cat)) {
487
+ throw new chunkWLJN7GIS_cjs.UnknownCategoryError(cat);
488
+ }
489
+ }
490
+ function baseOptions(overrides) {
491
+ const base = {
492
+ defaultStrategy,
493
+ ...customDetectors !== void 0 ? { customDetectors } : {},
494
+ ...customPatterns !== void 0 ? { customPatterns } : {},
495
+ ...globalReplacement !== void 0 ? { globalReplacement } : {},
496
+ ...consistentTokens !== void 0 ? { consistentTokens } : {},
497
+ ...aggressive !== void 0 ? { aggressive } : {},
498
+ ...overrides,
499
+ rules: overrides?.rules ?? (presetConfig ? presetConfig.categories.map((category) => ({
500
+ category,
501
+ strategy: presetConfig.rules?.find((r) => r.category === category)?.strategy ?? defaultStrategy
502
+ })) : categories.map((category) => ({
503
+ category,
504
+ strategy: defaultStrategy
505
+ })))
506
+ };
507
+ return base;
508
+ }
509
+ return {
510
+ anonymize(text, options) {
511
+ return anonymize(text, baseOptions(options));
512
+ },
513
+ detect(text) {
514
+ return detect(text, categories, customDetectors, aggressive);
515
+ },
516
+ anonymizeRecord(record, rules) {
517
+ return anonymizeRecord(record, rules);
518
+ },
519
+ anonymizeObject(obj, options) {
520
+ return anonymizeObject(obj, baseOptions(options));
521
+ },
522
+ async anonymizeAsync(text, options) {
523
+ return anonymizeAsync(text, baseOptions(options));
524
+ },
525
+ tokenize(text, options) {
526
+ const {
527
+ categories: tCats,
528
+ format = "bracket",
529
+ customDetectors: tCustDet,
530
+ aggressive: tAgg = aggressive,
531
+ confidenceThreshold: tConfidence = 0,
532
+ allowlist: tAllowlist = [],
533
+ allowlistCaseSensitive: tCaseSensitive = false
534
+ } = options ?? {};
535
+ const tCompiledAllowlist = tAllowlist.map(
536
+ (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&"), tCaseSensitive ? "" : "i")
537
+ );
538
+ const isAllowlisted = (v) => tCompiledAllowlist.some((re) => re.test(v));
539
+ const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(
540
+ (m) => m.confidence >= tConfidence && !isAllowlisted(m.value)
541
+ );
542
+ const store = createTokenStore();
543
+ let tResult = text;
544
+ const tTokens = [];
545
+ for (const match of [...tMatches].reverse()) {
546
+ const prefix = TOKEN_PREFIX_MAP[match.category];
547
+ const token = assignToken(store, match.category, match.value, prefix, format);
548
+ tTokens.push({
549
+ token,
550
+ original: match.value,
551
+ category: match.category,
552
+ start: match.start,
553
+ end: match.end
554
+ });
555
+ tResult = tResult.slice(0, match.start) + token + tResult.slice(match.end);
556
+ }
557
+ return { text: tResult, mapping: store.tokens, tokens: tTokens };
558
+ },
559
+ hasPII(text) {
560
+ return hasPII(text, categories, customDetectors);
561
+ }
562
+ };
563
+ }
564
+
565
+ // src/tokenize.ts
566
+ var TOKEN_PREFIX_MAP2 = {
567
+ email: "EMAIL",
568
+ phone: "PHONE",
569
+ ssn: "SSN",
570
+ "credit-card": "CREDIT_CARD",
571
+ ipv4: "IPV4",
572
+ ipv6: "IPV6",
573
+ url: "URL",
574
+ iban: "IBAN",
575
+ "date-of-birth": "DATE",
576
+ name: "PERSON",
577
+ address: "ADDRESS",
578
+ passport: "PASSPORT",
579
+ "drivers-license": "DRIVERS_LICENSE",
580
+ "national-id": "NATIONAL_ID",
581
+ "bank-account": "BANK_ACCOUNT",
582
+ cryptocurrency: "CRYPTO",
583
+ "tax-id": "TAX_ID",
584
+ "medical-record": "MEDICAL_RECORD",
585
+ "health-insurance": "HEALTH_INSURANCE",
586
+ prescription: "PRESCRIPTION",
587
+ "api-key": "API_KEY",
588
+ "social-media": "SOCIAL_MEDIA",
589
+ vin: "VIN",
590
+ "license-plate": "LICENSE_PLATE",
591
+ "tracking-number": "TRACKING_NUMBER",
592
+ "case-number": "CASE_NUMBER",
593
+ "company-registration": "COMPANY_REG"
594
+ };
595
+ function tokenize(text, options = {}) {
596
+ if (typeof text !== "string") throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
597
+ const {
598
+ categories,
599
+ format = "bracket",
600
+ customDetectors,
601
+ aggressive = false,
602
+ confidenceThreshold = 0,
603
+ allowlist = [],
604
+ allowlistCaseSensitive = false
605
+ } = options;
606
+ const compiledAllowlist = allowlist.map(
607
+ (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
608
+ );
609
+ const isAllowlisted = (v) => compiledAllowlist.some((re) => re.test(v));
610
+ const allMatches = detect(text, categories, customDetectors, aggressive).filter(
611
+ (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
612
+ );
613
+ const store = createTokenStore();
614
+ let result = text;
615
+ const reversed = [...allMatches].reverse();
616
+ const tokenMatches = [];
617
+ for (const match of reversed) {
618
+ const prefix = TOKEN_PREFIX_MAP2[match.category] ?? match.category.toUpperCase();
619
+ const token = assignToken(store, match.category, match.value, prefix, format);
620
+ tokenMatches.push({
621
+ token,
622
+ original: match.value,
623
+ category: match.category,
624
+ start: match.start,
625
+ end: match.end
626
+ });
627
+ result = result.slice(0, match.start) + token + result.slice(match.end);
628
+ }
629
+ return { text: result, mapping: store.tokens, tokens: tokenMatches };
630
+ }
631
+ function tokenizeAsync(text, options = {}) {
632
+ return Promise.resolve(tokenize(text, options));
633
+ }
634
+ function detokenize(text, mapping) {
635
+ if (typeof text !== "string") throw new chunkWLJN7GIS_cjs.ValidationError("text", "must be a string");
636
+ const store = createTokenStore();
637
+ for (const [token, value] of mapping) {
638
+ store.tokens.set(token, value);
639
+ }
640
+ const result = detokenizeText(text, store);
641
+ const TOKEN_RE = /(\[[A-Z_]+_\d+\]|<[A-Z_]+_\d+>)/g;
642
+ const totalInText = (text.match(TOKEN_RE) ?? []).length;
643
+ const replacedCount = totalInText - result.unresolved.length;
644
+ return {
645
+ text: result.text,
646
+ replacedCount,
647
+ unresolved: result.unresolved
648
+ };
649
+ }
650
+
651
+ exports.anonymize = anonymize;
652
+ exports.anonymizeAsync = anonymizeAsync;
653
+ exports.anonymizeObject = anonymizeObject;
654
+ exports.anonymizeRecord = anonymizeRecord;
655
+ exports.createAnonymizer = createAnonymizer;
656
+ exports.detect = detect;
657
+ exports.detokenize = detokenize;
658
+ exports.hasPII = hasPII;
659
+ exports.tokenize = tokenize;
660
+ exports.tokenizeAsync = tokenizeAsync;
661
+ //# sourceMappingURL=chunk-26IHMQHL.cjs.map
662
+ //# sourceMappingURL=chunk-26IHMQHL.cjs.map