@stll/anonymize-wasm 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/dist/wasm.d.mts CHANGED
@@ -361,6 +361,19 @@ type ReviewedEntity = Entity & {
361
361
  decision?: ReviewDecision;
362
362
  originalLabel?: string;
363
363
  };
364
+ /**
365
+ * A single entry in the workspace-scoped gazetteer
366
+ * (deny list). Persisted in IndexedDB.
367
+ */
368
+ type GazetteerEntry = {
369
+ id: string;
370
+ canonical: string;
371
+ label: string;
372
+ variants: string[];
373
+ workspaceId: string;
374
+ createdAt: number;
375
+ source: "manual" | "confirmed-from-model";
376
+ };
364
377
  /** Per-label operator selection. Key is the entity label. */
365
378
  type OperatorConfig = {
366
379
  /** Operator per label. Missing labels default to "replace". */operators: Record<string, OperatorType>; /** Custom replacement string for the redact operator. */
@@ -390,6 +403,183 @@ type RedactionResult = {
390
403
  operatorMap: Map<string, OperatorType>;
391
404
  entityCount: number;
392
405
  };
406
+ /**
407
+ * Configuration for the detection pipeline.
408
+ */
409
+ type DenyListCategory = "Names" | "Places" | "Addresses" | "Courts" | "Financial" | "Government" | "Healthcare" | "Education" | "Political" | "Organizations" | "International";
410
+ /**
411
+ * Metadata for a single dictionary entry in the
412
+ * deny-list system. Mirrors the shape from
413
+ * the anonymize-data package so consumers can pass
414
+ * pre-loaded data without a runtime dependency.
415
+ */
416
+ type DictionaryMeta = {
417
+ label: string;
418
+ category: DenyListCategory;
419
+ country: string | null;
420
+ };
421
+ /**
422
+ * Caller-supplied exact terms for deny-list matching.
423
+ * These entries are merged with the published deny-list
424
+ * dictionaries when `enableDenyList` is enabled.
425
+ */
426
+ type CustomDenyListEntry = {
427
+ value: string;
428
+ label: string;
429
+ variants?: readonly string[];
430
+ };
431
+ /**
432
+ * Caller-supplied regex detector. The pattern is passed
433
+ * to the underlying text-search regex engine, so use its
434
+ * supported regex syntax. Inline flags such as `(?i)` are
435
+ * accepted when supported by that engine.
436
+ */
437
+ type CustomRegexPattern = {
438
+ pattern: string;
439
+ label: string;
440
+ score?: number;
441
+ preparedArtifactPolicy?: "include" | "omit";
442
+ };
443
+ /**
444
+ * Pre-loaded dictionary data for dependency injection.
445
+ * Consumers that want name/city/deny-list detection
446
+ * load dictionaries themselves (e.g. from the
447
+ * anonymize-data package) and pass them here; the
448
+ * anonymize package has zero cross-package imports.
449
+ *
450
+ * All fields are optional. When a field is absent,
451
+ * the corresponding detection path is skipped (same
452
+ * behavior as when no dictionaries are available).
453
+ */
454
+ type Dictionaries = {
455
+ /**
456
+ * First names per language code (e.g., "cs", "de").
457
+ * Merged with legacy config names at init time.
458
+ */
459
+ firstNames?: Readonly<Record<string, readonly string[]>>;
460
+ /**
461
+ * Surnames per language code.
462
+ * Merged with legacy config names at init time.
463
+ */
464
+ surnames?: Readonly<Record<string, readonly string[]>>;
465
+ /**
466
+ * Non-Western name tokens per locale code
467
+ * (e.g., "in", "ar", "ja-latn", "ko", "zh-latn",
468
+ * "th", "vi", "fil", "id"). Merged with bundled
469
+ * names-nw-*.json data at init time.
470
+ */
471
+ nonWesternNames?: Readonly<Record<string, readonly string[]>>;
472
+ /**
473
+ * Pre-loaded deny-list dictionaries keyed by
474
+ * dictionary ID (e.g., "courts/CZ", "banks/DE").
475
+ * Each value is the array of terms for that
476
+ * dictionary.
477
+ */
478
+ denyList?: Readonly<Record<string, readonly string[]>>;
479
+ /**
480
+ * Metadata per dictionary ID. Required when
481
+ * `denyList` is provided so the pipeline knows
482
+ * labels, categories, and country filters.
483
+ */
484
+ denyListMeta?: Readonly<Record<string, DictionaryMeta>>;
485
+ /**
486
+ * Pre-loaded city names, already merged across
487
+ * all desired countries.
488
+ *
489
+ * Prefer `citiesByCountry` when callers also pass
490
+ * `denyListCountries` / `denyListRegions`; merged
491
+ * city arrays cannot be scoped after injection.
492
+ */
493
+ cities?: readonly string[];
494
+ /**
495
+ * Pre-loaded city names keyed by ISO 3166-1 alpha-2
496
+ * country code. When provided, the deny-list builder
497
+ * applies `denyListCountries` / `denyListRegions`
498
+ * before adding city patterns to the search automaton.
499
+ */
500
+ citiesByCountry?: Readonly<Record<string, readonly string[]>>;
501
+ };
502
+ type PipelineConfig = {
503
+ threshold: number;
504
+ enableTriggerPhrases: boolean;
505
+ enableRegex: boolean;
506
+ /**
507
+ * Expected content language codes. When present, these
508
+ * derive default dictionary scopes for name corpus and
509
+ * deny-list matching unless the lower-level scope fields
510
+ * below are set explicitly.
511
+ */
512
+ languages?: string[];
513
+ /**
514
+ * Convenience form for single-language documents. Ignored
515
+ * when `languages` is also provided.
516
+ */
517
+ language?: string;
518
+ /**
519
+ * Enables legal-form organization detection.
520
+ * Required for typed callers; legacy untyped
521
+ * callers that omit this field are treated as
522
+ * enabled at runtime for backward compatibility.
523
+ */
524
+ enableLegalForms: boolean;
525
+ /**
526
+ * Enables first-name/surname/title corpus matching.
527
+ * When deny-list mode is enabled, this also controls
528
+ * whether name-corpus entries are injected into the
529
+ * deny-list search automaton.
530
+ */
531
+ enableNameCorpus: boolean;
532
+ /**
533
+ * Optional language scope for first-name/surname
534
+ * dictionaries, using the keys present in
535
+ * `dictionaries.firstNames` / `dictionaries.surnames`
536
+ * (for example `["en", "de"]`). When omitted, all
537
+ * injected name languages are used for backward
538
+ * compatibility.
539
+ */
540
+ nameCorpusLanguages?: string[];
541
+ enableDenyList: boolean;
542
+ denyListCountries?: string[];
543
+ denyListRegions?: string[];
544
+ denyListExcludeCategories?: string[];
545
+ /**
546
+ * Caller-owned exact terms to match through the
547
+ * deny-list layer. Requires `enableDenyList: true`.
548
+ */
549
+ customDenyList?: readonly CustomDenyListEntry[];
550
+ /**
551
+ * Caller-owned regex detectors. Requires
552
+ * `enableRegex: true`.
553
+ */
554
+ customRegexes?: readonly CustomRegexPattern[];
555
+ enableGazetteer: boolean;
556
+ /**
557
+ * Detect country names (ISO 3166-1 names, curated
558
+ * aliases, alpha-3 codes). Defaults to true. Names
559
+ * span all manifest languages plus widely-used
560
+ * additions (Dutch, Russian, Chinese, Arabic, etc.).
561
+ */
562
+ enableCountries?: boolean;
563
+ enableNer: boolean;
564
+ enableConfidenceBoost: boolean;
565
+ enableCoreference: boolean;
566
+ enableZoneClassification?: boolean;
567
+ enableHotwordRules?: boolean;
568
+ /**
569
+ * Requested output labels. An empty array means
570
+ * "do not filter by label" for deterministic
571
+ * detectors; NER falls back to DEFAULT_ENTITY_LABELS.
572
+ */
573
+ labels: string[];
574
+ workspaceId: string;
575
+ /**
576
+ * Pre-loaded dictionary data for name, deny-list,
577
+ * and city detection. When omitted, dictionary-based
578
+ * detection paths are skipped. Consumers load from
579
+ * the anonymize-data package and pass the data here.
580
+ */
581
+ dictionaries?: Dictionaries;
582
+ };
393
583
  //#endregion
394
584
  //#region src/native.d.ts
395
585
  type NativeBindingOperatorConfig = {
@@ -596,6 +786,22 @@ type PreparedSearch = PreparedNativeAnonymizer;
596
786
  declare const PreparedAnonymizer: typeof PreparedNativeAnonymizer;
597
787
  type PreparedAnonymizer = PreparedNativeAnonymizer;
598
788
  //#endregion
789
+ //#region src/context.d.ts
790
+ /**
791
+ * Cached state for a single pipeline run (or a sequence of runs sharing the
792
+ * same config). The native pipeline builds its prepared package once and reuses
793
+ * it across calls with the same config; the package bytes and the key/promise
794
+ * that guard concurrent builds live here so callers can share one warmed
795
+ * context.
796
+ */
797
+ type PipelineContext = {
798
+ nativePipelinePackage: Uint8Array | null;
799
+ nativePipelinePackageKey: string;
800
+ nativePipelinePackagePromise: Promise<Uint8Array> | null;
801
+ };
802
+ /** Create a fresh, empty pipeline context. */
803
+ declare const createPipelineContext: () => PipelineContext;
804
+ //#endregion
599
805
  //#region src/redact.d.ts
600
806
  /**
601
807
  * Serialize the redaction key to JSON for export.
@@ -609,6 +815,44 @@ declare const exportRedactionKey: (redactionMap: Map<string, string>, operatorMa
609
815
  */
610
816
  declare const deanonymise: (redactedText: string, redactionMap: Map<string, string>) => string;
611
817
  //#endregion
818
+ //#region src/native-pipeline.d.ts
819
+ type NativePipelineUnsupportedFeature = "enableNer";
820
+ type NativePipelineCompatibility = {
821
+ status: "supported";
822
+ } | {
823
+ status: "unsupported";
824
+ unsupportedFeatures: NativePipelineUnsupportedFeature[];
825
+ };
826
+ type NativePipelineBuildOptions = {
827
+ binding: NativeAnonymizeBinding;
828
+ config: PipelineConfig;
829
+ gazetteerEntries?: GazetteerEntry[];
830
+ context?: PipelineContext;
831
+ };
832
+ type NativePipelinePackageOptions = NativePipelineBuildOptions & {
833
+ compressed?: boolean;
834
+ };
835
+ declare const getNativePipelineCompatibility: (config: PipelineConfig) => NativePipelineCompatibility;
836
+ declare const assertNativePipelineSupported: (config: PipelineConfig) => void;
837
+ declare const prepareNativePipelineConfig: ({
838
+ binding,
839
+ config,
840
+ gazetteerEntries
841
+ }: Omit<NativePipelineBuildOptions, "context">) => Promise<NativePreparedSearchConfig>;
842
+ declare const prepareNativePipelinePackage: ({
843
+ binding,
844
+ config,
845
+ gazetteerEntries,
846
+ context,
847
+ compressed
848
+ }: NativePipelinePackageOptions) => Promise<Uint8Array>;
849
+ declare const createNativePipelineFromConfig: ({
850
+ binding,
851
+ config,
852
+ gazetteerEntries,
853
+ context
854
+ }: NativePipelineBuildOptions) => Promise<PreparedNativePipeline>;
855
+ //#endregion
612
856
  //#region src/wasm.d.ts
613
857
  /** A prepared package the caller supplies: raw bytes, an ArrayBuffer, or a URL
614
858
  * (string or `URL`) that resolves to the package and is fetched. */
@@ -664,5 +908,5 @@ declare const diagnostics_json: (config: NativeSearchPackageInput, fullText: str
664
908
  declare const diagnostics_stream_json: (config: NativeSearchPackageInput, fullText: string, onBatch: NativeDiagnosticsBatchCallback, operators?: NativeOperatorConfig, options?: WasmBindingOptions) => Promise<string | null>;
665
909
  declare const summary_diagnostics_json: (config: NativeSearchPackageInput, fullText: string, operators?: NativeOperatorConfig, options?: WasmBindingOptions) => Promise<string | null>;
666
910
  //#endregion
667
- export { type AnonymisationOperator, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, type DetectionSource, type Entity, LoadPreparedPackageOptions, NativeAnonymizeBinding, NativeAnonymizerFromConfigOptions, NativeAnonymizerFromPackageOptions, NativeBindingVersionOptions, NativeDiagnosticsBatchCallback, NativeNormalizeOptions, NativeOperatorConfig, NativePipelineEntity, NativePipelineFromPackageOptions, NativePreparedSearchBinding, type NativePreparedSearchConfig, NativeRedactionResult, NativeResultEventCallback, NativeSearchPackageInput, NativeSearchPackageOptions, NativeStaticRedactionResult, OPERATOR_TYPES, type OperatorConfig, type OperatorType, PrepareSearchPackageOptions, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedPackageSource, PreparedSearch, type RedactionResult, type ReviewDecision, type ReviewedEntity, SharedNativeDiagnosticsJsonOptions, SharedNativeDiagnosticsStreamJsonOptions, SharedNativePreparedPackageOptions, SharedNativeRedactTextJsonOptions, SharedNativeRedactTextOptions, SharedNativeRedactTextStreamJsonOptions, SharedNativeSearchPackageOptions, WasmBindingOptions, assertNativeBindingVersion, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromPackage, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
911
+ export { type AnonymisationOperator, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, type DetectionSource, type Dictionaries, type Entity, type GazetteerEntry, LoadPreparedPackageOptions, NativeAnonymizeBinding, NativeAnonymizerFromConfigOptions, NativeAnonymizerFromPackageOptions, NativeBindingVersionOptions, NativeDiagnosticsBatchCallback, NativeNormalizeOptions, NativeOperatorConfig, type NativePipelineBuildOptions, type NativePipelineCompatibility, NativePipelineEntity, NativePipelineFromPackageOptions, type NativePipelinePackageOptions, type NativePipelineUnsupportedFeature, NativePreparedSearchBinding, type NativePreparedSearchConfig, NativeRedactionResult, NativeResultEventCallback, NativeSearchPackageInput, NativeSearchPackageOptions, NativeStaticRedactionResult, OPERATOR_TYPES, type OperatorConfig, type OperatorType, type PipelineConfig, type PipelineContext, PrepareSearchPackageOptions, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedPackageSource, PreparedSearch, type RedactionResult, type ReviewDecision, type ReviewedEntity, SharedNativeDiagnosticsJsonOptions, SharedNativeDiagnosticsStreamJsonOptions, SharedNativePreparedPackageOptions, SharedNativeRedactTextJsonOptions, SharedNativeRedactTextOptions, SharedNativeRedactTextStreamJsonOptions, SharedNativeSearchPackageOptions, WasmBindingOptions, assertNativeBindingVersion, assertNativePipelineSupported, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipelineContext, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
668
912
  //# sourceMappingURL=wasm.d.mts.map
package/dist/wasm.mjs CHANGED
@@ -222,6 +222,20 @@ const toOperatorMap = (entries) => {
222
222
  return map;
223
223
  };
224
224
  //#endregion
225
+ //#region src/context.ts
226
+ /** Create a fresh, empty pipeline context. */
227
+ const createPipelineContext = () => ({
228
+ nativePipelinePackage: null,
229
+ nativePipelinePackageKey: "",
230
+ nativePipelinePackagePromise: null
231
+ });
232
+ /**
233
+ * Module-level default context. Used when callers
234
+ * don't provide an explicit context, preserving full
235
+ * backward compatibility with the existing API.
236
+ */
237
+ const defaultContext = createPipelineContext();
238
+ //#endregion
225
239
  //#region src/redact.ts
226
240
  /**
227
241
  * Serialize the redaction key to JSON for export.
@@ -246,6 +260,314 @@ const deanonymise = (redactedText, redactionMap) => {
246
260
  return result;
247
261
  };
248
262
  //#endregion
263
+ //#region src/types.ts
264
+ const isLegalFormsEnabled = (config) => config.enableLegalForms !== false;
265
+ //#endregion
266
+ //#region src/language-scope.ts
267
+ const scopeData = {
268
+ _comment: "Default dictionary scopes for content language hints. Lower-level caller config can still override name corpus languages and deny-list countries independently.",
269
+ languages: {
270
+ "cs": {
271
+ "nameCorpusLanguages": ["cs", "sk"],
272
+ "denyListCountries": ["CZ", "SK"]
273
+ },
274
+ "de": {
275
+ "nameCorpusLanguages": ["de"],
276
+ "denyListCountries": [
277
+ "DE",
278
+ "AT",
279
+ "CH"
280
+ ]
281
+ },
282
+ "en": {
283
+ "nameCorpusLanguages": ["en"],
284
+ "denyListCountries": [
285
+ "US",
286
+ "GB",
287
+ "CA",
288
+ "AU",
289
+ "IE"
290
+ ]
291
+ },
292
+ "es": {
293
+ "nameCorpusLanguages": ["es"],
294
+ "denyListCountries": [
295
+ "ES",
296
+ "MX",
297
+ "AR",
298
+ "CL",
299
+ "CO",
300
+ "PE",
301
+ "EC",
302
+ "VE",
303
+ "UY",
304
+ "PY",
305
+ "BO",
306
+ "CR",
307
+ "PA",
308
+ "DO",
309
+ "GT",
310
+ "HN",
311
+ "SV",
312
+ "NI",
313
+ "CU"
314
+ ]
315
+ },
316
+ "fr": {
317
+ "nameCorpusLanguages": ["fr"],
318
+ "denyListCountries": [
319
+ "FR",
320
+ "BE",
321
+ "CH",
322
+ "CA",
323
+ "LU",
324
+ "MC"
325
+ ]
326
+ },
327
+ "hu": {
328
+ "nameCorpusLanguages": ["hu"],
329
+ "denyListCountries": ["HU"]
330
+ },
331
+ "it": {
332
+ "nameCorpusLanguages": ["it"],
333
+ "denyListCountries": ["IT", "CH"]
334
+ },
335
+ "pl": {
336
+ "nameCorpusLanguages": ["pl"],
337
+ "denyListCountries": ["PL"]
338
+ },
339
+ "pt-br": {
340
+ "nameCorpusLanguages": ["pt-br"],
341
+ "denyListCountries": ["BR"]
342
+ },
343
+ "ro": {
344
+ "nameCorpusLanguages": ["ro"],
345
+ "denyListCountries": ["RO", "MD"]
346
+ },
347
+ "sk": {
348
+ "nameCorpusLanguages": ["sk", "cs"],
349
+ "denyListCountries": ["SK", "CZ"]
350
+ },
351
+ "sv": {
352
+ "nameCorpusLanguages": ["sv"],
353
+ "denyListCountries": ["SE", "FI"]
354
+ }
355
+ }
356
+ };
357
+ const normalizeLanguage$1 = (language) => language.trim().toLowerCase();
358
+ const fallbackLanguage = (language) => {
359
+ const index = language.indexOf("-");
360
+ return index === -1 ? null : language.slice(0, index);
361
+ };
362
+ const uniquePush = (target, values) => {
363
+ const seen = new Set(target);
364
+ for (const value of values) {
365
+ if (seen.has(value)) continue;
366
+ seen.add(value);
367
+ target.push(value);
368
+ }
369
+ };
370
+ const resolveLanguageScope = (language) => {
371
+ const normalized = normalizeLanguage$1(language);
372
+ if (normalized.length === 0) return null;
373
+ const exact = scopeData.languages[normalized];
374
+ if (exact !== void 0) return exact;
375
+ const fallback = fallbackLanguage(normalized);
376
+ return fallback === null ? null : scopeData.languages[fallback] ?? null;
377
+ };
378
+ const configuredLanguages = (config) => {
379
+ if (config.languages !== void 0) return config.languages;
380
+ return config.language === void 0 ? [] : [config.language];
381
+ };
382
+ const applyPipelineLanguageScope = (config) => {
383
+ const languages = configuredLanguages(config);
384
+ if (languages.length === 0) return config;
385
+ const nameCorpusLanguages = [];
386
+ const denyListCountries = [];
387
+ for (const language of languages) {
388
+ const scope = resolveLanguageScope(language);
389
+ if (scope === null) continue;
390
+ uniquePush(nameCorpusLanguages, scope.nameCorpusLanguages ?? []);
391
+ uniquePush(denyListCountries, scope.denyListCountries ?? []);
392
+ }
393
+ const next = {};
394
+ if (config.nameCorpusLanguages === void 0 && nameCorpusLanguages.length > 0) next.nameCorpusLanguages = nameCorpusLanguages;
395
+ if (config.denyListCountries === void 0 && denyListCountries.length > 0) next.denyListCountries = denyListCountries;
396
+ return Object.keys(next).length === 0 ? config : {
397
+ ...config,
398
+ ...next
399
+ };
400
+ };
401
+ //#endregion
402
+ //#region src/util/language-selection.ts
403
+ const normalizeLanguageCode = (language) => language.trim().toLowerCase();
404
+ const normalizeLanguageSelection = (languages) => languages === void 0 ? [] : languages.map(normalizeLanguageCode).filter((language) => language.length > 0);
405
+ const languageSelectionKey = (languages) => {
406
+ const normalized = normalizeLanguageSelection(languages).toSorted();
407
+ return normalized.length === 0 ? "*" : normalized.join(",");
408
+ };
409
+ //#endregion
410
+ //#region src/pipeline-cache-key.ts
411
+ const DEFAULT_CUSTOM_REGEX_SCORE = .9;
412
+ const contentLanguageFingerprint = (config) => {
413
+ return languageSelectionKey(config.languages ?? (config.language === void 0 ? [] : [config.language]));
414
+ };
415
+ const pipelineConfigKey = (config, gazetteerEntries) => {
416
+ const legalFormsEnabled = isLegalFormsEnabled(config);
417
+ const customDenyFingerprint = config.enableDenyList && config.customDenyList ? config.customDenyList.map((entry) => JSON.stringify({
418
+ label: entry.label,
419
+ value: entry.value,
420
+ variants: [...entry.variants ?? []].sort()
421
+ })).sort().join("\n") : "";
422
+ const customRegexFingerprint = config.enableRegex && config.customRegexes ? config.customRegexes.map((entry) => JSON.stringify({
423
+ label: entry.label,
424
+ pattern: entry.pattern,
425
+ preparedArtifactPolicy: entry.preparedArtifactPolicy ?? null,
426
+ score: entry.score ?? DEFAULT_CUSTOM_REGEX_SCORE
427
+ })).sort().join("\n") : "";
428
+ const gazFingerprint = config.enableGazetteer && gazetteerEntries.length > 0 ? gazetteerEntries.map((entry) => `${entry.id}:${entry.canonical}:${entry.label}:${[...entry.variants].sort().join(",")}`).toSorted().join(";") : "";
429
+ return `${config.enableDenyList}:${config.enableTriggerPhrases}:${legalFormsEnabled}:${config.enableNameCorpus}:${contentLanguageFingerprint(config)}:${config.nameCorpusLanguages?.toSorted().join(",") ?? ""}:${config.enableRegex}:${config.threshold}:${config.enableConfidenceBoost}:${config.enableHotwordRules === true}:${config.enableCoreference === true}:${config.enableZoneClassification === true}:${config.labels.toSorted().join(",")}:${config.denyListCountries?.toSorted().join(",") ?? ""}:${config.denyListRegions?.toSorted().join(",") ?? ""}:${config.denyListExcludeCategories?.toSorted().join(",") ?? ""}:${customDenyFingerprint}:${customRegexFingerprint}:${config.enableGazetteer}:${gazFingerprint}:${config.enableCountries !== false}`;
430
+ };
431
+ //#endregion
432
+ //#region src/native-pipeline.ts
433
+ const sharedPackageByDictionaries = /* @__PURE__ */ new WeakMap();
434
+ const sharedPackageWithoutDictionaries = /* @__PURE__ */ new Map();
435
+ const dictionaryCacheIds = /* @__PURE__ */ new WeakMap();
436
+ let nextDictionaryCacheId = 0;
437
+ const dictionaryCacheKey = (dictionaries) => {
438
+ if (dictionaries === void 0) return "none";
439
+ const existing = dictionaryCacheIds.get(dictionaries);
440
+ if (existing !== void 0) return `dict:${existing}`;
441
+ nextDictionaryCacheId += 1;
442
+ dictionaryCacheIds.set(dictionaries, nextDictionaryCacheId);
443
+ return `dict:${nextDictionaryCacheId}`;
444
+ };
445
+ const sharedPackageCacheFor = (dictionaries) => {
446
+ if (dictionaries === void 0) return sharedPackageWithoutDictionaries;
447
+ const cached = sharedPackageByDictionaries.get(dictionaries);
448
+ if (cached !== void 0) return cached;
449
+ const created = /* @__PURE__ */ new Map();
450
+ sharedPackageByDictionaries.set(dictionaries, created);
451
+ return created;
452
+ };
453
+ const getNativePipelineCompatibility = (config) => {
454
+ const unsupportedFeatures = [];
455
+ if (config.enableNer) unsupportedFeatures.push("enableNer");
456
+ if (unsupportedFeatures.length === 0) return { status: "supported" };
457
+ return {
458
+ status: "unsupported",
459
+ unsupportedFeatures
460
+ };
461
+ };
462
+ const assertNativePipelineSupported = (config) => {
463
+ const compatibility = getNativePipelineCompatibility(config);
464
+ if (compatibility.status === "supported") return;
465
+ throw new Error(`Native pipeline does not yet support: ${compatibility.unsupportedFeatures.join(", ")}`);
466
+ };
467
+ const encoder = new TextEncoder();
468
+ /**
469
+ * Serialize the assembler inputs the Rust binding expects. Dictionaries are
470
+ * stripped from the pipeline config and passed out of band: the assembler reads
471
+ * the separate bundle preferentially, and keeping the (large) dictionaries out
472
+ * of the config JSON avoids serializing them twice.
473
+ */
474
+ const toAssembleInputs = ({ dictionaries, ...config }, gazetteerEntries) => ({
475
+ pipelineConfigJson: encoder.encode(JSON.stringify(config)),
476
+ dictionariesJson: dictionaries === void 0 ? void 0 : encoder.encode(JSON.stringify(dictionaries)),
477
+ gazetteerJson: gazetteerEntries.length === 0 ? void 0 : encoder.encode(JSON.stringify(gazetteerEntries))
478
+ });
479
+ const assemblePackageBytes = (binding, { pipelineConfigJson, dictionariesJson, gazetteerJson }, compressed) => {
480
+ const assemble = compressed ? binding.assembleStaticSearchCompressedPackageBytes : binding.assembleStaticSearchPackageBytes;
481
+ if (assemble === void 0) throw new Error("Native anonymize binding does not support static-search config assembly");
482
+ return assemble(pipelineConfigJson, dictionariesJson, gazetteerJson);
483
+ };
484
+ const prepareNativePipelineConfig = async ({ binding, config, gazetteerEntries = [] }) => {
485
+ const scopedConfig = applyPipelineLanguageScope(config);
486
+ assertNativePipelineSupported(scopedConfig);
487
+ const assemble = binding.assembleStaticSearchConfigJson;
488
+ if (assemble === void 0) throw new Error("Native anonymize binding does not support static-search config assembly");
489
+ const { pipelineConfigJson, dictionariesJson, gazetteerJson } = toAssembleInputs(scopedConfig, gazetteerEntries);
490
+ const configJson = assemble(pipelineConfigJson, dictionariesJson, gazetteerJson);
491
+ return JSON.parse(new TextDecoder().decode(configJson));
492
+ };
493
+ const prepareNativePipelinePackage = async ({ binding, config, gazetteerEntries = [], context, compressed = false }) => {
494
+ const packageBytes = await getCachedNativePipelinePackage({
495
+ config,
496
+ binding,
497
+ gazetteerEntries,
498
+ ...context ? { context } : {},
499
+ compressed
500
+ });
501
+ return new Uint8Array(packageBytes);
502
+ };
503
+ const createNativePipelineFromConfig = async ({ binding, config, gazetteerEntries = [], context }) => {
504
+ return createNativePipelineFromPackage({
505
+ binding,
506
+ packageBytes: await getCachedNativePipelinePackage({
507
+ binding,
508
+ config,
509
+ gazetteerEntries,
510
+ ...context ? { context } : {}
511
+ })
512
+ });
513
+ };
514
+ const getCachedNativePipelinePackage = async ({ binding, config, gazetteerEntries = [], context, compressed = false }) => {
515
+ const scopedConfig = applyPipelineLanguageScope(config);
516
+ assertNativePipelineSupported(scopedConfig);
517
+ const ctx = context ?? defaultContext;
518
+ const key = nativePackageCacheKey({
519
+ binding,
520
+ config: scopedConfig,
521
+ gazetteerEntries,
522
+ compressed
523
+ });
524
+ if (ctx.nativePipelinePackage && ctx.nativePipelinePackageKey === key) return ctx.nativePipelinePackage;
525
+ if (ctx.nativePipelinePackagePromise && ctx.nativePipelinePackageKey === key) return ctx.nativePipelinePackagePromise;
526
+ const sharedCache = sharedPackageCacheFor(scopedConfig.dictionaries);
527
+ const shared = sharedCache.get(key);
528
+ if (shared !== void 0) {
529
+ const packageBytes = await shared;
530
+ ctx.nativePipelinePackage = packageBytes;
531
+ ctx.nativePipelinePackageKey = key;
532
+ ctx.nativePipelinePackagePromise = null;
533
+ return packageBytes;
534
+ }
535
+ ctx.nativePipelinePackage = null;
536
+ ctx.nativePipelinePackageKey = key;
537
+ const promise = buildNativePipelinePackage({
538
+ binding,
539
+ config: scopedConfig,
540
+ gazetteerEntries,
541
+ compressed
542
+ });
543
+ ctx.nativePipelinePackagePromise = promise;
544
+ sharedCache.set(key, promise);
545
+ let packageBytes;
546
+ try {
547
+ packageBytes = await promise;
548
+ } catch (error) {
549
+ if (sharedCache.get(key) === promise) sharedCache.delete(key);
550
+ if (ctx.nativePipelinePackageKey === key && ctx.nativePipelinePackagePromise === promise) {
551
+ ctx.nativePipelinePackage = null;
552
+ ctx.nativePipelinePackagePromise = null;
553
+ }
554
+ throw error;
555
+ }
556
+ if (sharedCache.get(key) === promise) sharedCache.set(key, packageBytes);
557
+ if (ctx.nativePipelinePackageKey === key) {
558
+ ctx.nativePipelinePackage = packageBytes;
559
+ ctx.nativePipelinePackagePromise = null;
560
+ }
561
+ return packageBytes;
562
+ };
563
+ const buildNativePipelinePackage = async ({ binding, config, gazetteerEntries, compressed }) => assemblePackageBytes(binding, toAssembleInputs(config, gazetteerEntries), compressed);
564
+ const nativePackageCacheKey = ({ binding, config, gazetteerEntries, compressed }) => [
565
+ binding.nativePackageVersion(),
566
+ compressed ? "compressed" : "raw",
567
+ dictionaryCacheKey(config.dictionaries),
568
+ pipelineConfigKey(config, gazetteerEntries)
569
+ ].join(":");
570
+ //#endregion
249
571
  //#region src/wasm.ts
250
572
  const NODE_GLUE_MODULE = "index.wasi.cjs";
251
573
  const BROWSER_GLUE_MODULE = "index.wasi-browser.js";
@@ -425,6 +747,6 @@ const normalizeLanguage = (language) => {
425
747
  return normalized;
426
748
  };
427
749
  //#endregion
428
- export { DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, OPERATOR_TYPES, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedSearch, assertNativeBindingVersion, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromPackage, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
750
+ export { DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, OPERATOR_TYPES, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedSearch, assertNativeBindingVersion, assertNativePipelineSupported, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipelineContext, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
429
751
 
430
752
  //# sourceMappingURL=wasm.mjs.map
package/dist/wasm.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"wasm.mjs","names":["#prepared","#anonymizer","native_package_version","normalize_for_search","prepare_search_package","redact_text_json","redact_text","redact_text_stream_json","diagnostics_json","diagnostics_stream_json","summary_diagnostics_json","nativePackageVersionWithBinding","normalizeForSearchWithBinding","prepareSearchPackageWithBinding","redactTextWithBinding","redactTextJsonWithBinding","redactTextStreamJsonWithBinding","diagnosticsJsonWithBinding","diagnosticsStreamJsonWithBinding","summaryDiagnosticsJsonWithBinding"],"sources":["../../src/native.ts","../../src/context.ts","../../src/redact.ts","../../src/wasm.ts"],"sourcesContent":["import type { NativePreparedSearchConfig } from \"./native-search-config\";\nimport type { OperatorType } from \"./types\";\n\nexport type { NativePreparedSearchConfig } from \"./native-search-config\";\n\ntype NativeBindingOperatorConfig = {\n operators?: Record<string, OperatorType>;\n redactString?: string;\n};\n\nexport type NativeDiagnosticsBatchCallback = (diagnosticsJson: string) => void;\nexport type NativeResultEventCallback = (eventJson: string) => void;\n\ntype NativeBindingRedactionEntry = {\n placeholder: string;\n original: string;\n};\n\ntype NativeBindingOperatorEntry = {\n placeholder: string;\n operator: OperatorType;\n};\n\ntype NativeBindingPipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n sourceDetail?: string | null;\n};\n\ntype NativeBindingRedactionResult = {\n redactedText: string;\n redactionMap: NativeBindingRedactionEntry[];\n operatorMap: NativeBindingOperatorEntry[];\n entityCount: number;\n};\n\ntype NativeBindingStaticRedactionResult = {\n resolvedEntities: NativeBindingPipelineEntity[];\n redaction: NativeBindingRedactionResult;\n};\n\ntype CanonicalPipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n source_detail?: string | null;\n};\n\ntype CanonicalStaticRedactionResult = {\n resolved_entities: CanonicalPipelineEntity[];\n redaction: {\n redacted_text: string;\n redaction_map: NativeBindingRedactionEntry[];\n operator_map: NativeBindingOperatorEntry[];\n entity_count: number;\n };\n};\n\nexport type NativePreparedSearchBinding = {\n prepareDiagnosticsJson?: () => string;\n warmLazyRegex?: () => void;\n warm_lazy_regex?: () => void;\n warmLazyRegexDiagnosticsJson?: () => string;\n warm_lazy_regex_diagnostics_json?: () => string;\n redactStaticEntities: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => NativeBindingStaticRedactionResult;\n redactStaticEntitiesJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n redactStaticEntitiesResultStreamJson?: (\n fullText: string,\n operators: NativeBindingOperatorConfig | undefined,\n onEvent: NativeResultEventCallback,\n ) => string;\n redactStaticEntitiesDiagnosticsJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n redactStaticEntitiesDiagnosticsStreamJson?: (\n fullText: string,\n operators: NativeBindingOperatorConfig | undefined,\n onBatch: NativeDiagnosticsBatchCallback,\n ) => string;\n redactStaticEntitiesSummaryDiagnosticsJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n};\n\nexport type NativeAnonymizeBinding = {\n normalizeForSearch: (text: string) => string;\n nativePackageVersion: () => string;\n NativePreparedSearch: {\n fromConfigJsonBytes: (\n configJson: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromPreparedPackageBytes: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromPreparedPackageBytesWithoutCache?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromTrustedPreparedPackageBytes?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromTrustedPreparedPackageBytesWithoutCache?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n };\n prepareStaticSearchPackageBytes: (configJson: Uint8Array) => Uint8Array;\n prepareStaticSearchCompressedPackageBytes: (\n configJson: Uint8Array,\n ) => Uint8Array;\n // Rust config assembler (replaces the retired TypeScript config-assembly\n // layer). Takes the pipeline config plus out-of-band dictionaries and\n // gazetteer JSON and returns either the assembled config JSON or ready\n // package bytes. Optional so older bindings without the assembler still\n // satisfy the type; native-node loads them from the same `.node`.\n assembleStaticSearchConfigJson?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n assembleStaticSearchPackageBytes?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n assembleStaticSearchCompressedPackageBytes?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n};\n\nexport type NativeOperatorConfig = {\n operators?: Record<string, OperatorType>;\n redactString?: string;\n};\n\nexport type NativePipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n sourceDetail?: string;\n};\n\nexport type NativeRedactionResult = {\n redactedText: string;\n redactionMap: Map<string, string>;\n operatorMap: Map<string, OperatorType>;\n entityCount: number;\n};\n\nexport type NativeStaticRedactionResult = {\n resolvedEntities: NativePipelineEntity[];\n redaction: NativeRedactionResult;\n};\n\nexport type NativeSearchPackageOptions = {\n binding: NativeAnonymizeBinding;\n config: NativePreparedSearchConfig;\n compressed?: boolean;\n};\n\nexport type NativeSearchPackageInput =\n | NativePreparedSearchConfig\n | string\n | Uint8Array;\n\nexport type SharedNativeSearchPackageOptions = {\n binding: NativeAnonymizeBinding;\n config: NativeSearchPackageInput;\n compressed?: boolean;\n};\n\nexport type SharedNativePreparedPackageOptions = {\n binding: NativeAnonymizeBinding;\n packageBytes: Uint8Array;\n};\n\nexport type SharedNativeRedactTextJsonOptions = {\n binding: NativeAnonymizeBinding;\n config: NativeSearchPackageInput;\n fullText: string;\n operators?: NativeOperatorConfig;\n};\n\nexport type SharedNativeRedactTextOptions = SharedNativeRedactTextJsonOptions;\n\nexport type SharedNativeDiagnosticsJsonOptions =\n SharedNativeRedactTextJsonOptions;\n\nexport type SharedNativeDiagnosticsStreamJsonOptions =\n SharedNativeRedactTextJsonOptions & {\n onBatch: NativeDiagnosticsBatchCallback;\n };\n\nexport type SharedNativeRedactTextStreamJsonOptions =\n SharedNativeRedactTextJsonOptions & {\n onEvent: NativeResultEventCallback;\n };\n\nexport type NativeNormalizeOptions = {\n binding: NativeAnonymizeBinding;\n text: string;\n};\n\nexport type NativeAnonymizerFromConfigOptions = {\n binding: NativeAnonymizeBinding;\n config: NativePreparedSearchConfig;\n};\n\nexport type NativeAnonymizerFromPackageOptions = {\n binding: NativeAnonymizeBinding;\n packageBytes: Uint8Array;\n};\n\nexport type NativePipelineFromPackageOptions =\n NativeAnonymizerFromPackageOptions;\n\nexport type NativeBindingVersionOptions = {\n binding: NativeAnonymizeBinding;\n expectedVersion: string;\n};\n\nexport class PreparedNativeAnonymizer {\n readonly #prepared: NativePreparedSearchBinding;\n\n constructor(prepared: NativePreparedSearchBinding) {\n this.#prepared = prepared;\n }\n\n prepareDiagnosticsJson(): string | null {\n return this.#prepared.prepareDiagnosticsJson?.() ?? null;\n }\n\n prepare_diagnostics_json(): string | null {\n return this.prepareDiagnosticsJson();\n }\n\n warmLazyRegex(): void {\n if (this.#prepared.warmLazyRegex) {\n this.#prepared.warmLazyRegex();\n return;\n }\n this.#prepared.warm_lazy_regex?.();\n }\n\n warm_lazy_regex(): void {\n this.warmLazyRegex();\n }\n\n warmLazyRegexDiagnosticsJson(): string | null {\n if (this.#prepared.warmLazyRegexDiagnosticsJson) {\n return this.#prepared.warmLazyRegexDiagnosticsJson();\n }\n return this.#prepared.warm_lazy_regex_diagnostics_json?.() ?? null;\n }\n\n warm_lazy_regex_diagnostics_json(): string | null {\n return this.warmLazyRegexDiagnosticsJson();\n }\n\n redactStaticEntities(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return toNativeStaticRedactionResult(\n this.#prepared.redactStaticEntities(\n fullText,\n toBindingOperatorConfig(operators),\n ),\n );\n }\n\n redact_text(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.redactStaticEntities(fullText, operators);\n }\n\n redact_text_json(fullText: string, operators?: NativeOperatorConfig): string {\n const bindingOperators = toBindingOperatorConfig(operators);\n if (this.#prepared.redactStaticEntitiesJson) {\n return this.#prepared.redactStaticEntitiesJson(\n fullText,\n bindingOperators,\n );\n }\n return JSON.stringify(\n toBindingStaticRedactionResult(\n toNativeStaticRedactionResult(\n this.#prepared.redactStaticEntities(fullText, bindingOperators),\n ),\n ),\n );\n }\n\n redactTextJson(fullText: string, operators?: NativeOperatorConfig): string {\n return this.redact_text_json(fullText, operators);\n }\n\n redactTextStreamJson(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesResultStreamJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesResultStreamJson(\n fullText,\n toBindingOperatorConfig(operators),\n onEvent,\n );\n }\n\n redact_text_stream_json(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redactStaticEntitiesDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesDiagnosticsJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesDiagnosticsJson(\n fullText,\n toBindingOperatorConfig(operators),\n );\n }\n\n diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactStaticEntitiesDiagnosticsJson(fullText, operators);\n }\n\n diagnosticsStreamJson(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesDiagnosticsStreamJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesDiagnosticsStreamJson(\n fullText,\n toBindingOperatorConfig(operators),\n onBatch,\n );\n }\n\n diagnostics_stream_json(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n redactStaticEntitiesSummaryDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesSummaryDiagnosticsJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesSummaryDiagnosticsJson(\n fullText,\n toBindingOperatorConfig(operators),\n );\n }\n\n summary_diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactStaticEntitiesSummaryDiagnosticsJson(fullText, operators);\n }\n}\n\nexport class PreparedNativePipeline {\n readonly #anonymizer: PreparedNativeAnonymizer;\n\n constructor(anonymizer: PreparedNativeAnonymizer) {\n this.#anonymizer = anonymizer;\n }\n\n prepareDiagnosticsJson(): string | null {\n return this.#anonymizer.prepareDiagnosticsJson();\n }\n\n prepare_diagnostics_json(): string | null {\n return this.prepareDiagnosticsJson();\n }\n\n warmLazyRegex(): void {\n this.#anonymizer.warmLazyRegex();\n }\n\n warm_lazy_regex(): void {\n this.warmLazyRegex();\n }\n\n warmLazyRegexDiagnosticsJson(): string | null {\n return this.#anonymizer.warmLazyRegexDiagnosticsJson();\n }\n\n warm_lazy_regex_diagnostics_json(): string | null {\n return this.warmLazyRegexDiagnosticsJson();\n }\n\n redactText(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.#anonymizer.redactStaticEntities(fullText, operators);\n }\n\n redact_text(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.redactText(fullText, operators);\n }\n\n redact_text_json(fullText: string, operators?: NativeOperatorConfig): string {\n return this.#anonymizer.redact_text_json(fullText, operators);\n }\n\n redactTextJson(fullText: string, operators?: NativeOperatorConfig): string {\n return this.redact_text_json(fullText, operators);\n }\n\n redactTextStreamJson(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redact_text_stream_json(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redactTextDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactStaticEntitiesDiagnosticsJson(\n fullText,\n operators,\n );\n }\n\n diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextDiagnosticsJson(fullText, operators);\n }\n\n diagnosticsStreamJson(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n diagnostics_stream_json(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n redactTextSummaryDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactStaticEntitiesSummaryDiagnosticsJson(\n fullText,\n operators,\n );\n }\n\n summary_diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextSummaryDiagnosticsJson(fullText, operators);\n }\n}\n\nexport const encodeNativeSearchConfig = (\n config: NativePreparedSearchConfig,\n): Uint8Array => new TextEncoder().encode(JSON.stringify(config));\n\nexport const encodeNativeSearchConfigInput = (\n config: NativeSearchPackageInput,\n): Uint8Array => {\n if (typeof config === \"string\") {\n return new TextEncoder().encode(config);\n }\n if (config instanceof Uint8Array) {\n return config;\n }\n return encodeNativeSearchConfig(config);\n};\n\nexport const getNativeBindingVersion = (\n binding: NativeAnonymizeBinding,\n): string => binding.nativePackageVersion();\n\nexport const native_package_version = getNativeBindingVersion;\n\nexport const normalize_for_search = ({\n binding,\n text,\n}: NativeNormalizeOptions): string => binding.normalizeForSearch(text);\n\nexport const assertNativeBindingVersion = ({\n binding,\n expectedVersion,\n}: NativeBindingVersionOptions): void => {\n const actualVersion = getNativeBindingVersion(binding);\n if (actualVersion !== expectedVersion) {\n throw new Error(\n `Native anonymize binding version ${actualVersion} does not match ${expectedVersion}`,\n );\n }\n};\n\nexport const prepareNativeSearchPackage = ({\n binding,\n config,\n compressed = false,\n}: NativeSearchPackageOptions): Uint8Array => {\n const configBytes = encodeNativeSearchConfig(config);\n return compressed\n ? binding.prepareStaticSearchCompressedPackageBytes(configBytes)\n : binding.prepareStaticSearchPackageBytes(configBytes);\n};\n\nexport const prepare_search_package = ({\n binding,\n config,\n compressed = false,\n}: SharedNativeSearchPackageOptions): Uint8Array => {\n const configBytes = encodeNativeSearchConfigInput(config);\n return compressed\n ? binding.prepareStaticSearchCompressedPackageBytes(configBytes)\n : binding.prepareStaticSearchPackageBytes(configBytes);\n};\n\nexport const createNativeAnonymizerFromConfig = ({\n binding,\n config,\n}: NativeAnonymizerFromConfigOptions): PreparedNativeAnonymizer =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfig(config),\n ),\n );\n\nexport const createNativeAnonymizerFromPackage = ({\n binding,\n packageBytes,\n}: NativeAnonymizerFromPackageOptions): PreparedNativeAnonymizer =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromPreparedPackageBytes(packageBytes),\n );\n\nexport const load_prepared_package = ({\n binding,\n packageBytes,\n}: SharedNativePreparedPackageOptions): PreparedNativeAnonymizer =>\n createNativeAnonymizerFromPackage({ binding, packageBytes });\n\nexport const redact_text_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeRedactTextJsonOptions): string =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text_json(fullText, operators);\n\nexport const redact_text = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeRedactTextOptions): NativeStaticRedactionResult =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text(fullText, operators);\n\nexport const redact_text_stream_json = ({\n binding,\n config,\n fullText,\n operators,\n onEvent,\n}: SharedNativeRedactTextStreamJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text_stream_json(fullText, onEvent, operators);\n\nexport const diagnostics_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeDiagnosticsJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).diagnostics_json(fullText, operators);\n\nexport const diagnostics_stream_json = ({\n binding,\n config,\n fullText,\n operators,\n onBatch,\n}: SharedNativeDiagnosticsStreamJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).diagnostics_stream_json(fullText, onBatch, operators);\n\nexport const summary_diagnostics_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeDiagnosticsJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).summary_diagnostics_json(fullText, operators);\n\nexport const createNativePipelineFromPackage = ({\n binding,\n packageBytes,\n}: NativePipelineFromPackageOptions): PreparedNativePipeline =>\n new PreparedNativePipeline(\n createNativeAnonymizerFromPackage({ binding, packageBytes }),\n );\n\nexport const PreparedSearch = PreparedNativeAnonymizer;\nexport type PreparedSearch = PreparedNativeAnonymizer;\nexport const PreparedAnonymizer = PreparedNativeAnonymizer;\nexport type PreparedAnonymizer = PreparedNativeAnonymizer;\n\nconst toBindingOperatorConfig = (\n config: NativeOperatorConfig | undefined,\n): NativeBindingOperatorConfig | undefined => {\n if (!config) {\n return undefined;\n }\n const bindingConfig: NativeBindingOperatorConfig = {};\n if (config.operators !== undefined) {\n bindingConfig.operators = config.operators;\n }\n if (config.redactString !== undefined) {\n bindingConfig.redactString = config.redactString;\n }\n return bindingConfig;\n};\n\nconst toNativeStaticRedactionResult = (\n result: NativeBindingStaticRedactionResult,\n): NativeStaticRedactionResult => ({\n resolvedEntities: result.resolvedEntities.map(toNativePipelineEntity),\n redaction: toNativeRedactionResult(result.redaction),\n});\n\nconst toBindingStaticRedactionResult = (\n result: NativeStaticRedactionResult,\n): CanonicalStaticRedactionResult => ({\n resolved_entities: result.resolvedEntities.map(toBindingPipelineEntity),\n redaction: {\n redacted_text: result.redaction.redactedText,\n redaction_map: [...result.redaction.redactionMap.entries()].map(\n ([placeholder, original]) => ({ placeholder, original }),\n ),\n operator_map: [...result.redaction.operatorMap.entries()].map(\n ([placeholder, operator]) => ({ placeholder, operator }),\n ),\n entity_count: result.redaction.entityCount,\n },\n});\n\nconst toNativePipelineEntity = (\n entity: NativeBindingPipelineEntity,\n): NativePipelineEntity => ({\n start: entity.start,\n end: entity.end,\n label: entity.label,\n text: entity.text,\n score: entity.score,\n source: entity.source,\n ...(entity.sourceDetail ? { sourceDetail: entity.sourceDetail } : {}),\n});\n\nconst toBindingPipelineEntity = ({\n sourceDetail,\n ...entity\n}: NativePipelineEntity): CanonicalPipelineEntity => ({\n ...entity,\n source_detail: sourceDetail ?? null,\n});\n\nconst toNativeRedactionResult = (\n result: NativeBindingRedactionResult,\n): NativeRedactionResult => ({\n redactedText: result.redactedText,\n redactionMap: toRedactionMap(result.redactionMap),\n operatorMap: toOperatorMap(result.operatorMap),\n entityCount: result.entityCount,\n});\n\nconst toRedactionMap = (\n entries: readonly NativeBindingRedactionEntry[],\n): Map<string, string> => {\n const map = new Map<string, string>();\n for (const entry of entries) {\n map.set(entry.placeholder, entry.original);\n }\n return map;\n};\n\nconst toOperatorMap = (\n entries: readonly NativeBindingOperatorEntry[],\n): Map<string, OperatorType> => {\n const map = new Map<string, OperatorType>();\n for (const entry of entries) {\n map.set(entry.placeholder, entry.operator);\n }\n return map;\n};\n","/**\n * Cached state for a single pipeline run (or a sequence of runs sharing the\n * same config). The native pipeline builds its prepared package once and reuses\n * it across calls with the same config; the package bytes and the key/promise\n * that guard concurrent builds live here so callers can share one warmed\n * context.\n */\nexport type PipelineContext = {\n // ── Native prepared-package cache ─────────────\n nativePipelinePackage: Uint8Array | null;\n nativePipelinePackageKey: string;\n nativePipelinePackagePromise: Promise<Uint8Array> | null;\n};\n\n/** Create a fresh, empty pipeline context. */\nexport const createPipelineContext = (): PipelineContext => ({\n nativePipelinePackage: null,\n nativePipelinePackageKey: \"\",\n nativePipelinePackagePromise: null,\n});\n\n/**\n * Module-level default context. Used when callers\n * don't provide an explicit context, preserving full\n * backward compatibility with the existing API.\n */\nexport const defaultContext: PipelineContext = createPipelineContext();\n","import {\n DEFAULT_OPERATOR_CONFIG,\n OPERATOR_REGISTRY,\n resolveOperator,\n} from \"./operators\";\nimport type {\n Entity,\n OperatorConfig,\n OperatorType,\n RedactionResult,\n} from \"./types\";\nimport type { PipelineContext } from \"./context\";\nimport { defaultContext } from \"./context\";\n\nconst WHITESPACE_RE = /\\s+/g;\nconst PHONE_NOISE_RE = /[()\\s-]/g;\nconst ETHEREUM_ADDRESS_RE = /0x[0-9A-Fa-f]{40}/;\nconst BECH32_ADDRESS_RE = /\\bbc1[ac-hj-np-z02-9]{11,71}\\b/i;\nconst BASE58_ADDRESS_RE = /\\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\\b/;\nconst NHS_NUMBER_CUE_RE = /\\b(?:NHS|National\\s+Health\\s+Service)\\b/i;\nconst PLACEHOLDER_TOKEN_RE = /\\[[^\\s[\\]]+_[1-9]\\d*\\]/g;\nconst PASSPORT_IDENTIFIER_RE =\n /\\b(?:[A-Za-z]{1,2}\\d{6,8}|\\d{2}[A-Za-z]{2}\\d{5}|\\d{7,9})\\b/;\n// Strip all separators the ID detectors accept so the\n// same real-world value canonicalises to one placeholder:\n// - whitespace and `-` for IBAN, NIP, REGON, etc.\n// - `/` for birth numbers (\"900101/1234\") and Czech\n// bank accounts (\"123-4567/0100\").\n// - `.` for credit cards (\"4111.1111.1111.1111\") and\n// other dotted IDs.\nconst ID_SEPARATOR_RE = /[\\s\\-/.]/g;\n\nconst nextPlaceholder = (\n labelKey: string,\n counters: Map<string, number>,\n reservedPlaceholders: ReadonlySet<string>,\n): string => {\n let count = counters.get(labelKey) ?? 0;\n\n while (true) {\n count += 1;\n const placeholder = `[${labelKey}_${count}]`;\n if (reservedPlaceholders.has(placeholder)) continue;\n\n counters.set(labelKey, count);\n return placeholder;\n }\n};\n\nconst collectReservedPlaceholders = (\n reservedText: string,\n): ReadonlySet<string> => new Set(reservedText.match(PLACEHOLDER_TOKEN_RE));\n\nconst normalizeCryptoText = (text: string): string => {\n const trimmed = text.trim();\n\n const ethereumAddress = ETHEREUM_ADDRESS_RE.exec(trimmed)?.[0];\n if (ethereumAddress) {\n return ethereumAddress.toLowerCase();\n }\n\n const bech32Address = BECH32_ADDRESS_RE.exec(trimmed)?.[0];\n if (bech32Address) {\n return bech32Address.toLowerCase();\n }\n\n const base58Address = BASE58_ADDRESS_RE.exec(trimmed)?.[0];\n return base58Address ?? trimmed;\n};\n\nconst normalizePassportText = (text: string): string => {\n const passportIdentifier = PASSPORT_IDENTIFIER_RE.exec(text)?.[0] ?? text;\n return passportIdentifier.replace(ID_SEPARATOR_RE, \"\").toUpperCase();\n};\n\n/**\n * Normalize entity text so that surface-form variations\n * of the same real-world value map to a single canonical\n * key. Lowercased emails, stripped phone formatting, etc.\n */\nconst normalizeEntityText = (label: string, text: string): string => {\n const upper = label.toUpperCase().replace(WHITESPACE_RE, \"_\");\n\n if (upper === \"EMAIL_ADDRESS\" || upper === \"EMAIL\") {\n return text.toLowerCase().trim();\n }\n if (upper === \"PHONE_NUMBER\" || upper === \"PHONE\") {\n return text.replace(PHONE_NOISE_RE, \"\");\n }\n if (upper === \"CRYPTO\") {\n return normalizeCryptoText(text);\n }\n if (\n upper === \"NATIONAL_IDENTIFICATION_NUMBER\" &&\n NHS_NUMBER_CUE_RE.test(text)\n ) {\n return text.replace(/\\D/g, \"\");\n }\n if (\n upper === \"IBAN\" ||\n upper === \"BANK_ACCOUNT_NUMBER\" ||\n upper === \"TAX_IDENTIFICATION_NUMBER\" ||\n upper === \"REGISTRATION_NUMBER\" ||\n upper === \"NATIONAL_IDENTIFICATION_NUMBER\" ||\n upper === \"SOCIAL_SECURITY_NUMBER\" ||\n upper === \"BIRTH_NUMBER\" ||\n upper === \"IDENTITY_CARD_NUMBER\" ||\n upper === \"CREDIT_CARD_NUMBER\"\n ) {\n return text.replace(ID_SEPARATOR_RE, \"\").toUpperCase();\n }\n if (upper === \"PASSPORT_NUMBER\") {\n return normalizePassportText(text);\n }\n if (\n upper === \"PERSON\" ||\n upper === \"ORGANIZATION\" ||\n upper === \"ADDRESS\" ||\n upper === \"LAND_PARCEL\" ||\n upper === \"MISC\"\n ) {\n return text.replace(WHITESPACE_RE, \" \").toLowerCase().trim();\n }\n return text.trim();\n};\n\n/**\n * Build a stable mapping from entity text to numbered\n * placeholders. Same real-world value always maps to the\n * same placeholder (e.g., \"Dr. Muller\" and \"Dr. Muller\"\n * share one person placeholder).\n *\n * Placeholder format: [LABEL_N] where LABEL is uppercase.\n * N is allocated per label and skips tokens already present\n * in reserved text.\n *\n * @param _ctx Unused. Kept for signature compatibility;\n * coref alias links now travel on the entities\n * themselves (`corefSourceText`).\n */\ntype PlaceholderMapOptions = {\n reservedText?: string;\n};\n\nexport const buildPlaceholderMap = (\n entities: Entity[],\n _ctx: PipelineContext = defaultContext,\n { reservedText = \"\" }: PlaceholderMapOptions = {},\n): Map<string, string> => {\n const counters = new Map<string, number>();\n const textLabelToPlaceholder = new Map<string, string>();\n const normalizedToPlaceholder = new Map<string, string>();\n const reservedPlaceholders = collectReservedPlaceholders(reservedText);\n\n const sorted = entities.toSorted((a, b) => a.start - b.start);\n\n for (const entity of sorted) {\n const compositeKey = `${entity.label}\\0${entity.text}`;\n if (textLabelToPlaceholder.has(compositeKey)) {\n continue;\n }\n\n const labelKey = entity.label.toUpperCase().replace(WHITESPACE_RE, \"_\");\n\n // If this entity is a coref alias, unify its key\n // with the source entity's key so both get the same\n // number — in either direction: a backward alias\n // joins the source's existing placeholder, and a\n // forward alias (bare mention before the full form)\n // reserves its placeholder under the source key so\n // the source joins it when numbered later. The link\n // is carried on the entity itself, so it cannot be\n // lost between detection and redaction.\n const sourceText =\n entity.source === \"coreference\" ? entity.corefSourceText : undefined;\n const sourceNormalizedKey =\n sourceText === undefined\n ? undefined\n : `${labelKey}\\0${normalizeEntityText(entity.label, sourceText)}`;\n if (sourceNormalizedKey !== undefined) {\n const sourceExisting = normalizedToPlaceholder.get(sourceNormalizedKey);\n if (sourceExisting) {\n textLabelToPlaceholder.set(compositeKey, sourceExisting);\n continue;\n }\n }\n\n const normalized = normalizeEntityText(entity.label, entity.text);\n const normalizedKey = `${labelKey}\\0${normalized}`;\n const existing = normalizedToPlaceholder.get(normalizedKey);\n if (existing) {\n textLabelToPlaceholder.set(compositeKey, existing);\n if (sourceNormalizedKey !== undefined) {\n normalizedToPlaceholder.set(sourceNormalizedKey, existing);\n }\n continue;\n }\n\n const placeholder = nextPlaceholder(\n labelKey,\n counters,\n reservedPlaceholders,\n );\n textLabelToPlaceholder.set(compositeKey, placeholder);\n normalizedToPlaceholder.set(normalizedKey, placeholder);\n if (sourceNormalizedKey !== undefined) {\n normalizedToPlaceholder.set(sourceNormalizedKey, placeholder);\n }\n }\n\n return textLabelToPlaceholder;\n};\n\n/**\n * Apply redactions to the source text, replacing each\n * confirmed entity span using the configured operator.\n *\n * Co-references are consistent: if the same text appears\n * multiple times, all occurrences get the same placeholder.\n *\n * @param ctx Pipeline context. Must be the same instance\n * passed to `runPipeline` (or `findCoreferenceSpans`)\n * so coreference placeholder links are preserved.\n * Defaults to `defaultContext` for single-tenant usage.\n */\nexport const redactText = (\n fullText: string,\n entities: Entity[],\n config: OperatorConfig = DEFAULT_OPERATOR_CONFIG,\n ctx: PipelineContext = defaultContext,\n): RedactionResult => {\n if (entities.length === 0) {\n return {\n redactedText: fullText,\n redactionMap: new Map(),\n operatorMap: new Map(),\n entityCount: 0,\n };\n }\n\n const placeholderMap = buildPlaceholderMap(entities, ctx, {\n reservedText: fullText,\n });\n\n const sorted = entities.toSorted((a, b) => a.start - b.start);\n\n // Remove overlapping spans (keep first occurrence)\n const nonOverlapping: Entity[] = [];\n let lastEnd = 0;\n for (const entity of sorted) {\n if (entity.start >= lastEnd) {\n nonOverlapping.push(entity);\n lastEnd = entity.end;\n }\n }\n\n const parts: string[] = [];\n const redactionMap = new Map<string, string>();\n const operatorMap = new Map<string, OperatorType>();\n let cursor = 0;\n\n for (const entity of nonOverlapping) {\n if (entity.start > cursor) {\n parts.push(fullText.slice(cursor, entity.start));\n }\n\n const placeholder =\n placeholderMap.get(`${entity.label}\\0${entity.text}`) ??\n `[${entity.label.toUpperCase().replace(/\\s+/g, \"_\")}]`;\n\n const opType = resolveOperator(config, entity.label);\n const operator = OPERATOR_REGISTRY[opType];\n\n const replacement = operator.apply(\n entity.text,\n entity.label,\n placeholder,\n config.redactString,\n );\n\n parts.push(replacement);\n // operatorMap is keyed by the conceptual placeholder\n // ([LABEL_N]), not by the replacement text. For \"redact\"\n // operators the placeholder never appears in the output;\n // the map is only consulted via exportRedactionKey which\n // iterates redactionMap (replace entries only).\n operatorMap.set(placeholder, opType);\n\n // Only populate redactionMap for reversible operators.\n // A coref alias contributes its source's full text, so\n // a forward alias (\"Acme\" before \"Acme Corporation\")\n // cannot pin the shortened surface form as the key's\n // canonical value for the shared placeholder.\n if (\n operator.reversibility === \"reversible\" &&\n !redactionMap.has(placeholder)\n ) {\n redactionMap.set(\n placeholder,\n entity.source === \"coreference\" ? entity.corefSourceText : entity.text,\n );\n }\n\n cursor = entity.end;\n }\n\n if (cursor < fullText.length) {\n parts.push(fullText.slice(cursor));\n }\n\n return {\n redactedText: parts.join(\"\"),\n redactionMap,\n operatorMap,\n entityCount: nonOverlapping.length,\n };\n};\n\n/**\n * Serialize the redaction key to JSON for export.\n * Includes operator metadata so the export is self-describing.\n */\nexport const exportRedactionKey = (\n redactionMap: Map<string, string>,\n operatorMap: Map<string, OperatorType>,\n): string => {\n const entries: Record<string, { original: string; operator: OperatorType }> =\n {};\n\n for (const [placeholder, value] of redactionMap) {\n entries[placeholder] = {\n original: value,\n operator: operatorMap.get(placeholder) ?? \"replace\",\n };\n }\n\n return JSON.stringify({ entries }, null, 2);\n};\n\n/**\n * De-anonymise text using a redaction key.\n * Replaces placeholders back with original values.\n * Only works for reversible operators (replace).\n */\nexport const deanonymise = (\n redactedText: string,\n redactionMap: Map<string, string>,\n): string => {\n let result = redactedText;\n\n for (const [placeholder, original] of redactionMap) {\n result = result.replaceAll(placeholder, original);\n }\n\n return result;\n};\n","/* @stll/anonymize-wasm — browser / WebAssembly entry.\n *\n * Exposes the same native-SDK surface as `@stll/anonymize/native` (the\n * runtime-agnostic layer in `native.ts`), backed by the napi-rs\n * wasm32-wasip1-threads binding instead of the `.node` sidecars. The old\n * TS-pipeline surface (`runPipeline` and friends) is intentionally gone here:\n * this package now redacts entirely through the wasm binding and PREBUILT\n * prepared packages.\n *\n * Browsers load prepared packages only (no in-browser config building): pass\n * package bytes, an `ArrayBuffer`, or a URL to fetch, or call\n * `loadDefaultPipeline()` for the default package bundled in the tarball.\n *\n * No module-level side effects: the wasm binding is instantiated lazily on\n * first use via `getBinding()`. The napi-generated glue is loaded from the\n * package's own `native/` asset directory — `index.wasi.cjs` under Node's WASI\n * runtime, `index.wasi-browser.js` (fetch + Worker) in browsers.\n */\n\nimport {\n createNativeAnonymizerFromPackage,\n createNativePipelineFromPackage,\n diagnostics_json as diagnosticsJsonWithBinding,\n diagnostics_stream_json as diagnosticsStreamJsonWithBinding,\n type NativeAnonymizeBinding,\n type NativeDiagnosticsBatchCallback,\n type NativeOperatorConfig,\n type NativeResultEventCallback,\n type NativeSearchPackageInput,\n type NativeStaticRedactionResult,\n native_package_version as nativePackageVersionWithBinding,\n normalize_for_search as normalizeForSearchWithBinding,\n PreparedNativeAnonymizer,\n PreparedNativePipeline,\n prepare_search_package as prepareSearchPackageWithBinding,\n redact_text as redactTextWithBinding,\n redact_text_json as redactTextJsonWithBinding,\n redact_text_stream_json as redactTextStreamJsonWithBinding,\n summary_diagnostics_json as summaryDiagnosticsJsonWithBinding,\n} from \"./native\";\n\nexport * from \"./native\";\nexport { deanonymise, exportRedactionKey } from \"./redact\";\nexport {\n DEFAULT_ENTITY_LABELS,\n DETECTION_SOURCES,\n DETECTOR_PRIORITY,\n OPERATOR_TYPES,\n} from \"./types\";\nexport type {\n AnonymisationOperator,\n DetectionSource,\n Entity,\n OperatorConfig,\n OperatorType,\n RedactionResult,\n ReviewDecision,\n ReviewedEntity,\n} from \"./types\";\n\n/** A prepared package the caller supplies: raw bytes, an ArrayBuffer, or a URL\n * (string or `URL`) that resolves to the package and is fetched. */\nexport type PreparedPackageSource = Uint8Array | ArrayBuffer | URL | string;\n\n/** Escape hatch for callers that already hold a binding (e.g. a custom sidecar\n * or a test double). When omitted, the lazily-instantiated wasm binding is\n * used. */\nexport type WasmBindingOptions = {\n binding?: NativeAnonymizeBinding;\n};\n\nconst NODE_GLUE_MODULE = \"index.wasi.cjs\";\nconst BROWSER_GLUE_MODULE = \"index.wasi-browser.js\";\nconst NODE_FS_MODULE = \"node:fs/promises\";\nconst NATIVE_ASSET_DIR = \"native\";\nconst DEFAULT_PACKAGE_FILE = \"native-pipeline.stlanonpkg\";\nconst LANGUAGE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\n\nlet bindingPromise: Promise<NativeAnonymizeBinding> | undefined;\nconst defaultPipelineCache = new Map<string, Promise<PreparedNativePipeline>>();\n\n/** Instantiate (once) and return the wasm binding. Safe to call repeatedly:\n * the underlying wasm module is instantiated a single time and cached. */\nexport const getBinding = (): Promise<NativeAnonymizeBinding> => {\n bindingPromise ??= loadWasmBinding();\n return bindingPromise;\n};\n\nconst loadWasmBinding = async (): Promise<NativeAnonymizeBinding> => {\n const glueModule = isNodeRuntime() ? NODE_GLUE_MODULE : BROWSER_GLUE_MODULE;\n const glueUrl = assetUrl(glueModule);\n // The specifier is deliberately a runtime asset URL (resolved against the\n // package's own `native/` directory), not a module the bundler should follow:\n // the napi-rs glue lives outside src and is copied in at build time.\n // eslint-disable-next-line stll/no-dynamic-import-specifier\n const loaded: unknown = await import(/* @vite-ignore */ glueUrl.href);\n return toNativeAnonymizeBinding(loaded);\n};\n\ntype RuntimeGlobals = {\n process?: { versions?: { node?: string } };\n window?: unknown;\n};\n\nconst isNodeRuntime = (): boolean => {\n const globals: RuntimeGlobals = globalThis;\n return (\n globals.window === undefined &&\n typeof globals.process?.versions?.node === \"string\"\n );\n};\n\nconst assetUrl = (fileName: string): URL =>\n new URL(`./${NATIVE_ASSET_DIR}/${fileName}`, import.meta.url);\n\nconst resolveBinding = (\n options?: WasmBindingOptions,\n): Promise<NativeAnonymizeBinding> =>\n options?.binding ? Promise.resolve(options.binding) : getBinding();\n\nconst toPackageBytes = async (\n source: PreparedPackageSource,\n): Promise<Uint8Array> => {\n if (source instanceof Uint8Array) {\n return source;\n }\n if (source instanceof ArrayBuffer) {\n return new Uint8Array(source);\n }\n const href = source instanceof URL ? source.href : source;\n // Node's global fetch (undici) rejects file: URLs, so package URLs resolved\n // from import.meta.url (loadDefaultPipeline, `new URL(..., import.meta.url)`)\n // fail there. Read those through node:fs instead of fetch.\n if (href.startsWith(\"file:\")) {\n return readFileUrlBytes(href);\n }\n const response = await fetch(href);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch prepared package (${response.status} ${response.statusText})`,\n );\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\n/** Read a `file:` URL through node:fs. The import is dynamic and gated behind\n * the `file:` check (never reached in browsers); the specifier is a runtime\n * value so the bundler leaves it alone, mirroring the runtime glue import in\n * {@link loadWasmBinding}, so browser bundles never pull in node:fs. */\nconst readFileUrlBytes = async (fileUrl: string): Promise<Uint8Array> => {\n // eslint-disable-next-line stll/no-dynamic-import-specifier\n const { readFile } = await import(/* @vite-ignore */ NODE_FS_MODULE);\n return new Uint8Array(await readFile(new URL(fileUrl)));\n};\n\n// --- Prepared-package loaders (the primary browser flow) ---------------------\n\nexport type LoadPreparedPackageOptions = WasmBindingOptions;\n\n/** Load a prepared package and return a pipeline ready to redact text. */\nexport const loadPipeline = async (\n source: PreparedPackageSource,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n const [binding, packageBytes] = await Promise.all([\n resolveBinding(options),\n toPackageBytes(source),\n ]);\n return createNativePipelineFromPackage({ binding, packageBytes });\n};\n\n/** Load a prepared package and return the lower-level anonymizer. */\nexport const load_prepared_package = async (\n source: PreparedPackageSource,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativeAnonymizer> => {\n const [binding, packageBytes] = await Promise.all([\n resolveBinding(options),\n toPackageBytes(source),\n ]);\n return createNativeAnonymizerFromPackage({ binding, packageBytes });\n};\n\n// --- Default package bundled in the tarball ----------------------------------\n\n/** URL of a bundled default prepared package, resolved against this module so\n * it points at the `native/` asset directory shipped in the tarball. */\nexport const defaultPackageUrl = (language?: string): URL =>\n language === undefined\n ? assetUrl(DEFAULT_PACKAGE_FILE)\n : assetUrl(`native-pipeline.${normalizeLanguage(language)}.stlanonpkg`);\n\n/** Load a fresh pipeline from the bundled default prepared package.\n *\n * Mirrors the node loader's regional-tag fallback: when an exact package for\n * a locale tag such as `en-US` is not shipped, the base-language package\n * (`en`) is loaded instead. The browser cannot check asset existence up\n * front, so the fallback triggers on a failed load of the exact package. */\nexport const loadDefaultPipeline = async (\n language?: string,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n try {\n return await loadPipeline(defaultPackageUrl(language), options);\n } catch (error) {\n const normalized =\n language === undefined ? undefined : normalizeLanguage(language);\n const baseLanguage = normalized?.split(\"-\").at(0);\n if (baseLanguage === undefined || baseLanguage === normalized) {\n throw error;\n }\n return loadPipeline(defaultPackageUrl(baseLanguage), options);\n }\n};\n\n/** Cached variant of {@link loadDefaultPipeline}: the default pipeline for a\n * given language is fetched and prepared once, then reused.\n *\n * Only the ambient-binding case is cached. The cache key is language-only, so a\n * caller that injects its own `options.binding` bypasses the cache entirely:\n * reusing a pipeline built against a different binding would be wrong, and\n * folding the binding into the key would keep unbounded per-binding entries\n * alive. Injected-binding callers get a fresh pipeline each call. */\nexport const getDefaultPipeline = (\n language?: string,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n if (options?.binding) {\n return loadDefaultPipeline(language, options);\n }\n const key = language ?? \"<default>\";\n const cached = defaultPipelineCache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n // Evict the entry on rejection so a failed load (e.g. a transient fetch/read\n // error) is retried on the next call instead of caching the rejection.\n const pipeline = loadDefaultPipeline(language).catch((error: unknown) => {\n defaultPipelineCache.delete(key);\n throw error;\n });\n defaultPipelineCache.set(key, pipeline);\n return pipeline;\n};\n\nexport const redactDefaultText = async (\n fullText: string,\n operators?: NativeOperatorConfig,\n language?: string,\n): Promise<NativeStaticRedactionResult> =>\n (await getDefaultPipeline(language)).redactText(fullText, operators);\n\nexport const redactDefaultTextJson = async (\n fullText: string,\n operators?: NativeOperatorConfig,\n language?: string,\n): Promise<string> =>\n (await getDefaultPipeline(language)).redact_text_json(fullText, operators);\n\n// --- Binding-injected SDK surface (async parity with native-node) ------------\n\nexport const native_package_version = async (\n options?: WasmBindingOptions,\n): Promise<string> =>\n nativePackageVersionWithBinding(await resolveBinding(options));\n\nexport const normalize_for_search = async (\n text: string,\n options?: WasmBindingOptions,\n): Promise<string> =>\n normalizeForSearchWithBinding({\n binding: await resolveBinding(options),\n text,\n });\n\nexport type PrepareSearchPackageOptions = WasmBindingOptions & {\n compressed?: boolean;\n};\n\nexport const prepare_search_package = async (\n config: NativeSearchPackageInput,\n { compressed = false, ...options }: PrepareSearchPackageOptions = {},\n): Promise<Uint8Array> =>\n prepareSearchPackageWithBinding({\n binding: await resolveBinding(options),\n config,\n compressed,\n });\n\nexport const redact_text = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<NativeStaticRedactionResult> =>\n redactTextWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const redact_text_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string> =>\n redactTextJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const redact_text_stream_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n redactTextStreamJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n onEvent,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const diagnostics_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n diagnosticsJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const diagnostics_stream_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n diagnosticsStreamJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n onBatch,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const summary_diagnostics_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n summaryDiagnosticsJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\n// --- Binding extraction ------------------------------------------------------\n\nconst toNativeAnonymizeBinding = (loaded: unknown): NativeAnonymizeBinding => {\n const candidate = pickBindingCandidate(loaded);\n if (!isNativeAnonymizeBinding(candidate)) {\n throw new Error(\n \"wasm binding module does not expose the native anonymize surface\",\n );\n }\n return candidate;\n};\n\nconst pickBindingCandidate = (loaded: unknown): unknown => {\n if (isRecord(loaded) && isNativeAnonymizeBinding(loaded[\"default\"])) {\n return loaded[\"default\"];\n }\n return loaded;\n};\n\nconst isNativeAnonymizeBinding = (\n value: unknown,\n): value is NativeAnonymizeBinding => {\n if (!isRecord(value)) {\n return false;\n }\n if (typeof value[\"nativePackageVersion\"] !== \"function\") {\n return false;\n }\n if (typeof value[\"normalizeForSearch\"] !== \"function\") {\n return false;\n }\n if (typeof value[\"prepareStaticSearchPackageBytes\"] !== \"function\") {\n return false;\n }\n if (\n typeof value[\"prepareStaticSearchCompressedPackageBytes\"] !== \"function\"\n ) {\n return false;\n }\n const preparedSearch = value[\"NativePreparedSearch\"];\n if (!isRecord(preparedSearch)) {\n return false;\n }\n if (typeof preparedSearch[\"fromConfigJsonBytes\"] !== \"function\") {\n return false;\n }\n return typeof preparedSearch[\"fromPreparedPackageBytes\"] === \"function\";\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n\nconst normalizeLanguage = (language: string): string => {\n const normalized = language.trim().toLowerCase();\n if (!LANGUAGE_PATTERN.test(normalized)) {\n throw new Error(`Language must match ${LANGUAGE_PATTERN.source}`);\n }\n return normalized;\n};\n"],"mappings":";;AA+OA,IAAa,2BAAb,MAAsC;CACpC;CAEA,YAAY,UAAuC;EACjD,KAAKA,YAAY;CACnB;CAEA,yBAAwC;EACtC,OAAO,KAAKA,UAAU,yBAAyB,KAAK;CACtD;CAEA,2BAA0C;EACxC,OAAO,KAAK,uBAAuB;CACrC;CAEA,gBAAsB;EACpB,IAAI,KAAKA,UAAU,eAAe;GAChC,KAAKA,UAAU,cAAc;GAC7B;EACF;EACA,KAAKA,UAAU,kBAAkB;CACnC;CAEA,kBAAwB;EACtB,KAAK,cAAc;CACrB;CAEA,+BAA8C;EAC5C,IAAI,KAAKA,UAAU,8BACjB,OAAO,KAAKA,UAAU,6BAA6B;EAErD,OAAO,KAAKA,UAAU,mCAAmC,KAAK;CAChE;CAEA,mCAAkD;EAChD,OAAO,KAAK,6BAA6B;CAC3C;CAEA,qBACE,UACA,WAC6B;EAC7B,OAAO,8BACL,KAAKA,UAAU,qBACb,UACA,wBAAwB,SAAS,CACnC,CACF;CACF;CAEA,YACE,UACA,WAC6B;EAC7B,OAAO,KAAK,qBAAqB,UAAU,SAAS;CACtD;CAEA,iBAAiB,UAAkB,WAA0C;EAC3E,MAAM,mBAAmB,wBAAwB,SAAS;EAC1D,IAAI,KAAKA,UAAU,0BACjB,OAAO,KAAKA,UAAU,yBACpB,UACA,gBACF;EAEF,OAAO,KAAK,UACV,+BACE,8BACE,KAAKA,UAAU,qBAAqB,UAAU,gBAAgB,CAChE,CACF,CACF;CACF;CAEA,eAAe,UAAkB,WAA0C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ACrC,MAAM,IAAI,MACR,kEACF;CAEF,OAAO;AACT;AAEA,MAAM,wBAAwB,WAA6B;CACzD,IAAI,SAAS,MAAM,KAAK,yBAAyB,OAAO,UAAU,GAChE,OAAO,OAAO;CAEhB,OAAO;AACT;AAEA,MAAM,4BACJ,UACoC;CACpC,IAAI,CAAC,SAAS,KAAK,GACjB,OAAO;CAET,IAAI,OAAO,MAAM,4BAA4B,YAC3C,OAAO;CAET,IAAI,OAAO,MAAM,0BAA0B,YACzC,OAAO;CAET,IAAI,OAAO,MAAM,uCAAuC,YACtD,OAAO;CAET,IACE,OAAO,MAAM,iDAAiD,YAE9D,OAAO;CAET,MAAM,iBAAiB,MAAM;CAC7B,IAAI,CAAC,SAAS,cAAc,GAC1B,OAAO;CAET,IAAI,OAAO,eAAe,2BAA2B,YACnD,OAAO;CAET,OAAO,OAAO,eAAe,gCAAgC;AAC/D;AAEA,MAAM,YAAY,UACf,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAEpE,MAAM,qBAAqB,aAA6B;CACtD,MAAM,aAAa,SAAS,KAAK,CAAC,CAAC,YAAY;CAC/C,IAAI,CAAC,iBAAiB,KAAK,UAAU,GACnC,MAAM,IAAI,MAAM,uBAAuB,iBAAiB,QAAQ;CAElE,OAAO;AACT"}
1
+ {"version":3,"file":"wasm.mjs","names":["#prepared","#anonymizer","native_package_version","normalize_for_search","prepare_search_package","redact_text_json","redact_text","redact_text_stream_json","diagnostics_json","diagnostics_stream_json","summary_diagnostics_json","languageScopes","normalizeLanguage","nativePackageVersionWithBinding","normalizeForSearchWithBinding","prepareSearchPackageWithBinding","redactTextWithBinding","redactTextJsonWithBinding","redactTextStreamJsonWithBinding","diagnosticsJsonWithBinding","diagnosticsStreamJsonWithBinding","summaryDiagnosticsJsonWithBinding"],"sources":["../../src/native.ts","../../src/context.ts","../../src/redact.ts","../../src/types.ts","../../src/data/language-scopes.json","../../src/language-scope.ts","../../src/util/language-selection.ts","../../src/pipeline-cache-key.ts","../../src/native-pipeline.ts","../../src/wasm.ts"],"sourcesContent":["import type { NativePreparedSearchConfig } from \"./native-search-config\";\nimport type { OperatorType } from \"./types\";\n\nexport type { NativePreparedSearchConfig } from \"./native-search-config\";\n\ntype NativeBindingOperatorConfig = {\n operators?: Record<string, OperatorType>;\n redactString?: string;\n};\n\nexport type NativeDiagnosticsBatchCallback = (diagnosticsJson: string) => void;\nexport type NativeResultEventCallback = (eventJson: string) => void;\n\ntype NativeBindingRedactionEntry = {\n placeholder: string;\n original: string;\n};\n\ntype NativeBindingOperatorEntry = {\n placeholder: string;\n operator: OperatorType;\n};\n\ntype NativeBindingPipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n sourceDetail?: string | null;\n};\n\ntype NativeBindingRedactionResult = {\n redactedText: string;\n redactionMap: NativeBindingRedactionEntry[];\n operatorMap: NativeBindingOperatorEntry[];\n entityCount: number;\n};\n\ntype NativeBindingStaticRedactionResult = {\n resolvedEntities: NativeBindingPipelineEntity[];\n redaction: NativeBindingRedactionResult;\n};\n\ntype CanonicalPipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n source_detail?: string | null;\n};\n\ntype CanonicalStaticRedactionResult = {\n resolved_entities: CanonicalPipelineEntity[];\n redaction: {\n redacted_text: string;\n redaction_map: NativeBindingRedactionEntry[];\n operator_map: NativeBindingOperatorEntry[];\n entity_count: number;\n };\n};\n\nexport type NativePreparedSearchBinding = {\n prepareDiagnosticsJson?: () => string;\n warmLazyRegex?: () => void;\n warm_lazy_regex?: () => void;\n warmLazyRegexDiagnosticsJson?: () => string;\n warm_lazy_regex_diagnostics_json?: () => string;\n redactStaticEntities: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => NativeBindingStaticRedactionResult;\n redactStaticEntitiesJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n redactStaticEntitiesResultStreamJson?: (\n fullText: string,\n operators: NativeBindingOperatorConfig | undefined,\n onEvent: NativeResultEventCallback,\n ) => string;\n redactStaticEntitiesDiagnosticsJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n redactStaticEntitiesDiagnosticsStreamJson?: (\n fullText: string,\n operators: NativeBindingOperatorConfig | undefined,\n onBatch: NativeDiagnosticsBatchCallback,\n ) => string;\n redactStaticEntitiesSummaryDiagnosticsJson?: (\n fullText: string,\n operators?: NativeBindingOperatorConfig,\n ) => string;\n};\n\nexport type NativeAnonymizeBinding = {\n normalizeForSearch: (text: string) => string;\n nativePackageVersion: () => string;\n NativePreparedSearch: {\n fromConfigJsonBytes: (\n configJson: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromPreparedPackageBytes: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromPreparedPackageBytesWithoutCache?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromTrustedPreparedPackageBytes?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n fromTrustedPreparedPackageBytesWithoutCache?: (\n packageBytes: Uint8Array,\n ) => NativePreparedSearchBinding;\n };\n prepareStaticSearchPackageBytes: (configJson: Uint8Array) => Uint8Array;\n prepareStaticSearchCompressedPackageBytes: (\n configJson: Uint8Array,\n ) => Uint8Array;\n // Rust config assembler (replaces the retired TypeScript config-assembly\n // layer). Takes the pipeline config plus out-of-band dictionaries and\n // gazetteer JSON and returns either the assembled config JSON or ready\n // package bytes. Optional so older bindings without the assembler still\n // satisfy the type; native-node loads them from the same `.node`.\n assembleStaticSearchConfigJson?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n assembleStaticSearchPackageBytes?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n assembleStaticSearchCompressedPackageBytes?: (\n pipelineConfigJson: Uint8Array,\n dictionariesJson?: Uint8Array,\n gazetteerJson?: Uint8Array,\n ) => Uint8Array;\n};\n\nexport type NativeOperatorConfig = {\n operators?: Record<string, OperatorType>;\n redactString?: string;\n};\n\nexport type NativePipelineEntity = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n source: string;\n sourceDetail?: string;\n};\n\nexport type NativeRedactionResult = {\n redactedText: string;\n redactionMap: Map<string, string>;\n operatorMap: Map<string, OperatorType>;\n entityCount: number;\n};\n\nexport type NativeStaticRedactionResult = {\n resolvedEntities: NativePipelineEntity[];\n redaction: NativeRedactionResult;\n};\n\nexport type NativeSearchPackageOptions = {\n binding: NativeAnonymizeBinding;\n config: NativePreparedSearchConfig;\n compressed?: boolean;\n};\n\nexport type NativeSearchPackageInput =\n | NativePreparedSearchConfig\n | string\n | Uint8Array;\n\nexport type SharedNativeSearchPackageOptions = {\n binding: NativeAnonymizeBinding;\n config: NativeSearchPackageInput;\n compressed?: boolean;\n};\n\nexport type SharedNativePreparedPackageOptions = {\n binding: NativeAnonymizeBinding;\n packageBytes: Uint8Array;\n};\n\nexport type SharedNativeRedactTextJsonOptions = {\n binding: NativeAnonymizeBinding;\n config: NativeSearchPackageInput;\n fullText: string;\n operators?: NativeOperatorConfig;\n};\n\nexport type SharedNativeRedactTextOptions = SharedNativeRedactTextJsonOptions;\n\nexport type SharedNativeDiagnosticsJsonOptions =\n SharedNativeRedactTextJsonOptions;\n\nexport type SharedNativeDiagnosticsStreamJsonOptions =\n SharedNativeRedactTextJsonOptions & {\n onBatch: NativeDiagnosticsBatchCallback;\n };\n\nexport type SharedNativeRedactTextStreamJsonOptions =\n SharedNativeRedactTextJsonOptions & {\n onEvent: NativeResultEventCallback;\n };\n\nexport type NativeNormalizeOptions = {\n binding: NativeAnonymizeBinding;\n text: string;\n};\n\nexport type NativeAnonymizerFromConfigOptions = {\n binding: NativeAnonymizeBinding;\n config: NativePreparedSearchConfig;\n};\n\nexport type NativeAnonymizerFromPackageOptions = {\n binding: NativeAnonymizeBinding;\n packageBytes: Uint8Array;\n};\n\nexport type NativePipelineFromPackageOptions =\n NativeAnonymizerFromPackageOptions;\n\nexport type NativeBindingVersionOptions = {\n binding: NativeAnonymizeBinding;\n expectedVersion: string;\n};\n\nexport class PreparedNativeAnonymizer {\n readonly #prepared: NativePreparedSearchBinding;\n\n constructor(prepared: NativePreparedSearchBinding) {\n this.#prepared = prepared;\n }\n\n prepareDiagnosticsJson(): string | null {\n return this.#prepared.prepareDiagnosticsJson?.() ?? null;\n }\n\n prepare_diagnostics_json(): string | null {\n return this.prepareDiagnosticsJson();\n }\n\n warmLazyRegex(): void {\n if (this.#prepared.warmLazyRegex) {\n this.#prepared.warmLazyRegex();\n return;\n }\n this.#prepared.warm_lazy_regex?.();\n }\n\n warm_lazy_regex(): void {\n this.warmLazyRegex();\n }\n\n warmLazyRegexDiagnosticsJson(): string | null {\n if (this.#prepared.warmLazyRegexDiagnosticsJson) {\n return this.#prepared.warmLazyRegexDiagnosticsJson();\n }\n return this.#prepared.warm_lazy_regex_diagnostics_json?.() ?? null;\n }\n\n warm_lazy_regex_diagnostics_json(): string | null {\n return this.warmLazyRegexDiagnosticsJson();\n }\n\n redactStaticEntities(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return toNativeStaticRedactionResult(\n this.#prepared.redactStaticEntities(\n fullText,\n toBindingOperatorConfig(operators),\n ),\n );\n }\n\n redact_text(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.redactStaticEntities(fullText, operators);\n }\n\n redact_text_json(fullText: string, operators?: NativeOperatorConfig): string {\n const bindingOperators = toBindingOperatorConfig(operators);\n if (this.#prepared.redactStaticEntitiesJson) {\n return this.#prepared.redactStaticEntitiesJson(\n fullText,\n bindingOperators,\n );\n }\n return JSON.stringify(\n toBindingStaticRedactionResult(\n toNativeStaticRedactionResult(\n this.#prepared.redactStaticEntities(fullText, bindingOperators),\n ),\n ),\n );\n }\n\n redactTextJson(fullText: string, operators?: NativeOperatorConfig): string {\n return this.redact_text_json(fullText, operators);\n }\n\n redactTextStreamJson(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesResultStreamJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesResultStreamJson(\n fullText,\n toBindingOperatorConfig(operators),\n onEvent,\n );\n }\n\n redact_text_stream_json(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redactStaticEntitiesDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesDiagnosticsJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesDiagnosticsJson(\n fullText,\n toBindingOperatorConfig(operators),\n );\n }\n\n diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactStaticEntitiesDiagnosticsJson(fullText, operators);\n }\n\n diagnosticsStreamJson(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesDiagnosticsStreamJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesDiagnosticsStreamJson(\n fullText,\n toBindingOperatorConfig(operators),\n onBatch,\n );\n }\n\n diagnostics_stream_json(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n redactStaticEntitiesSummaryDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n if (!this.#prepared.redactStaticEntitiesSummaryDiagnosticsJson) {\n return null;\n }\n return this.#prepared.redactStaticEntitiesSummaryDiagnosticsJson(\n fullText,\n toBindingOperatorConfig(operators),\n );\n }\n\n summary_diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactStaticEntitiesSummaryDiagnosticsJson(fullText, operators);\n }\n}\n\nexport class PreparedNativePipeline {\n readonly #anonymizer: PreparedNativeAnonymizer;\n\n constructor(anonymizer: PreparedNativeAnonymizer) {\n this.#anonymizer = anonymizer;\n }\n\n prepareDiagnosticsJson(): string | null {\n return this.#anonymizer.prepareDiagnosticsJson();\n }\n\n prepare_diagnostics_json(): string | null {\n return this.prepareDiagnosticsJson();\n }\n\n warmLazyRegex(): void {\n this.#anonymizer.warmLazyRegex();\n }\n\n warm_lazy_regex(): void {\n this.warmLazyRegex();\n }\n\n warmLazyRegexDiagnosticsJson(): string | null {\n return this.#anonymizer.warmLazyRegexDiagnosticsJson();\n }\n\n warm_lazy_regex_diagnostics_json(): string | null {\n return this.warmLazyRegexDiagnosticsJson();\n }\n\n redactText(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.#anonymizer.redactStaticEntities(fullText, operators);\n }\n\n redact_text(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): NativeStaticRedactionResult {\n return this.redactText(fullText, operators);\n }\n\n redact_text_json(fullText: string, operators?: NativeOperatorConfig): string {\n return this.#anonymizer.redact_text_json(fullText, operators);\n }\n\n redactTextJson(fullText: string, operators?: NativeOperatorConfig): string {\n return this.redact_text_json(fullText, operators);\n }\n\n redactTextStreamJson(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redact_text_stream_json(\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextStreamJson(fullText, onEvent, operators);\n }\n\n redactTextDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactStaticEntitiesDiagnosticsJson(\n fullText,\n operators,\n );\n }\n\n diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextDiagnosticsJson(fullText, operators);\n }\n\n diagnosticsStreamJson(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n diagnostics_stream_json(\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.diagnosticsStreamJson(fullText, onBatch, operators);\n }\n\n redactTextSummaryDiagnosticsJson(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.#anonymizer.redactStaticEntitiesSummaryDiagnosticsJson(\n fullText,\n operators,\n );\n }\n\n summary_diagnostics_json(\n fullText: string,\n operators?: NativeOperatorConfig,\n ): string | null {\n return this.redactTextSummaryDiagnosticsJson(fullText, operators);\n }\n}\n\nexport const encodeNativeSearchConfig = (\n config: NativePreparedSearchConfig,\n): Uint8Array => new TextEncoder().encode(JSON.stringify(config));\n\nexport const encodeNativeSearchConfigInput = (\n config: NativeSearchPackageInput,\n): Uint8Array => {\n if (typeof config === \"string\") {\n return new TextEncoder().encode(config);\n }\n if (config instanceof Uint8Array) {\n return config;\n }\n return encodeNativeSearchConfig(config);\n};\n\nexport const getNativeBindingVersion = (\n binding: NativeAnonymizeBinding,\n): string => binding.nativePackageVersion();\n\nexport const native_package_version = getNativeBindingVersion;\n\nexport const normalize_for_search = ({\n binding,\n text,\n}: NativeNormalizeOptions): string => binding.normalizeForSearch(text);\n\nexport const assertNativeBindingVersion = ({\n binding,\n expectedVersion,\n}: NativeBindingVersionOptions): void => {\n const actualVersion = getNativeBindingVersion(binding);\n if (actualVersion !== expectedVersion) {\n throw new Error(\n `Native anonymize binding version ${actualVersion} does not match ${expectedVersion}`,\n );\n }\n};\n\nexport const prepareNativeSearchPackage = ({\n binding,\n config,\n compressed = false,\n}: NativeSearchPackageOptions): Uint8Array => {\n const configBytes = encodeNativeSearchConfig(config);\n return compressed\n ? binding.prepareStaticSearchCompressedPackageBytes(configBytes)\n : binding.prepareStaticSearchPackageBytes(configBytes);\n};\n\nexport const prepare_search_package = ({\n binding,\n config,\n compressed = false,\n}: SharedNativeSearchPackageOptions): Uint8Array => {\n const configBytes = encodeNativeSearchConfigInput(config);\n return compressed\n ? binding.prepareStaticSearchCompressedPackageBytes(configBytes)\n : binding.prepareStaticSearchPackageBytes(configBytes);\n};\n\nexport const createNativeAnonymizerFromConfig = ({\n binding,\n config,\n}: NativeAnonymizerFromConfigOptions): PreparedNativeAnonymizer =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfig(config),\n ),\n );\n\nexport const createNativeAnonymizerFromPackage = ({\n binding,\n packageBytes,\n}: NativeAnonymizerFromPackageOptions): PreparedNativeAnonymizer =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromPreparedPackageBytes(packageBytes),\n );\n\nexport const load_prepared_package = ({\n binding,\n packageBytes,\n}: SharedNativePreparedPackageOptions): PreparedNativeAnonymizer =>\n createNativeAnonymizerFromPackage({ binding, packageBytes });\n\nexport const redact_text_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeRedactTextJsonOptions): string =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text_json(fullText, operators);\n\nexport const redact_text = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeRedactTextOptions): NativeStaticRedactionResult =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text(fullText, operators);\n\nexport const redact_text_stream_json = ({\n binding,\n config,\n fullText,\n operators,\n onEvent,\n}: SharedNativeRedactTextStreamJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).redact_text_stream_json(fullText, onEvent, operators);\n\nexport const diagnostics_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeDiagnosticsJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).diagnostics_json(fullText, operators);\n\nexport const diagnostics_stream_json = ({\n binding,\n config,\n fullText,\n operators,\n onBatch,\n}: SharedNativeDiagnosticsStreamJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).diagnostics_stream_json(fullText, onBatch, operators);\n\nexport const summary_diagnostics_json = ({\n binding,\n config,\n fullText,\n operators,\n}: SharedNativeDiagnosticsJsonOptions): string | null =>\n new PreparedNativeAnonymizer(\n binding.NativePreparedSearch.fromConfigJsonBytes(\n encodeNativeSearchConfigInput(config),\n ),\n ).summary_diagnostics_json(fullText, operators);\n\nexport const createNativePipelineFromPackage = ({\n binding,\n packageBytes,\n}: NativePipelineFromPackageOptions): PreparedNativePipeline =>\n new PreparedNativePipeline(\n createNativeAnonymizerFromPackage({ binding, packageBytes }),\n );\n\nexport const PreparedSearch = PreparedNativeAnonymizer;\nexport type PreparedSearch = PreparedNativeAnonymizer;\nexport const PreparedAnonymizer = PreparedNativeAnonymizer;\nexport type PreparedAnonymizer = PreparedNativeAnonymizer;\n\nconst toBindingOperatorConfig = (\n config: NativeOperatorConfig | undefined,\n): NativeBindingOperatorConfig | undefined => {\n if (!config) {\n return undefined;\n }\n const bindingConfig: NativeBindingOperatorConfig = {};\n if (config.operators !== undefined) {\n bindingConfig.operators = config.operators;\n }\n if (config.redactString !== undefined) {\n bindingConfig.redactString = config.redactString;\n }\n return bindingConfig;\n};\n\nconst toNativeStaticRedactionResult = (\n result: NativeBindingStaticRedactionResult,\n): NativeStaticRedactionResult => ({\n resolvedEntities: result.resolvedEntities.map(toNativePipelineEntity),\n redaction: toNativeRedactionResult(result.redaction),\n});\n\nconst toBindingStaticRedactionResult = (\n result: NativeStaticRedactionResult,\n): CanonicalStaticRedactionResult => ({\n resolved_entities: result.resolvedEntities.map(toBindingPipelineEntity),\n redaction: {\n redacted_text: result.redaction.redactedText,\n redaction_map: [...result.redaction.redactionMap.entries()].map(\n ([placeholder, original]) => ({ placeholder, original }),\n ),\n operator_map: [...result.redaction.operatorMap.entries()].map(\n ([placeholder, operator]) => ({ placeholder, operator }),\n ),\n entity_count: result.redaction.entityCount,\n },\n});\n\nconst toNativePipelineEntity = (\n entity: NativeBindingPipelineEntity,\n): NativePipelineEntity => ({\n start: entity.start,\n end: entity.end,\n label: entity.label,\n text: entity.text,\n score: entity.score,\n source: entity.source,\n ...(entity.sourceDetail ? { sourceDetail: entity.sourceDetail } : {}),\n});\n\nconst toBindingPipelineEntity = ({\n sourceDetail,\n ...entity\n}: NativePipelineEntity): CanonicalPipelineEntity => ({\n ...entity,\n source_detail: sourceDetail ?? null,\n});\n\nconst toNativeRedactionResult = (\n result: NativeBindingRedactionResult,\n): NativeRedactionResult => ({\n redactedText: result.redactedText,\n redactionMap: toRedactionMap(result.redactionMap),\n operatorMap: toOperatorMap(result.operatorMap),\n entityCount: result.entityCount,\n});\n\nconst toRedactionMap = (\n entries: readonly NativeBindingRedactionEntry[],\n): Map<string, string> => {\n const map = new Map<string, string>();\n for (const entry of entries) {\n map.set(entry.placeholder, entry.original);\n }\n return map;\n};\n\nconst toOperatorMap = (\n entries: readonly NativeBindingOperatorEntry[],\n): Map<string, OperatorType> => {\n const map = new Map<string, OperatorType>();\n for (const entry of entries) {\n map.set(entry.placeholder, entry.operator);\n }\n return map;\n};\n","/**\n * Cached state for a single pipeline run (or a sequence of runs sharing the\n * same config). The native pipeline builds its prepared package once and reuses\n * it across calls with the same config; the package bytes and the key/promise\n * that guard concurrent builds live here so callers can share one warmed\n * context.\n */\nexport type PipelineContext = {\n // ── Native prepared-package cache ─────────────\n nativePipelinePackage: Uint8Array | null;\n nativePipelinePackageKey: string;\n nativePipelinePackagePromise: Promise<Uint8Array> | null;\n};\n\n/** Create a fresh, empty pipeline context. */\nexport const createPipelineContext = (): PipelineContext => ({\n nativePipelinePackage: null,\n nativePipelinePackageKey: \"\",\n nativePipelinePackagePromise: null,\n});\n\n/**\n * Module-level default context. Used when callers\n * don't provide an explicit context, preserving full\n * backward compatibility with the existing API.\n */\nexport const defaultContext: PipelineContext = createPipelineContext();\n","import {\n DEFAULT_OPERATOR_CONFIG,\n OPERATOR_REGISTRY,\n resolveOperator,\n} from \"./operators\";\nimport type {\n Entity,\n OperatorConfig,\n OperatorType,\n RedactionResult,\n} from \"./types\";\nimport type { PipelineContext } from \"./context\";\nimport { defaultContext } from \"./context\";\n\nconst WHITESPACE_RE = /\\s+/g;\nconst PHONE_NOISE_RE = /[()\\s-]/g;\nconst ETHEREUM_ADDRESS_RE = /0x[0-9A-Fa-f]{40}/;\nconst BECH32_ADDRESS_RE = /\\bbc1[ac-hj-np-z02-9]{11,71}\\b/i;\nconst BASE58_ADDRESS_RE = /\\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\\b/;\nconst NHS_NUMBER_CUE_RE = /\\b(?:NHS|National\\s+Health\\s+Service)\\b/i;\nconst PLACEHOLDER_TOKEN_RE = /\\[[^\\s[\\]]+_[1-9]\\d*\\]/g;\nconst PASSPORT_IDENTIFIER_RE =\n /\\b(?:[A-Za-z]{1,2}\\d{6,8}|\\d{2}[A-Za-z]{2}\\d{5}|\\d{7,9})\\b/;\n// Strip all separators the ID detectors accept so the\n// same real-world value canonicalises to one placeholder:\n// - whitespace and `-` for IBAN, NIP, REGON, etc.\n// - `/` for birth numbers (\"900101/1234\") and Czech\n// bank accounts (\"123-4567/0100\").\n// - `.` for credit cards (\"4111.1111.1111.1111\") and\n// other dotted IDs.\nconst ID_SEPARATOR_RE = /[\\s\\-/.]/g;\n\nconst nextPlaceholder = (\n labelKey: string,\n counters: Map<string, number>,\n reservedPlaceholders: ReadonlySet<string>,\n): string => {\n let count = counters.get(labelKey) ?? 0;\n\n while (true) {\n count += 1;\n const placeholder = `[${labelKey}_${count}]`;\n if (reservedPlaceholders.has(placeholder)) continue;\n\n counters.set(labelKey, count);\n return placeholder;\n }\n};\n\nconst collectReservedPlaceholders = (\n reservedText: string,\n): ReadonlySet<string> => new Set(reservedText.match(PLACEHOLDER_TOKEN_RE));\n\nconst normalizeCryptoText = (text: string): string => {\n const trimmed = text.trim();\n\n const ethereumAddress = ETHEREUM_ADDRESS_RE.exec(trimmed)?.[0];\n if (ethereumAddress) {\n return ethereumAddress.toLowerCase();\n }\n\n const bech32Address = BECH32_ADDRESS_RE.exec(trimmed)?.[0];\n if (bech32Address) {\n return bech32Address.toLowerCase();\n }\n\n const base58Address = BASE58_ADDRESS_RE.exec(trimmed)?.[0];\n return base58Address ?? trimmed;\n};\n\nconst normalizePassportText = (text: string): string => {\n const passportIdentifier = PASSPORT_IDENTIFIER_RE.exec(text)?.[0] ?? text;\n return passportIdentifier.replace(ID_SEPARATOR_RE, \"\").toUpperCase();\n};\n\n/**\n * Normalize entity text so that surface-form variations\n * of the same real-world value map to a single canonical\n * key. Lowercased emails, stripped phone formatting, etc.\n */\nconst normalizeEntityText = (label: string, text: string): string => {\n const upper = label.toUpperCase().replace(WHITESPACE_RE, \"_\");\n\n if (upper === \"EMAIL_ADDRESS\" || upper === \"EMAIL\") {\n return text.toLowerCase().trim();\n }\n if (upper === \"PHONE_NUMBER\" || upper === \"PHONE\") {\n return text.replace(PHONE_NOISE_RE, \"\");\n }\n if (upper === \"CRYPTO\") {\n return normalizeCryptoText(text);\n }\n if (\n upper === \"NATIONAL_IDENTIFICATION_NUMBER\" &&\n NHS_NUMBER_CUE_RE.test(text)\n ) {\n return text.replace(/\\D/g, \"\");\n }\n if (\n upper === \"IBAN\" ||\n upper === \"BANK_ACCOUNT_NUMBER\" ||\n upper === \"TAX_IDENTIFICATION_NUMBER\" ||\n upper === \"REGISTRATION_NUMBER\" ||\n upper === \"NATIONAL_IDENTIFICATION_NUMBER\" ||\n upper === \"SOCIAL_SECURITY_NUMBER\" ||\n upper === \"BIRTH_NUMBER\" ||\n upper === \"IDENTITY_CARD_NUMBER\" ||\n upper === \"CREDIT_CARD_NUMBER\"\n ) {\n return text.replace(ID_SEPARATOR_RE, \"\").toUpperCase();\n }\n if (upper === \"PASSPORT_NUMBER\") {\n return normalizePassportText(text);\n }\n if (\n upper === \"PERSON\" ||\n upper === \"ORGANIZATION\" ||\n upper === \"ADDRESS\" ||\n upper === \"LAND_PARCEL\" ||\n upper === \"MISC\"\n ) {\n return text.replace(WHITESPACE_RE, \" \").toLowerCase().trim();\n }\n return text.trim();\n};\n\n/**\n * Build a stable mapping from entity text to numbered\n * placeholders. Same real-world value always maps to the\n * same placeholder (e.g., \"Dr. Muller\" and \"Dr. Muller\"\n * share one person placeholder).\n *\n * Placeholder format: [LABEL_N] where LABEL is uppercase.\n * N is allocated per label and skips tokens already present\n * in reserved text.\n *\n * @param _ctx Unused. Kept for signature compatibility;\n * coref alias links now travel on the entities\n * themselves (`corefSourceText`).\n */\ntype PlaceholderMapOptions = {\n reservedText?: string;\n};\n\nexport const buildPlaceholderMap = (\n entities: Entity[],\n _ctx: PipelineContext = defaultContext,\n { reservedText = \"\" }: PlaceholderMapOptions = {},\n): Map<string, string> => {\n const counters = new Map<string, number>();\n const textLabelToPlaceholder = new Map<string, string>();\n const normalizedToPlaceholder = new Map<string, string>();\n const reservedPlaceholders = collectReservedPlaceholders(reservedText);\n\n const sorted = entities.toSorted((a, b) => a.start - b.start);\n\n for (const entity of sorted) {\n const compositeKey = `${entity.label}\\0${entity.text}`;\n if (textLabelToPlaceholder.has(compositeKey)) {\n continue;\n }\n\n const labelKey = entity.label.toUpperCase().replace(WHITESPACE_RE, \"_\");\n\n // If this entity is a coref alias, unify its key\n // with the source entity's key so both get the same\n // number — in either direction: a backward alias\n // joins the source's existing placeholder, and a\n // forward alias (bare mention before the full form)\n // reserves its placeholder under the source key so\n // the source joins it when numbered later. The link\n // is carried on the entity itself, so it cannot be\n // lost between detection and redaction.\n const sourceText =\n entity.source === \"coreference\" ? entity.corefSourceText : undefined;\n const sourceNormalizedKey =\n sourceText === undefined\n ? undefined\n : `${labelKey}\\0${normalizeEntityText(entity.label, sourceText)}`;\n if (sourceNormalizedKey !== undefined) {\n const sourceExisting = normalizedToPlaceholder.get(sourceNormalizedKey);\n if (sourceExisting) {\n textLabelToPlaceholder.set(compositeKey, sourceExisting);\n continue;\n }\n }\n\n const normalized = normalizeEntityText(entity.label, entity.text);\n const normalizedKey = `${labelKey}\\0${normalized}`;\n const existing = normalizedToPlaceholder.get(normalizedKey);\n if (existing) {\n textLabelToPlaceholder.set(compositeKey, existing);\n if (sourceNormalizedKey !== undefined) {\n normalizedToPlaceholder.set(sourceNormalizedKey, existing);\n }\n continue;\n }\n\n const placeholder = nextPlaceholder(\n labelKey,\n counters,\n reservedPlaceholders,\n );\n textLabelToPlaceholder.set(compositeKey, placeholder);\n normalizedToPlaceholder.set(normalizedKey, placeholder);\n if (sourceNormalizedKey !== undefined) {\n normalizedToPlaceholder.set(sourceNormalizedKey, placeholder);\n }\n }\n\n return textLabelToPlaceholder;\n};\n\n/**\n * Apply redactions to the source text, replacing each\n * confirmed entity span using the configured operator.\n *\n * Co-references are consistent: if the same text appears\n * multiple times, all occurrences get the same placeholder.\n *\n * @param ctx Pipeline context. Must be the same instance\n * passed to `runPipeline` (or `findCoreferenceSpans`)\n * so coreference placeholder links are preserved.\n * Defaults to `defaultContext` for single-tenant usage.\n */\nexport const redactText = (\n fullText: string,\n entities: Entity[],\n config: OperatorConfig = DEFAULT_OPERATOR_CONFIG,\n ctx: PipelineContext = defaultContext,\n): RedactionResult => {\n if (entities.length === 0) {\n return {\n redactedText: fullText,\n redactionMap: new Map(),\n operatorMap: new Map(),\n entityCount: 0,\n };\n }\n\n const placeholderMap = buildPlaceholderMap(entities, ctx, {\n reservedText: fullText,\n });\n\n const sorted = entities.toSorted((a, b) => a.start - b.start);\n\n // Remove overlapping spans (keep first occurrence)\n const nonOverlapping: Entity[] = [];\n let lastEnd = 0;\n for (const entity of sorted) {\n if (entity.start >= lastEnd) {\n nonOverlapping.push(entity);\n lastEnd = entity.end;\n }\n }\n\n const parts: string[] = [];\n const redactionMap = new Map<string, string>();\n const operatorMap = new Map<string, OperatorType>();\n let cursor = 0;\n\n for (const entity of nonOverlapping) {\n if (entity.start > cursor) {\n parts.push(fullText.slice(cursor, entity.start));\n }\n\n const placeholder =\n placeholderMap.get(`${entity.label}\\0${entity.text}`) ??\n `[${entity.label.toUpperCase().replace(/\\s+/g, \"_\")}]`;\n\n const opType = resolveOperator(config, entity.label);\n const operator = OPERATOR_REGISTRY[opType];\n\n const replacement = operator.apply(\n entity.text,\n entity.label,\n placeholder,\n config.redactString,\n );\n\n parts.push(replacement);\n // operatorMap is keyed by the conceptual placeholder\n // ([LABEL_N]), not by the replacement text. For \"redact\"\n // operators the placeholder never appears in the output;\n // the map is only consulted via exportRedactionKey which\n // iterates redactionMap (replace entries only).\n operatorMap.set(placeholder, opType);\n\n // Only populate redactionMap for reversible operators.\n // A coref alias contributes its source's full text, so\n // a forward alias (\"Acme\" before \"Acme Corporation\")\n // cannot pin the shortened surface form as the key's\n // canonical value for the shared placeholder.\n if (\n operator.reversibility === \"reversible\" &&\n !redactionMap.has(placeholder)\n ) {\n redactionMap.set(\n placeholder,\n entity.source === \"coreference\" ? entity.corefSourceText : entity.text,\n );\n }\n\n cursor = entity.end;\n }\n\n if (cursor < fullText.length) {\n parts.push(fullText.slice(cursor));\n }\n\n return {\n redactedText: parts.join(\"\"),\n redactionMap,\n operatorMap,\n entityCount: nonOverlapping.length,\n };\n};\n\n/**\n * Serialize the redaction key to JSON for export.\n * Includes operator metadata so the export is self-describing.\n */\nexport const exportRedactionKey = (\n redactionMap: Map<string, string>,\n operatorMap: Map<string, OperatorType>,\n): string => {\n const entries: Record<string, { original: string; operator: OperatorType }> =\n {};\n\n for (const [placeholder, value] of redactionMap) {\n entries[placeholder] = {\n original: value,\n operator: operatorMap.get(placeholder) ?? \"replace\",\n };\n }\n\n return JSON.stringify({ entries }, null, 2);\n};\n\n/**\n * De-anonymise text using a redaction key.\n * Replaces placeholders back with original values.\n * Only works for reversible operators (replace).\n */\nexport const deanonymise = (\n redactedText: string,\n redactionMap: Map<string, string>,\n): string => {\n let result = redactedText;\n\n for (const [placeholder, original] of redactionMap) {\n result = result.replaceAll(placeholder, original);\n }\n\n return result;\n};\n","// Runtime-free constants live in `./constants`; re-exported\n// here for back-compat with existing call sites that import\n// from `@stll/anonymize` directly.\n//\n// `verbatimModuleSyntax` requires an explicit type-only\n// import for any name used locally as a type even when it\n// is also re-exported below — applies to `DetectionSource`\n// (used by `Entity`) and `OperatorType` (used by\n// `OperatorConfig`).\nimport type { DetectionSource, OperatorType } from \"./constants\";\nimport { DETECTION_SOURCES } from \"./constants\";\n\nexport {\n DETECTION_SOURCES,\n DETECTOR_PRIORITY,\n type DetectionSource,\n} from \"./constants\";\n\n/**\n * Fields shared by every entity span in the source text.\n */\ntype EntityBase = {\n start: number;\n end: number;\n label: string;\n text: string;\n score: number;\n sourceDetail?: \"custom-deny-list\" | \"custom-regex\" | \"gazetteer-extension\";\n};\n\n/**\n * A PII entity span found by a primary detection layer\n * (regex, NER, legal forms, deny list, ...).\n */\nexport type DetectedEntity = EntityBase & {\n source: Exclude<DetectionSource, typeof DETECTION_SOURCES.COREFERENCE>;\n};\n\n/**\n * An alias mention of a previously detected entity: a\n * defined term (\"the Seller\") or a propagated bare\n * mention (\"Acme\" after \"Acme Corp.\").\n *\n * `corefSourceText` is required by construction, so an\n * alias cannot exist without the link back to its source\n * entity. Placeholder numbering reads it to give the\n * alias the same placeholder as the source. The link\n * travels with the entity instead of living in a\n * side-channel map that a producer could forget to\n * write — or that a later pass could clear.\n */\nexport type CorefAliasEntity = EntityBase & {\n source: typeof DETECTION_SOURCES.COREFERENCE;\n /** Full text of the source entity this alias refers to. */\n corefSourceText: string;\n};\n\n/**\n * A detected PII entity span in the source text.\n * Every detection layer produces these.\n */\nexport type Entity = DetectedEntity | CorefAliasEntity;\n\n/**\n * Entity after human review. Extends the base Entity\n * with a review decision.\n */\nexport type ReviewDecision = \"confirmed\" | \"rejected\" | \"relabeled\";\n\nexport type ReviewedEntity = Entity & {\n decision?: ReviewDecision;\n originalLabel?: string;\n};\n\n/**\n * A single entry in the workspace-scoped gazetteer\n * (deny list). Persisted in IndexedDB.\n */\nexport type GazetteerEntry = {\n id: string;\n canonical: string;\n label: string;\n variants: string[];\n workspaceId: string;\n createdAt: number;\n source: \"manual\" | \"confirmed-from-model\";\n};\n\n/** Extraction strategy — closed discriminated union. */\nexport type TriggerStrategy =\n | {\n type: \"to-next-comma\";\n /**\n * Optional list of lowercase keywords that terminate\n * the value scan, in addition to commas/newlines. Useful\n * for triggers like court names that may continue past\n * a missing comma into adjacent clause text (\"Městským\n * soudem v Praze dne 1. 1. 2020\"); listing `\"dne\"` here\n * stops the scan at the date boundary. Matched on a\n * word-boundary, case-insensitive.\n */\n stopWords?: string[];\n /**\n * Hard cap on the captured span length, in characters,\n * regardless of where the next comma / stop char sits.\n * Use for triggers that label short formulaic phrases\n * (\"State of Delaware\") and must not absorb the rest\n * of a long forum-selection clause when the comma is\n * sentences away. Falls back to the default 100-char\n * fallback when omitted.\n */\n maxLength?: number;\n }\n | { type: \"to-end-of-line\" }\n | { type: \"n-words\"; count: number }\n | { type: \"company-id-value\" }\n | { type: \"address\"; maxChars?: number }\n | {\n /**\n * Extract the first regex match in the value text.\n * Useful for shape-bounded values that follow a\n * label on the same line as other fields, where\n * `to-end-of-line` would over-capture. The pattern\n * is anchored to the start of the (already\n * leading-whitespace-stripped) value, so use\n * `(?:.*?)` prefix only when intentional.\n */\n type: \"match-pattern\";\n pattern: string;\n flags?: string;\n };\n\n/** Validation rules — closed discriminated union. */\nexport type TriggerValidation =\n | { type: \"starts-uppercase\" }\n | { type: \"min-length\"; min: number }\n | { type: \"max-length\"; max: number }\n | { type: \"no-digits\" }\n | { type: \"has-digits\" }\n | {\n type: \"matches-pattern\";\n pattern: string;\n flags?: string;\n }\n /**\n * Run a named stdnum validator (checksum + length)\n * against the captured value. Keeps the trigger\n * path symmetrical with the formatted-regex\n * detectors so e.g. `CPF nº 00000000000` does not\n * survive as a tax-ID entity.\n */\n | { type: \"valid-id\"; validator: ValidIdValidator };\n\n/** Built-in stdnum validators that can be referenced\n * by `valid-id` validations. */\nexport type ValidIdValidator = \"br.cpf\" | \"br.cnpj\" | \"us.rtn\";\n\n/** Auto-generated trigger variants — closed set. */\nexport type TriggerExtension =\n | \"add-colon\"\n | \"add-trailing-space\"\n | \"add-colon-space\"\n | \"normalize-spaces\";\n\n/** V2 trigger config entry (JSON shape). */\nexport type TriggerGroupConfig = {\n id?: string;\n triggers: string[];\n label: string;\n strategy: TriggerStrategy;\n extensions?: TriggerExtension[];\n validations?: TriggerValidation[];\n /** When true, include the trigger text in the\n * entity span (e.g., court names). */\n includeTrigger?: boolean;\n};\n\n/** Compiled validation with pre-built regex. */\nexport type CompiledValidation =\n | { type: \"starts-uppercase\"; re: RegExp }\n | { type: \"min-length\"; min: number }\n | { type: \"max-length\"; max: number }\n | { type: \"no-digits\"; re: RegExp }\n | { type: \"has-digits\"; re: RegExp }\n | { type: \"matches-pattern\"; re: RegExp }\n | {\n type: \"valid-id\";\n validator: ValidIdValidator;\n check: (value: string) => boolean;\n };\n\n/**\n * Runtime rule — one per trigger string after\n * expansion. Fed to the Aho-Corasick automaton.\n */\nexport type TriggerRule = {\n trigger: string;\n label: string;\n strategy: TriggerStrategy;\n validations: CompiledValidation[];\n includeTrigger: boolean;\n};\n\nexport { OPERATOR_TYPES, type OperatorType } from \"./constants\";\n\n/** Per-label operator selection. Key is the entity label. */\nexport type OperatorConfig = {\n /** Operator per label. Missing labels default to \"replace\". */\n operators: Record<string, OperatorType>;\n /** Custom replacement string for the redact operator. */\n redactString: string;\n};\n\n/** Whether an operator produces a reversible redaction entry. */\ntype OperatorReversibility = \"reversible\" | \"irreversible\";\n\nexport type AnonymisationOperator = {\n type: OperatorType;\n reversibility: OperatorReversibility;\n /**\n * Apply the operator to a single entity occurrence.\n * Returns the replacement string to embed in the document.\n */\n apply: (\n text: string,\n label: string,\n placeholder: string,\n redactString: string,\n ) => string;\n};\n\n/**\n * Redacted document output with stable entity mapping.\n */\nexport type RedactionResult = {\n redactedText: string;\n /**\n * Maps placeholder to original text. Only populated for\n * reversible operators (replace). Empty for redact.\n */\n redactionMap: Map<string, string>;\n /** Maps placeholder to the operator that produced it. */\n operatorMap: Map<string, OperatorType>;\n entityCount: number;\n};\n\n/**\n * Configuration for the detection pipeline.\n */\nexport type DenyListCategory =\n | \"Names\"\n | \"Places\"\n | \"Addresses\"\n | \"Courts\"\n | \"Financial\"\n | \"Government\"\n | \"Healthcare\"\n | \"Education\"\n | \"Political\"\n | \"Organizations\"\n | \"International\";\n\n/**\n * Metadata for a single dictionary entry in the\n * deny-list system. Mirrors the shape from\n * the anonymize-data package so consumers can pass\n * pre-loaded data without a runtime dependency.\n */\nexport type DictionaryMeta = {\n label: string;\n category: DenyListCategory;\n country: string | null;\n};\n\n/**\n * Caller-supplied exact terms for deny-list matching.\n * These entries are merged with the published deny-list\n * dictionaries when `enableDenyList` is enabled.\n */\nexport type CustomDenyListEntry = {\n value: string;\n label: string;\n variants?: readonly string[];\n};\n\n/**\n * Caller-supplied regex detector. The pattern is passed\n * to the underlying text-search regex engine, so use its\n * supported regex syntax. Inline flags such as `(?i)` are\n * accepted when supported by that engine.\n */\nexport type CustomRegexPattern = {\n pattern: string;\n label: string;\n score?: number;\n preparedArtifactPolicy?: \"include\" | \"omit\";\n};\n\n/**\n * Pre-loaded dictionary data for dependency injection.\n * Consumers that want name/city/deny-list detection\n * load dictionaries themselves (e.g. from the\n * anonymize-data package) and pass them here; the\n * anonymize package has zero cross-package imports.\n *\n * All fields are optional. When a field is absent,\n * the corresponding detection path is skipped (same\n * behavior as when no dictionaries are available).\n */\nexport type Dictionaries = {\n /**\n * First names per language code (e.g., \"cs\", \"de\").\n * Merged with legacy config names at init time.\n */\n firstNames?: Readonly<Record<string, readonly string[]>>;\n /**\n * Surnames per language code.\n * Merged with legacy config names at init time.\n */\n surnames?: Readonly<Record<string, readonly string[]>>;\n /**\n * Non-Western name tokens per locale code\n * (e.g., \"in\", \"ar\", \"ja-latn\", \"ko\", \"zh-latn\",\n * \"th\", \"vi\", \"fil\", \"id\"). Merged with bundled\n * names-nw-*.json data at init time.\n */\n nonWesternNames?: Readonly<Record<string, readonly string[]>>;\n /**\n * Pre-loaded deny-list dictionaries keyed by\n * dictionary ID (e.g., \"courts/CZ\", \"banks/DE\").\n * Each value is the array of terms for that\n * dictionary.\n */\n denyList?: Readonly<Record<string, readonly string[]>>;\n /**\n * Metadata per dictionary ID. Required when\n * `denyList` is provided so the pipeline knows\n * labels, categories, and country filters.\n */\n denyListMeta?: Readonly<Record<string, DictionaryMeta>>;\n /**\n * Pre-loaded city names, already merged across\n * all desired countries.\n *\n * Prefer `citiesByCountry` when callers also pass\n * `denyListCountries` / `denyListRegions`; merged\n * city arrays cannot be scoped after injection.\n */\n cities?: readonly string[];\n /**\n * Pre-loaded city names keyed by ISO 3166-1 alpha-2\n * country code. When provided, the deny-list builder\n * applies `denyListCountries` / `denyListRegions`\n * before adding city patterns to the search automaton.\n */\n citiesByCountry?: Readonly<Record<string, readonly string[]>>;\n};\n\nexport type PipelineConfig = {\n threshold: number;\n enableTriggerPhrases: boolean;\n enableRegex: boolean;\n /**\n * Expected content language codes. When present, these\n * derive default dictionary scopes for name corpus and\n * deny-list matching unless the lower-level scope fields\n * below are set explicitly.\n */\n languages?: string[];\n /**\n * Convenience form for single-language documents. Ignored\n * when `languages` is also provided.\n */\n language?: string;\n /**\n * Enables legal-form organization detection.\n * Required for typed callers; legacy untyped\n * callers that omit this field are treated as\n * enabled at runtime for backward compatibility.\n */\n enableLegalForms: boolean;\n /**\n * Enables first-name/surname/title corpus matching.\n * When deny-list mode is enabled, this also controls\n * whether name-corpus entries are injected into the\n * deny-list search automaton.\n */\n enableNameCorpus: boolean;\n /**\n * Optional language scope for first-name/surname\n * dictionaries, using the keys present in\n * `dictionaries.firstNames` / `dictionaries.surnames`\n * (for example `[\"en\", \"de\"]`). When omitted, all\n * injected name languages are used for backward\n * compatibility.\n */\n nameCorpusLanguages?: string[];\n enableDenyList: boolean;\n denyListCountries?: string[];\n denyListRegions?: string[];\n denyListExcludeCategories?: string[];\n /**\n * Caller-owned exact terms to match through the\n * deny-list layer. Requires `enableDenyList: true`.\n */\n customDenyList?: readonly CustomDenyListEntry[];\n /**\n * Caller-owned regex detectors. Requires\n * `enableRegex: true`.\n */\n customRegexes?: readonly CustomRegexPattern[];\n enableGazetteer: boolean;\n /**\n * Detect country names (ISO 3166-1 names, curated\n * aliases, alpha-3 codes). Defaults to true. Names\n * span all manifest languages plus widely-used\n * additions (Dutch, Russian, Chinese, Arabic, etc.).\n */\n enableCountries?: boolean;\n enableNer: boolean;\n enableConfidenceBoost: boolean;\n enableCoreference: boolean;\n enableZoneClassification?: boolean;\n enableHotwordRules?: boolean;\n /**\n * Requested output labels. An empty array means\n * \"do not filter by label\" for deterministic\n * detectors; NER falls back to DEFAULT_ENTITY_LABELS.\n */\n labels: string[];\n workspaceId: string;\n /**\n * Pre-loaded dictionary data for name, deny-list,\n * and city detection. When omitted, dictionary-based\n * detection paths are skipped. Consumers load from\n * the anonymize-data package and pass the data here.\n */\n dictionaries?: Dictionaries;\n};\n\nexport { DEFAULT_ENTITY_LABELS } from \"./constants\";\n\nexport const isLegalFormsEnabled = (\n config: Pick<PipelineConfig, \"enableLegalForms\">,\n): boolean => config.enableLegalForms !== false;\n","","import languageScopes from \"./data/language-scopes.json\";\n\nimport type { PipelineConfig } from \"./types\";\n\ntype LanguageScope = {\n nameCorpusLanguages?: readonly string[];\n denyListCountries?: readonly string[];\n};\n\ntype LanguageScopeData = {\n languages: Record<string, LanguageScope>;\n};\n\nconst scopeData = languageScopes as LanguageScopeData;\n\nconst normalizeLanguage = (language: string): string =>\n language.trim().toLowerCase();\n\nconst fallbackLanguage = (language: string): string | null => {\n const index = language.indexOf(\"-\");\n return index === -1 ? null : language.slice(0, index);\n};\n\nconst uniquePush = (target: string[], values: readonly string[]): void => {\n const seen = new Set(target);\n for (const value of values) {\n if (seen.has(value)) {\n continue;\n }\n seen.add(value);\n target.push(value);\n }\n};\n\nconst resolveLanguageScope = (language: string): LanguageScope | null => {\n const normalized = normalizeLanguage(language);\n if (normalized.length === 0) {\n return null;\n }\n const exact = scopeData.languages[normalized];\n if (exact !== undefined) {\n return exact;\n }\n const fallback = fallbackLanguage(normalized);\n return fallback === null ? null : (scopeData.languages[fallback] ?? null);\n};\n\nconst configuredLanguages = (config: PipelineConfig): readonly string[] => {\n if (config.languages !== undefined) {\n return config.languages;\n }\n return config.language === undefined ? [] : [config.language];\n};\n\nexport const configuredContentLanguages = (\n config: Pick<PipelineConfig, \"language\" | \"languages\">,\n): readonly string[] | undefined => {\n if (config.languages !== undefined) {\n return config.languages;\n }\n return config.language === undefined ? undefined : [config.language];\n};\n\nexport const applyPipelineLanguageScope = (\n config: PipelineConfig,\n): PipelineConfig => {\n const languages = configuredLanguages(config);\n if (languages.length === 0) {\n return config;\n }\n\n const nameCorpusLanguages: string[] = [];\n const denyListCountries: string[] = [];\n for (const language of languages) {\n const scope = resolveLanguageScope(language);\n if (scope === null) {\n continue;\n }\n uniquePush(nameCorpusLanguages, scope.nameCorpusLanguages ?? []);\n uniquePush(denyListCountries, scope.denyListCountries ?? []);\n }\n\n const next: Partial<PipelineConfig> = {};\n if (\n config.nameCorpusLanguages === undefined &&\n nameCorpusLanguages.length > 0\n ) {\n next.nameCorpusLanguages = nameCorpusLanguages;\n }\n if (config.denyListCountries === undefined && denyListCountries.length > 0) {\n next.denyListCountries = denyListCountries;\n }\n\n return Object.keys(next).length === 0 ? config : { ...config, ...next };\n};\n","const normalizeLanguageCode = (language: string): string =>\n language.trim().toLowerCase();\n\nconst normalizeLanguageSelection = (\n languages: readonly string[] | undefined,\n): string[] =>\n languages === undefined\n ? []\n : languages\n .map(normalizeLanguageCode)\n .filter((language) => language.length > 0);\n\nexport const languageSelectionKey = (\n languages: readonly string[] | undefined,\n): string => {\n const normalized = normalizeLanguageSelection(languages).toSorted();\n return normalized.length === 0 ? \"*\" : normalized.join(\",\");\n};\n\nconst baseLanguage = (language: string): string => {\n const index = language.indexOf(\"-\");\n return index === -1 ? language : language.slice(0, index);\n};\n\nexport const languageConfigMatches = (\n configLanguage: string,\n selectedLanguages: readonly string[] | undefined,\n): boolean => {\n if (selectedLanguages === undefined || selectedLanguages.length === 0) {\n return true;\n }\n const normalizedSelectedLanguages =\n normalizeLanguageSelection(selectedLanguages);\n if (normalizedSelectedLanguages.length === 0) {\n return true;\n }\n\n const normalizedConfigLanguage = normalizeLanguageCode(configLanguage);\n if (normalizedConfigLanguage.length === 0) {\n return false;\n }\n\n const genericConfig =\n baseLanguage(normalizedConfigLanguage) === normalizedConfigLanguage;\n for (const normalizedLanguage of normalizedSelectedLanguages) {\n if (normalizedLanguage === normalizedConfigLanguage) {\n return true;\n }\n if (\n genericConfig &&\n baseLanguage(normalizedLanguage) === normalizedConfigLanguage\n ) {\n return true;\n }\n }\n\n return false;\n};\n","import {\n isLegalFormsEnabled,\n type GazetteerEntry,\n type PipelineConfig,\n} from \"./types\";\nimport { languageSelectionKey } from \"./util/language-selection\";\n\nconst DEFAULT_CUSTOM_REGEX_SCORE = 0.9;\n\nconst contentLanguageFingerprint = (\n config: Pick<PipelineConfig, \"language\" | \"languages\">,\n): string => {\n const languages =\n config.languages ??\n (config.language === undefined ? [] : [config.language]);\n return languageSelectionKey(languages);\n};\n\nexport const pipelineConfigKey = (\n config: PipelineConfig,\n gazetteerEntries: readonly GazetteerEntry[],\n): string => {\n const legalFormsEnabled = isLegalFormsEnabled(config);\n const customDenyFingerprint =\n config.enableDenyList && config.customDenyList\n ? config.customDenyList\n .map((entry) =>\n JSON.stringify({\n label: entry.label,\n value: entry.value,\n variants: [...(entry.variants ?? [])].sort(),\n }),\n )\n .sort()\n .join(\"\\n\")\n : \"\";\n const customRegexFingerprint =\n config.enableRegex && config.customRegexes\n ? config.customRegexes\n .map((entry) =>\n JSON.stringify({\n label: entry.label,\n pattern: entry.pattern,\n preparedArtifactPolicy: entry.preparedArtifactPolicy ?? null,\n score: entry.score ?? DEFAULT_CUSTOM_REGEX_SCORE,\n }),\n )\n .sort()\n .join(\"\\n\")\n : \"\";\n const gazFingerprint =\n config.enableGazetteer && gazetteerEntries.length > 0\n ? gazetteerEntries\n .map(\n (entry) =>\n `${entry.id}:${entry.canonical}:${entry.label}:${[\n ...entry.variants,\n ]\n .sort()\n .join(\",\")}`,\n )\n .toSorted()\n .join(\";\")\n : \"\";\n\n return (\n `${config.enableDenyList}:` +\n `${config.enableTriggerPhrases}:` +\n `${legalFormsEnabled}:` +\n `${config.enableNameCorpus}:` +\n `${contentLanguageFingerprint(config)}:` +\n `${config.nameCorpusLanguages?.toSorted().join(\",\") ?? \"\"}:` +\n `${config.enableRegex}:` +\n `${config.threshold}:` +\n `${config.enableConfidenceBoost}:` +\n `${config.enableHotwordRules === true}:` +\n `${config.enableCoreference === true}:` +\n `${config.enableZoneClassification === true}:` +\n `${config.labels.toSorted().join(\",\")}:` +\n `${config.denyListCountries?.toSorted().join(\",\") ?? \"\"}:` +\n `${config.denyListRegions?.toSorted().join(\",\") ?? \"\"}:` +\n `${config.denyListExcludeCategories?.toSorted().join(\",\") ?? \"\"}:` +\n `${customDenyFingerprint}:` +\n `${customRegexFingerprint}:` +\n `${config.enableGazetteer}:${gazFingerprint}:` +\n `${config.enableCountries !== false}`\n );\n};\n","import type { PipelineContext } from \"./context\";\nimport { defaultContext } from \"./context\";\nimport { applyPipelineLanguageScope } from \"./language-scope\";\nimport type { NativePreparedSearchConfig } from \"./native-search-config\";\nimport { pipelineConfigKey } from \"./pipeline-cache-key\";\nimport type { Dictionaries, GazetteerEntry, PipelineConfig } from \"./types\";\nimport {\n createNativePipelineFromPackage,\n PreparedNativePipeline,\n type NativeAnonymizeBinding,\n} from \"./native\";\n\nexport {\n PreparedNativePipeline,\n createNativePipelineFromPackage,\n} from \"./native\";\n\nexport type NativePipelineUnsupportedFeature = \"enableNer\";\n\nexport type NativePipelineCompatibility =\n | { status: \"supported\" }\n | {\n status: \"unsupported\";\n unsupportedFeatures: NativePipelineUnsupportedFeature[];\n };\n\nexport type NativePipelineBuildOptions = {\n binding: NativeAnonymizeBinding;\n config: PipelineConfig;\n gazetteerEntries?: GazetteerEntry[];\n context?: PipelineContext;\n};\n\nexport type NativePipelinePackageOptions = NativePipelineBuildOptions & {\n compressed?: boolean;\n};\n\nexport type { NativePipelineFromPackageOptions } from \"./native\";\n\ntype NativePipelinePackageCacheValue = Promise<Uint8Array> | Uint8Array;\n\nconst sharedPackageByDictionaries = new WeakMap<\n Dictionaries,\n Map<string, NativePipelinePackageCacheValue>\n>();\nconst sharedPackageWithoutDictionaries = new Map<\n string,\n NativePipelinePackageCacheValue\n>();\nconst dictionaryCacheIds = new WeakMap<Dictionaries, number>();\nlet nextDictionaryCacheId = 0;\n\nconst dictionaryCacheKey = (dictionaries: Dictionaries | undefined): string => {\n if (dictionaries === undefined) {\n return \"none\";\n }\n const existing = dictionaryCacheIds.get(dictionaries);\n if (existing !== undefined) {\n return `dict:${existing}`;\n }\n nextDictionaryCacheId += 1;\n dictionaryCacheIds.set(dictionaries, nextDictionaryCacheId);\n return `dict:${nextDictionaryCacheId}`;\n};\n\nconst sharedPackageCacheFor = (\n dictionaries: Dictionaries | undefined,\n): Map<string, NativePipelinePackageCacheValue> => {\n if (dictionaries === undefined) {\n return sharedPackageWithoutDictionaries;\n }\n const cached = sharedPackageByDictionaries.get(dictionaries);\n if (cached !== undefined) {\n return cached;\n }\n const created = new Map<string, NativePipelinePackageCacheValue>();\n sharedPackageByDictionaries.set(dictionaries, created);\n return created;\n};\n\nexport const getNativePipelineCompatibility = (\n config: PipelineConfig,\n): NativePipelineCompatibility => {\n const unsupportedFeatures: NativePipelineUnsupportedFeature[] = [];\n\n if (config.enableNer) unsupportedFeatures.push(\"enableNer\");\n if (unsupportedFeatures.length === 0) {\n return { status: \"supported\" };\n }\n return { status: \"unsupported\", unsupportedFeatures };\n};\n\nexport const assertNativePipelineSupported = (config: PipelineConfig): void => {\n const compatibility = getNativePipelineCompatibility(config);\n if (compatibility.status === \"supported\") {\n return;\n }\n throw new Error(\n `Native pipeline does not yet support: ${compatibility.unsupportedFeatures.join(\", \")}`,\n );\n};\n\nconst encoder = new TextEncoder();\n\ntype AssembleInputs = {\n pipelineConfigJson: Uint8Array;\n dictionariesJson: Uint8Array | undefined;\n gazetteerJson: Uint8Array | undefined;\n};\n\n/**\n * Serialize the assembler inputs the Rust binding expects. Dictionaries are\n * stripped from the pipeline config and passed out of band: the assembler reads\n * the separate bundle preferentially, and keeping the (large) dictionaries out\n * of the config JSON avoids serializing them twice.\n */\nconst toAssembleInputs = (\n { dictionaries, ...config }: PipelineConfig,\n gazetteerEntries: readonly GazetteerEntry[],\n): AssembleInputs => ({\n pipelineConfigJson: encoder.encode(JSON.stringify(config)),\n dictionariesJson:\n dictionaries === undefined\n ? undefined\n : encoder.encode(JSON.stringify(dictionaries)),\n gazetteerJson:\n gazetteerEntries.length === 0\n ? undefined\n : encoder.encode(JSON.stringify(gazetteerEntries)),\n});\n\nconst assemblePackageBytes = (\n binding: NativeAnonymizeBinding,\n { pipelineConfigJson, dictionariesJson, gazetteerJson }: AssembleInputs,\n compressed: boolean,\n): Uint8Array => {\n const assemble = compressed\n ? binding.assembleStaticSearchCompressedPackageBytes\n : binding.assembleStaticSearchPackageBytes;\n if (assemble === undefined) {\n throw new Error(\n \"Native anonymize binding does not support static-search config assembly\",\n );\n }\n return assemble(pipelineConfigJson, dictionariesJson, gazetteerJson);\n};\n\nexport const prepareNativePipelineConfig = async ({\n binding,\n config,\n gazetteerEntries = [],\n}: Omit<\n NativePipelineBuildOptions,\n \"context\"\n>): Promise<NativePreparedSearchConfig> => {\n const scopedConfig = applyPipelineLanguageScope(config);\n assertNativePipelineSupported(scopedConfig);\n const assemble = binding.assembleStaticSearchConfigJson;\n if (assemble === undefined) {\n throw new Error(\n \"Native anonymize binding does not support static-search config assembly\",\n );\n }\n const { pipelineConfigJson, dictionariesJson, gazetteerJson } =\n toAssembleInputs(scopedConfig, gazetteerEntries);\n const configJson = assemble(\n pipelineConfigJson,\n dictionariesJson,\n gazetteerJson,\n );\n return JSON.parse(new TextDecoder().decode(configJson));\n};\n\nexport const prepareNativePipelinePackage = async ({\n binding,\n config,\n gazetteerEntries = [],\n context,\n compressed = false,\n}: NativePipelinePackageOptions): Promise<Uint8Array> => {\n const packageBytes = await getCachedNativePipelinePackage({\n config,\n binding,\n gazetteerEntries,\n ...(context ? { context } : {}),\n compressed,\n });\n // Return a genuine copy: with the real NAPI binding packageBytes is a Node\n // Buffer, and Buffer.prototype.slice() yields a memory-sharing view, so a\n // caller mutating it would corrupt the shared cache and ctx.nativePipelinePackage.\n return new Uint8Array(packageBytes);\n};\n\nexport const createNativePipelineFromConfig = async ({\n binding,\n config,\n gazetteerEntries = [],\n context,\n}: NativePipelineBuildOptions): Promise<PreparedNativePipeline> => {\n const packageBytes = await getCachedNativePipelinePackage({\n binding,\n config,\n gazetteerEntries,\n ...(context ? { context } : {}),\n });\n return createNativePipelineFromPackage({ binding, packageBytes });\n};\n\nconst getCachedNativePipelinePackage = async ({\n binding,\n config,\n gazetteerEntries = [],\n context,\n compressed = false,\n}: NativePipelinePackageOptions): Promise<Uint8Array> => {\n const scopedConfig = applyPipelineLanguageScope(config);\n assertNativePipelineSupported(scopedConfig);\n const ctx = context ?? defaultContext;\n const key = nativePackageCacheKey({\n binding,\n config: scopedConfig,\n gazetteerEntries,\n compressed,\n });\n if (ctx.nativePipelinePackage && ctx.nativePipelinePackageKey === key) {\n return ctx.nativePipelinePackage;\n }\n if (\n ctx.nativePipelinePackagePromise &&\n ctx.nativePipelinePackageKey === key\n ) {\n return ctx.nativePipelinePackagePromise;\n }\n\n const sharedCache = sharedPackageCacheFor(scopedConfig.dictionaries);\n const shared = sharedCache.get(key);\n if (shared !== undefined) {\n const packageBytes = await shared;\n ctx.nativePipelinePackage = packageBytes;\n ctx.nativePipelinePackageKey = key;\n ctx.nativePipelinePackagePromise = null;\n return packageBytes;\n }\n\n ctx.nativePipelinePackage = null;\n ctx.nativePipelinePackageKey = key;\n const promise = buildNativePipelinePackage({\n binding,\n config: scopedConfig,\n gazetteerEntries,\n compressed,\n });\n ctx.nativePipelinePackagePromise = promise;\n sharedCache.set(key, promise);\n let packageBytes: Uint8Array;\n try {\n packageBytes = await promise;\n } catch (error) {\n if (sharedCache.get(key) === promise) {\n sharedCache.delete(key);\n }\n if (\n ctx.nativePipelinePackageKey === key &&\n ctx.nativePipelinePackagePromise === promise\n ) {\n ctx.nativePipelinePackage = null;\n ctx.nativePipelinePackagePromise = null;\n }\n throw error;\n }\n if (sharedCache.get(key) === promise) {\n sharedCache.set(key, packageBytes);\n }\n if (ctx.nativePipelinePackageKey === key) {\n ctx.nativePipelinePackage = packageBytes;\n ctx.nativePipelinePackagePromise = null;\n }\n return packageBytes;\n};\n\n// `async` so the shared package cache can store the in-flight value and dedupe\n// concurrent builds for the same key, and so assembly failures (an older\n// binding without the assemble functions, or a config the assembler rejects)\n// surface as a rejected promise rather than a synchronous throw mid-cache-flow.\nconst buildNativePipelinePackage = async ({\n binding,\n config,\n gazetteerEntries,\n compressed,\n}: Required<\n Omit<NativePipelinePackageOptions, \"context\">\n>): Promise<Uint8Array> =>\n assemblePackageBytes(\n binding,\n toAssembleInputs(config, gazetteerEntries),\n compressed,\n );\n\ntype NativePackageCacheKeyOptions = {\n binding: NativeAnonymizeBinding;\n config: PipelineConfig;\n gazetteerEntries: readonly GazetteerEntry[];\n compressed: boolean;\n};\n\nconst nativePackageCacheKey = ({\n binding,\n config,\n gazetteerEntries,\n compressed,\n}: NativePackageCacheKeyOptions): string =>\n [\n binding.nativePackageVersion(),\n compressed ? \"compressed\" : \"raw\",\n dictionaryCacheKey(config.dictionaries),\n pipelineConfigKey(config, gazetteerEntries),\n ].join(\":\");\n","/* @stll/anonymize-wasm — browser / WebAssembly entry.\n *\n * Exposes the same native-SDK surface as `@stll/anonymize/native` (the\n * runtime-agnostic layer in `native.ts`), backed by the napi-rs\n * wasm32-wasip1-threads binding instead of the `.node` sidecars. The old\n * TS-pipeline surface (`runPipeline` and friends) is intentionally gone here:\n * this package now redacts entirely through the wasm binding and PREBUILT\n * prepared packages.\n *\n * Browsers can either load prepared packages (pass package bytes, an\n * `ArrayBuffer`, or a URL to fetch, or call `loadDefaultPipeline()` for the\n * default package bundled in the tarball) or build a config in-browser: the\n * wasm binding exposes the same static-search config assembly the Node\n * binding does, so `prepareNativePipelineConfig` / `createNativePipelineFromConfig`\n * / `prepareNativePipelinePackage` work here too.\n *\n * No module-level side effects: the wasm binding is instantiated lazily on\n * first use via `getBinding()`. The napi-generated glue is loaded from the\n * package's own `native/` asset directory — `index.wasi.cjs` under Node's WASI\n * runtime, `index.wasi-browser.js` (fetch + Worker) in browsers.\n */\n\nimport {\n createNativeAnonymizerFromPackage,\n createNativePipelineFromPackage,\n diagnostics_json as diagnosticsJsonWithBinding,\n diagnostics_stream_json as diagnosticsStreamJsonWithBinding,\n type NativeAnonymizeBinding,\n type NativeDiagnosticsBatchCallback,\n type NativeOperatorConfig,\n type NativeResultEventCallback,\n type NativeSearchPackageInput,\n type NativeStaticRedactionResult,\n native_package_version as nativePackageVersionWithBinding,\n normalize_for_search as normalizeForSearchWithBinding,\n PreparedNativeAnonymizer,\n PreparedNativePipeline,\n prepare_search_package as prepareSearchPackageWithBinding,\n redact_text as redactTextWithBinding,\n redact_text_json as redactTextJsonWithBinding,\n redact_text_stream_json as redactTextStreamJsonWithBinding,\n summary_diagnostics_json as summaryDiagnosticsJsonWithBinding,\n} from \"./native\";\n\nexport * from \"./native\";\nexport { deanonymise, exportRedactionKey } from \"./redact\";\nexport {\n DEFAULT_ENTITY_LABELS,\n DETECTION_SOURCES,\n DETECTOR_PRIORITY,\n OPERATOR_TYPES,\n} from \"./types\";\nexport type {\n AnonymisationOperator,\n DetectionSource,\n Dictionaries,\n Entity,\n GazetteerEntry,\n OperatorConfig,\n OperatorType,\n PipelineConfig,\n RedactionResult,\n ReviewDecision,\n ReviewedEntity,\n} from \"./types\";\n// Config-driven pipeline surface: pure TS that delegates to\n// `binding.assembleStaticSearchConfigJson` / `assembleStaticSearchPackageBytes`,\n// which the wasm binding exposes with no cfg gating (crates/anonymize-napi/src/lib.rs),\n// so browser callers can assemble packages from a `PipelineConfig` (e.g. live\n// gazetteer entries and dictionaries) instead of only loading prebuilt packages.\nexport {\n assertNativePipelineSupported,\n createNativePipelineFromConfig,\n getNativePipelineCompatibility,\n prepareNativePipelineConfig,\n prepareNativePipelinePackage,\n} from \"./native-pipeline\";\nexport type {\n NativePipelineBuildOptions,\n NativePipelineCompatibility,\n NativePipelinePackageOptions,\n NativePipelineUnsupportedFeature,\n} from \"./native-pipeline\";\nexport { createPipelineContext } from \"./context\";\nexport type { PipelineContext } from \"./context\";\n\n/** A prepared package the caller supplies: raw bytes, an ArrayBuffer, or a URL\n * (string or `URL`) that resolves to the package and is fetched. */\nexport type PreparedPackageSource = Uint8Array | ArrayBuffer | URL | string;\n\n/** Escape hatch for callers that already hold a binding (e.g. a custom sidecar\n * or a test double). When omitted, the lazily-instantiated wasm binding is\n * used. */\nexport type WasmBindingOptions = {\n binding?: NativeAnonymizeBinding;\n};\n\nconst NODE_GLUE_MODULE = \"index.wasi.cjs\";\nconst BROWSER_GLUE_MODULE = \"index.wasi-browser.js\";\nconst NODE_FS_MODULE = \"node:fs/promises\";\nconst NATIVE_ASSET_DIR = \"native\";\nconst DEFAULT_PACKAGE_FILE = \"native-pipeline.stlanonpkg\";\nconst LANGUAGE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\n\nlet bindingPromise: Promise<NativeAnonymizeBinding> | undefined;\nconst defaultPipelineCache = new Map<string, Promise<PreparedNativePipeline>>();\n\n/** Instantiate (once) and return the wasm binding. Safe to call repeatedly:\n * the underlying wasm module is instantiated a single time and cached. */\nexport const getBinding = (): Promise<NativeAnonymizeBinding> => {\n bindingPromise ??= loadWasmBinding();\n return bindingPromise;\n};\n\nconst loadWasmBinding = async (): Promise<NativeAnonymizeBinding> => {\n const glueModule = isNodeRuntime() ? NODE_GLUE_MODULE : BROWSER_GLUE_MODULE;\n const glueUrl = assetUrl(glueModule);\n // The specifier is deliberately a runtime asset URL (resolved against the\n // package's own `native/` directory), not a module the bundler should follow:\n // the napi-rs glue lives outside src and is copied in at build time.\n // eslint-disable-next-line stll/no-dynamic-import-specifier\n const loaded: unknown = await import(/* @vite-ignore */ glueUrl.href);\n return toNativeAnonymizeBinding(loaded);\n};\n\ntype RuntimeGlobals = {\n process?: { versions?: { node?: string } };\n window?: unknown;\n};\n\nconst isNodeRuntime = (): boolean => {\n const globals: RuntimeGlobals = globalThis;\n return (\n globals.window === undefined &&\n typeof globals.process?.versions?.node === \"string\"\n );\n};\n\nconst assetUrl = (fileName: string): URL =>\n new URL(`./${NATIVE_ASSET_DIR}/${fileName}`, import.meta.url);\n\nconst resolveBinding = (\n options?: WasmBindingOptions,\n): Promise<NativeAnonymizeBinding> =>\n options?.binding ? Promise.resolve(options.binding) : getBinding();\n\nconst toPackageBytes = async (\n source: PreparedPackageSource,\n): Promise<Uint8Array> => {\n if (source instanceof Uint8Array) {\n return source;\n }\n if (source instanceof ArrayBuffer) {\n return new Uint8Array(source);\n }\n const href = source instanceof URL ? source.href : source;\n // Node's global fetch (undici) rejects file: URLs, so package URLs resolved\n // from import.meta.url (loadDefaultPipeline, `new URL(..., import.meta.url)`)\n // fail there. Read those through node:fs instead of fetch.\n if (href.startsWith(\"file:\")) {\n return readFileUrlBytes(href);\n }\n const response = await fetch(href);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch prepared package (${response.status} ${response.statusText})`,\n );\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\n/** Read a `file:` URL through node:fs. The import is dynamic and gated behind\n * the `file:` check (never reached in browsers); the specifier is a runtime\n * value so the bundler leaves it alone, mirroring the runtime glue import in\n * {@link loadWasmBinding}, so browser bundles never pull in node:fs. */\nconst readFileUrlBytes = async (fileUrl: string): Promise<Uint8Array> => {\n // eslint-disable-next-line stll/no-dynamic-import-specifier\n const { readFile } = await import(/* @vite-ignore */ NODE_FS_MODULE);\n return new Uint8Array(await readFile(new URL(fileUrl)));\n};\n\n// --- Prepared-package loaders (the primary browser flow) ---------------------\n\nexport type LoadPreparedPackageOptions = WasmBindingOptions;\n\n/** Load a prepared package and return a pipeline ready to redact text. */\nexport const loadPipeline = async (\n source: PreparedPackageSource,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n const [binding, packageBytes] = await Promise.all([\n resolveBinding(options),\n toPackageBytes(source),\n ]);\n return createNativePipelineFromPackage({ binding, packageBytes });\n};\n\n/** Load a prepared package and return the lower-level anonymizer. */\nexport const load_prepared_package = async (\n source: PreparedPackageSource,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativeAnonymizer> => {\n const [binding, packageBytes] = await Promise.all([\n resolveBinding(options),\n toPackageBytes(source),\n ]);\n return createNativeAnonymizerFromPackage({ binding, packageBytes });\n};\n\n// --- Default package bundled in the tarball ----------------------------------\n\n/** URL of a bundled default prepared package, resolved against this module so\n * it points at the `native/` asset directory shipped in the tarball. */\nexport const defaultPackageUrl = (language?: string): URL =>\n language === undefined\n ? assetUrl(DEFAULT_PACKAGE_FILE)\n : assetUrl(`native-pipeline.${normalizeLanguage(language)}.stlanonpkg`);\n\n/** Load a fresh pipeline from the bundled default prepared package.\n *\n * Mirrors the node loader's regional-tag fallback: when an exact package for\n * a locale tag such as `en-US` is not shipped, the base-language package\n * (`en`) is loaded instead. The browser cannot check asset existence up\n * front, so the fallback triggers on a failed load of the exact package. */\nexport const loadDefaultPipeline = async (\n language?: string,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n try {\n return await loadPipeline(defaultPackageUrl(language), options);\n } catch (error) {\n const normalized =\n language === undefined ? undefined : normalizeLanguage(language);\n const baseLanguage = normalized?.split(\"-\").at(0);\n if (baseLanguage === undefined || baseLanguage === normalized) {\n throw error;\n }\n return loadPipeline(defaultPackageUrl(baseLanguage), options);\n }\n};\n\n/** Cached variant of {@link loadDefaultPipeline}: the default pipeline for a\n * given language is fetched and prepared once, then reused.\n *\n * Only the ambient-binding case is cached. The cache key is language-only, so a\n * caller that injects its own `options.binding` bypasses the cache entirely:\n * reusing a pipeline built against a different binding would be wrong, and\n * folding the binding into the key would keep unbounded per-binding entries\n * alive. Injected-binding callers get a fresh pipeline each call. */\nexport const getDefaultPipeline = (\n language?: string,\n options?: LoadPreparedPackageOptions,\n): Promise<PreparedNativePipeline> => {\n if (options?.binding) {\n return loadDefaultPipeline(language, options);\n }\n const key = language ?? \"<default>\";\n const cached = defaultPipelineCache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n // Evict the entry on rejection so a failed load (e.g. a transient fetch/read\n // error) is retried on the next call instead of caching the rejection.\n const pipeline = loadDefaultPipeline(language).catch((error: unknown) => {\n defaultPipelineCache.delete(key);\n throw error;\n });\n defaultPipelineCache.set(key, pipeline);\n return pipeline;\n};\n\nexport const redactDefaultText = async (\n fullText: string,\n operators?: NativeOperatorConfig,\n language?: string,\n): Promise<NativeStaticRedactionResult> =>\n (await getDefaultPipeline(language)).redactText(fullText, operators);\n\nexport const redactDefaultTextJson = async (\n fullText: string,\n operators?: NativeOperatorConfig,\n language?: string,\n): Promise<string> =>\n (await getDefaultPipeline(language)).redact_text_json(fullText, operators);\n\n// --- Binding-injected SDK surface (async parity with native-node) ------------\n\nexport const native_package_version = async (\n options?: WasmBindingOptions,\n): Promise<string> =>\n nativePackageVersionWithBinding(await resolveBinding(options));\n\nexport const normalize_for_search = async (\n text: string,\n options?: WasmBindingOptions,\n): Promise<string> =>\n normalizeForSearchWithBinding({\n binding: await resolveBinding(options),\n text,\n });\n\nexport type PrepareSearchPackageOptions = WasmBindingOptions & {\n compressed?: boolean;\n};\n\nexport const prepare_search_package = async (\n config: NativeSearchPackageInput,\n { compressed = false, ...options }: PrepareSearchPackageOptions = {},\n): Promise<Uint8Array> =>\n prepareSearchPackageWithBinding({\n binding: await resolveBinding(options),\n config,\n compressed,\n });\n\nexport const redact_text = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<NativeStaticRedactionResult> =>\n redactTextWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const redact_text_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string> =>\n redactTextJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const redact_text_stream_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n onEvent: NativeResultEventCallback,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n redactTextStreamJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n onEvent,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const diagnostics_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n diagnosticsJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const diagnostics_stream_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n onBatch: NativeDiagnosticsBatchCallback,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n diagnosticsStreamJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n onBatch,\n ...(operators !== undefined ? { operators } : {}),\n });\n\nexport const summary_diagnostics_json = async (\n config: NativeSearchPackageInput,\n fullText: string,\n operators?: NativeOperatorConfig,\n options?: WasmBindingOptions,\n): Promise<string | null> =>\n summaryDiagnosticsJsonWithBinding({\n binding: await resolveBinding(options),\n config,\n fullText,\n ...(operators !== undefined ? { operators } : {}),\n });\n\n// --- Binding extraction ------------------------------------------------------\n\nconst toNativeAnonymizeBinding = (loaded: unknown): NativeAnonymizeBinding => {\n const candidate = pickBindingCandidate(loaded);\n if (!isNativeAnonymizeBinding(candidate)) {\n throw new Error(\n \"wasm binding module does not expose the native anonymize surface\",\n );\n }\n return candidate;\n};\n\nconst pickBindingCandidate = (loaded: unknown): unknown => {\n if (isRecord(loaded) && isNativeAnonymizeBinding(loaded[\"default\"])) {\n return loaded[\"default\"];\n }\n return loaded;\n};\n\nconst isNativeAnonymizeBinding = (\n value: unknown,\n): value is NativeAnonymizeBinding => {\n if (!isRecord(value)) {\n return false;\n }\n if (typeof value[\"nativePackageVersion\"] !== \"function\") {\n return false;\n }\n if (typeof value[\"normalizeForSearch\"] !== \"function\") {\n return false;\n }\n if (typeof value[\"prepareStaticSearchPackageBytes\"] !== \"function\") {\n return false;\n }\n if (\n typeof value[\"prepareStaticSearchCompressedPackageBytes\"] !== \"function\"\n ) {\n return false;\n }\n const preparedSearch = value[\"NativePreparedSearch\"];\n if (!isRecord(preparedSearch)) {\n return false;\n }\n if (typeof preparedSearch[\"fromConfigJsonBytes\"] !== \"function\") {\n return false;\n }\n return typeof preparedSearch[\"fromPreparedPackageBytes\"] === \"function\";\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n\nconst normalizeLanguage = (language: string): string => {\n const normalized = language.trim().toLowerCase();\n if (!LANGUAGE_PATTERN.test(normalized)) {\n throw new Error(`Language must match ${LANGUAGE_PATTERN.source}`);\n }\n return normalized;\n};\n"],"mappings":";;AA+OA,IAAa,2BAAb,MAAsC;CACpC;CAEA,YAAY,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eAAe,gCAAgC;AAC/D;AAEA,MAAM,YAAY,UACf,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAEpE,MAAM,qBAAqB,aAA6B;CACtD,MAAM,aAAa,SAAS,KAAK,CAAC,CAAC,YAAY;CAC/C,IAAI,CAAC,iBAAiB,KAAK,UAAU,GACnC,MAAM,IAAI,MAAM,uBAAuB,iBAAiB,QAAQ;CAElE,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/anonymize-wasm",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "PII detection and anonymization for browsers via WebAssembly. Same native SDK API as @stll/anonymize.",
5
5
  "keywords": [
6
6
  "anonymization",