@trustchex/react-native-sdk 1.472.0 → 1.475.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/android/build.gradle +3 -3
  2. package/android/src/main/java/com/trustchex/reactnativesdk/camera/TrustchexCameraView.kt +147 -9
  3. package/ios/Camera/TrustchexCameraView.swift +92 -19
  4. package/lib/module/Screens/Debug/MRZTestScreen.js +121 -147
  5. package/lib/module/Screens/Static/ResultScreen.js +5 -0
  6. package/lib/module/Shared/Components/IdentityDocumentCamera.js +38 -4
  7. package/lib/module/Shared/Libs/MRZ_KNOWN_ISSUES.md +112 -0
  8. package/lib/module/Shared/Libs/mrz.utils.js +570 -16
  9. package/lib/module/Shared/Libs/mrzFrameAggregator.js +301 -0
  10. package/lib/module/Shared/Libs/mrzOcrIntegration.js +109 -0
  11. package/lib/module/version.js +1 -1
  12. package/lib/typescript/src/Screens/Debug/MRZTestScreen.d.ts.map +1 -1
  13. package/lib/typescript/src/Screens/Static/ResultScreen.d.ts.map +1 -1
  14. package/lib/typescript/src/Shared/Components/IdentityDocumentCamera.d.ts.map +1 -1
  15. package/lib/typescript/src/Shared/Libs/mrz.utils.d.ts +8 -0
  16. package/lib/typescript/src/Shared/Libs/mrz.utils.d.ts.map +1 -1
  17. package/lib/typescript/src/Shared/Libs/mrzFrameAggregator.d.ts +76 -0
  18. package/lib/typescript/src/Shared/Libs/mrzFrameAggregator.d.ts.map +1 -0
  19. package/lib/typescript/src/Shared/Libs/mrzOcrIntegration.d.ts +73 -0
  20. package/lib/typescript/src/Shared/Libs/mrzOcrIntegration.d.ts.map +1 -0
  21. package/lib/typescript/src/version.d.ts +1 -1
  22. package/package.json +14 -10
  23. package/src/Screens/Debug/MRZTestScreen.tsx +137 -166
  24. package/src/Screens/Static/ResultScreen.tsx +5 -0
  25. package/src/Shared/Components/IdentityDocumentCamera.tsx +46 -6
  26. package/src/Shared/Libs/MRZ_KNOWN_ISSUES.md +112 -0
  27. package/src/Shared/Libs/mrz.utils.ts +639 -11
  28. package/src/Shared/Libs/mrzFrameAggregator.ts +370 -0
  29. package/src/Shared/Libs/mrzOcrIntegration.ts +175 -0
  30. package/src/version.ts +1 -1
@@ -1,6 +1,19 @@
1
1
  import { parse } from 'mrz';
2
2
  import type { MRZFields } from '../Types/mrzFields';
3
3
 
4
+ // Inherent limitations & deliberate trade-offs (ICAO check-digit collisions,
5
+ // unprotected fields, conservative filler normalisation): see MRZ_KNOWN_ISSUES.md
6
+ // in this directory.
7
+
8
+ // Wall-clock budget for a single validateMRZ call's recovery search. Recovery on
9
+ // a garbage frame can otherwise exhaustively parse thousands of permutations and
10
+ // block the JS thread for ~1s, freezing the UI during continuous scanning. The
11
+ // search loops check this deadline and bail; a real misread is found in <5ms, so
12
+ // a modest budget never costs a genuine correction.
13
+ const RECOVERY_BUDGET_MS = 80;
14
+ let recoveryDeadline = 0;
15
+ const recoveryExpired = (): boolean => Date.now() > recoveryDeadline;
16
+
4
17
  /**
5
18
  * MRZ Format Types according to ICAO 9303
6
19
  */
@@ -13,6 +26,13 @@ export interface MRZValidationResult {
13
26
  valid: boolean;
14
27
  format: MRZFormat;
15
28
  fields?: MRZFields;
29
+ /**
30
+ * The corrected MRZ as newline-joined fixed-width lines, when a valid result
31
+ * was produced. This reflects the FULLY recovered MRZ — check-digit-driven
32
+ * field repair, composite recomputation and noisy-frame reconstruction all
33
+ * applied — not the lightweight `fixMRZ` pre-clean. Display this to the user.
34
+ */
35
+ correctedMrz?: string;
16
36
  error?: string;
17
37
  }
18
38
 
@@ -78,6 +98,31 @@ const fixMRZ = (rawText: string): string => {
78
98
  // e.g., "<<K<<" → "<<<<<" (clearly a filler position)
79
99
  cleanedText = cleanedText.replace(/(<+)K(<+)/g, '$1<$2');
80
100
 
101
+ // Pattern 3b: "K" is the dominant OCR misread of the "<" filler glyph in OCR-B.
102
+ // Normalise "K" → "<" ONLY in the trailing filler region (the run after the
103
+ // last real data), which is unambiguously padding. A mid-line "K" is left
104
+ // intact: a single "<" also separates given names (e.g. "KAYA<KEMAL"), so a
105
+ // lone "K" beside fillers cannot be safely distinguished from a real name
106
+ // letter — a surname like "AKTAS" must keep its "K".
107
+ cleanedText = cleanedText
108
+ .split('\n')
109
+ .map((line) => {
110
+ if (!line.includes('<')) return line;
111
+ // Collapse a trailing run of fillers + K to "<" (e.g. "…TEST<KK"→"…TEST<<<").
112
+ let out = line.replace(/(?<=<)[<K]+$/g, (m) => '<'.repeat(m.length));
113
+ // Document-code filler: a TD1 line-1 starts with the doc code, a "<", a
114
+ // short issuing state, and then the DOCUMENT NUMBER (a long alphanumeric
115
+ // run). When the filler after the code is misread as "K" ("IKD<<SPEC1234…"
116
+ // for "I<D<<SPEC1234…"), fix it — but ONLY when that long doc-number run is
117
+ // present, so a short NAME line that merely starts with a doc-code letter
118
+ // (e.g. "AKTAS<<MEHMET" or "AK<<MERT") never matches and keeps its real "K".
119
+ if (/^[ACIPV]K[A-Z0-9<]{0,2}<[A-Z0-9]{6,}/.test(out)) {
120
+ out = out.replace(/^([ACIPV])K/, '$1<');
121
+ }
122
+ return out;
123
+ })
124
+ .join('\n');
125
+
81
126
  // Pattern 4: Fix trailing filler area corruption at line end
82
127
  // e.g., "TUR<<<<<KK" → "TUR<<<<<<<" (only at end after clear filler sequence)
83
128
  cleanedText = cleanedText.replace(/(<{5,})[KGB]+$/gm, (match, fillers) => {
@@ -177,6 +222,149 @@ const fixMRZ = (rawText: string): string => {
177
222
  return fixedMRZ;
178
223
  };
179
224
 
225
+ /**
226
+ * Reconstructs fixed-width MRZ line-sets from a noisy multi-block OCR frame
227
+ * where the band may be split across extra newlines, mixed with front-of-card
228
+ * text, broken by internal spaces, or missing its trailing fillers.
229
+ *
230
+ * Supports all ICAO 9303 machine-readable formats:
231
+ * - TD1: 3 lines × 30 (national ID cards)
232
+ * - TD2: 2 lines × 36
233
+ * - TD3: 2 lines × 44 (passports)
234
+ *
235
+ * It returns an array of CANDIDATE line-sets (most-likely first). Each
236
+ * candidate is just a structural guess — the caller MUST validate every
237
+ * candidate with the `mrz` parser + check-digit recovery and keep only one
238
+ * that passes its check digits. A wrong reconstruction therefore never leaks
239
+ * through; it simply fails validation and is discarded.
240
+ */
241
+ const reconstructMRZCandidates = (rawText: string): string[][] => {
242
+ if (!rawText) return [];
243
+ const upper = applyOCRBCorrections(rawText.toUpperCase());
244
+
245
+ // Per-OCR-line strip to MRZ-legal chars (drops spaces, punctuation, « …).
246
+ // The "<" filler glyph in OCR-B is frequently misread as a letter — most often
247
+ // "K", but under glare also "C", "E" and "G". Normalise those letters to "<"
248
+ // ONLY in an UNAMBIGUOUS filler context, never where the letter could be part
249
+ // of a real name. The safe contexts are runs (the trailing/internal filler
250
+ // region) or a single filler-letter flanked by 2+ real fillers — NOT a lone
251
+ // letter next to a single "<", because a single "<" also separates given names
252
+ // (e.g. "KAYA<KEMAL"), so the "K" of "KEMAL" must be left intact. The
253
+ // check-digit recovery downstream still vets the result.
254
+ // Only normalise filler-letters in the TRAILING filler region — the run of
255
+ // characters after the last real data, which is unambiguously "<" padding. A
256
+ // mid-line filler-letter cannot be distinguished from a real name letter
257
+ // (names follow the "<<" separator and may start with K/C/E/G, e.g.
258
+ // "KAYA<<KEMAL"), so we never touch those — leaving them avoids corrupting
259
+ // names, and the trailing region is where the K↔< glare misread actually shows.
260
+ const FILLER_LETTERS = 'KCEG';
261
+ const fillerClass = `[${FILLER_LETTERS}]`;
262
+ const normaliseFillers = (l: string): string =>
263
+ // A tail of fillers and filler-letters (with at least one real "<" present)
264
+ // is the padding region — collapse the whole tail to "<".
265
+ l.replace(new RegExp(`(?<=<)(?:<|${fillerClass}){1,}$`), (m) =>
266
+ '<'.repeat(m.length)
267
+ );
268
+
269
+ const ocrLines = upper
270
+ .split('\n')
271
+ .map((l) => normaliseFillers(l.replace(/[^A-Z0-9<]/g, '')))
272
+ .filter((l) => l.length > 0);
273
+ const flat = ocrLines.join('');
274
+
275
+ const pad = (s: string, len: number): string =>
276
+ s.length >= len ? s.slice(0, len) : s.padEnd(len, '<');
277
+
278
+ // Restore the filler right after the document code. In TD1/TD2/TD3 the second
279
+ // character of line 1 is always "<". OCR commonly reads it as "K" or drops it:
280
+ // "IKD…" -> "I<D…", "ITUR…" -> "I<TUR…", "I<D…" unchanged.
281
+ const fixDocStart = (s: string): string =>
282
+ s.replace(/^([ACIPV])([A-Z0-9<])/, (_m, code, next) =>
283
+ next === '<' ? code + next : code + '<' + (next === 'K' ? '' : next)
284
+ );
285
+
286
+ const candidates: string[][] = [];
287
+
288
+ // Helper: the OCR line that actually starts the MRZ (doc code + state pattern),
289
+ // so title/front-of-card text mixed into the blob can't create a false anchor.
290
+ const docLine = ocrLines.find((l) => /^[ACIPV][A-Z0-9<]{3,}<</.test(l));
291
+
292
+ // ---- TD3 (passport): line1 "P<XXX…", line2 starts with a 9-char doc number ----
293
+ // Line 2 signature: docNumber(9) + check + nationality(3) + birth(6)+check+sex+expiry(6)+check…
294
+ {
295
+ const l1m = flat.match(/P[<A-Z]TUR[A-Z<]{2,}|P<[A-Z]{3}[A-Z<]+/);
296
+ const l2m = flat.match(
297
+ /[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/
298
+ );
299
+ if (l1m && l2m) {
300
+ candidates.push([pad(fixDocStart(l1m[0]), 44), pad(l2m[0], 44)]);
301
+ }
302
+ }
303
+
304
+ // ---- TD2: line1 "X<XXX…", line2 starts with docNumber ----
305
+ {
306
+ const l1m = flat.match(/[ACIPV]<[A-Z]{3}[A-Z<]+/);
307
+ const l2m = flat.match(
308
+ /[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/
309
+ );
310
+ if (l1m && l2m) {
311
+ candidates.push([pad(fixDocStart(l1m[0]), 36), pad(l2m[0], 36)]);
312
+ }
313
+ }
314
+
315
+ // ---- TD1 (national ID): 3 independent 30-char records ----
316
+ {
317
+ // Prefer the dedicated MRZ line (avoids title/front text in the blob); fall
318
+ // back to a blob match if OCR merged the line with adjacent content.
319
+ const l1Source =
320
+ docLine ??
321
+ flat.match(/[ACIPV][A-Z0-9<]{4}[A-Z0-9<]{9}[0-9<][A-Z0-9<]*/)?.[0];
322
+ // Line 2: the OCR line (or blob slice) that looks like the date record:
323
+ // birth(6)+check+sex+expiry(6)+check+state(3). Allow letters in date spans
324
+ // for OCR slips; check-digit recovery resolves them.
325
+ const l2Line = ocrLines.find((l) =>
326
+ /^[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z<]{2,}/.test(l)
327
+ );
328
+ const l2m =
329
+ l2Line ??
330
+ flat.match(/[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z]{2,3}/)?.[0];
331
+
332
+ if (l1Source) {
333
+ let l1 = pad(fixDocStart(l1Source), 30);
334
+ // The issuing-state field (TD1 line 1, positions 2–5) is structurally
335
+ // fillers/letters only — never a personal name — so a "K" there flanked by
336
+ // a filler is an unambiguous "<" misread and safe to normalise. This is
337
+ // position-scoped so it can NEVER touch the name field (positions 5+).
338
+ l1 =
339
+ l1.slice(0, 2) +
340
+ l1.slice(2, 5).replace(/K(?=<)|(?<=<)K|(?<=[A-Z])K$/g, '<') +
341
+ l1.slice(5);
342
+ let l2: string;
343
+ if (l2m) {
344
+ // Use the matched date record, padded to 30.
345
+ l2 = pad(l2m, 30);
346
+ } else {
347
+ const after = flat.indexOf(l1Source) + l1Source.length;
348
+ l2 = pad(flat.slice(after, after + 30), 30);
349
+ }
350
+ // Line 3 (name): the longest letter+filler OCR line that is NOT the doc or
351
+ // date line — exclude obvious front-of-card title words by requiring fillers.
352
+ const nameRuns = ocrLines.filter(
353
+ (l) =>
354
+ l !== l1Source &&
355
+ l !== l2Line &&
356
+ /^[A-Z<]+$/.test(l) &&
357
+ /</.test(l) &&
358
+ l.length >= 5
359
+ );
360
+ const l3 = pad(nameRuns.sort((a, b) => b.length - a.length)[0] ?? '', 30);
361
+ candidates.push([l1, l2, l3]);
362
+ }
363
+ }
364
+
365
+ return candidates;
366
+ };
367
+
180
368
  const AMBIGUOUS_CHAR_MAP: Record<string, string[]> = {
181
369
  '0': ['O', 'Q', 'D'],
182
370
  'O': ['0', 'Q', 'D'],
@@ -206,14 +394,24 @@ const AMBIGUOUS_CHAR_MAP: Record<string, string[]> = {
206
394
  */
207
395
  const OCRB_SPECIFIC_MAP: Record<string, string> = {
208
396
  // Glyph confusion in OCR-B (low contrast scanning)
209
- Ø: '0', // Slashed zero sometimes appears as capital O with slash
210
- ø: '0', // Lowercase variant
211
- œ: 'O', // Ligature
397
+ 'Ø': '0', // Slashed zero sometimes appears as capital O with slash
398
+ 'ø': '0', // Lowercase variant
399
+ 'œ': 'O', // Ligature
400
+
401
+ // The "<" filler chevron is frequently OCR'd as a guillemet/angle-quote glyph,
402
+ // especially in the trailing filler run. Map these to "<" so they KEEP their
403
+ // position (rather than being stripped, which would shift the line).
404
+ '«': '<',
405
+ '»': '<',
406
+ '‹': '<',
407
+ '›': '<',
408
+ '《': '<',
409
+ '》': '<',
212
410
 
213
411
  // Common in monospace OCR
214
- Ι: 'I', // Greek capital iota confused with I
215
- ι: 'i', // Greek lowercase iota
216
- l: 'I', // Lowercase L as I (common with serif OCR-B variants)
412
+ 'Ι': 'I', // Greek capital iota confused with I
413
+ 'ι': 'i', // Greek lowercase iota
414
+ 'l': 'I', // Lowercase L as I (common with serif OCR-B variants)
217
415
  };
218
416
 
219
417
  /**
@@ -342,6 +540,370 @@ const generateAmbiguousVariants = (
342
540
  return entries.map((e) => e.text);
343
541
  };
344
542
 
543
+ /**
544
+ * Maps a failing check-digit field (as reported by the `mrz` package) to the
545
+ * [line, start, endExclusive] span of the DATA it protects, per the ICAO 9303
546
+ * fixed layout for each format. Spans are 0-based, relative to fixed-width lines.
547
+ */
548
+ const CHECK_DIGIT_FIELD_DATA_SPANS: Record<
549
+ string,
550
+ Record<string, [number, number, number]>
551
+ > = {
552
+ // TD1: line0 docNumber[5..14]; line1 birth[0..6], expiry[8..14]
553
+ TD1: {
554
+ documentNumberCheckDigit: [0, 5, 14],
555
+ birthDateCheckDigit: [1, 0, 6],
556
+ expirationDateCheckDigit: [1, 8, 14],
557
+ },
558
+ // TD2: line1 docNumber[0..9], birth[13..19], expiry[21..27]
559
+ TD2: {
560
+ documentNumberCheckDigit: [1, 0, 9],
561
+ birthDateCheckDigit: [1, 13, 19],
562
+ expirationDateCheckDigit: [1, 21, 27],
563
+ },
564
+ // TD3 (passport): line1 docNumber[0..9], birth[13..19], expiry[21..27]
565
+ TD3: {
566
+ documentNumberCheckDigit: [1, 0, 9],
567
+ birthDateCheckDigit: [1, 13, 19],
568
+ expirationDateCheckDigit: [1, 21, 27],
569
+ },
570
+ };
571
+
572
+ /**
573
+ * Exhaustively tries every ambiguous-character permutation (0↔O, 5↔S, A↔4, …)
574
+ * WITHIN the data spans of the check-digit fields that are currently failing,
575
+ * re-parsing after each candidate, until the FULL MRZ validates (all check
576
+ * digits, including the composite).
577
+ *
578
+ * Because the search is scoped to the small failing fields, it is genuinely
579
+ * exhaustive — every permutation is tried — without the combinatorial blow-up of
580
+ * permuting the entire MRZ. This is what allows a misread document number
581
+ * (e.g. O→0, A→4, S→5) to be corrected before any downstream screen.
582
+ *
583
+ * @returns the parse result if a fully-valid MRZ is found, otherwise null.
584
+ */
585
+ /** ICAO 9303 7-3-1 weighted check digit. */
586
+ const icaoCheckDigit = (str: string): string => {
587
+ const weights = [7, 3, 1];
588
+ let sum = 0;
589
+ for (let i = 0; i < str.length; i++) {
590
+ const c = str[i];
591
+ const v =
592
+ c === '<'
593
+ ? 0
594
+ : c >= '0' && c <= '9'
595
+ ? c.charCodeAt(0) - 48
596
+ : c.charCodeAt(0) - 55;
597
+ sum = (sum + weights[i % 3] * v) % 10;
598
+ }
599
+ return String(sum);
600
+ };
601
+
602
+ /**
603
+ * When a TD1 MRZ fails ONLY on its composite check digit (every per-field check
604
+ * digit is valid), the composite is deterministically derivable from the other
605
+ * fields — OCR often just drops the trailing digit. Recompute and set it.
606
+ * Returns the corrected parse result, or null if not applicable.
607
+ */
608
+ const fixTD1Composite = (lines: string[]): ReturnType<typeof parse> | null => {
609
+ if (lines.length < 3 || lines[0].length !== 30 || lines[1].length !== 30) {
610
+ return null;
611
+ }
612
+ const r = parse(lines);
613
+ const bad = (r.details ?? []).filter((d) => !d.valid);
614
+ if (bad.length !== 1 || bad[0].field !== 'compositeCheckDigit') return null;
615
+
616
+ // TD1 composite covers: line1[5..30) + line2[0..7) + line2[8..15) + line2[18..29)
617
+ const l1 = lines[0];
618
+ const l2 = lines[1];
619
+ const composite =
620
+ l1.slice(5, 30) + l2.slice(0, 7) + l2.slice(8, 15) + l2.slice(18, 29);
621
+ const fixedL2 = l2.slice(0, 29) + icaoCheckDigit(composite);
622
+ const fixed = parse([l1, fixedL2, lines[2]]);
623
+ return fixed.valid ? fixed : null;
624
+ };
625
+
626
+ /**
627
+ * Recovers a TD1 MRZ when OCR INSERTED or DROPPED a character inside a numeric
628
+ * field — a real failure mode on glossy cards (e.g. expiry "360118"+check"7"
629
+ * read as "36011187", which shifts the nationality and overflows the line).
630
+ *
631
+ * Pure character substitution can't fix a length/alignment error, so this tries
632
+ * single-character edits in the relevant region and re-validates by check digit:
633
+ * - line 2 (date record): delete each char in the birth..expiry-check window
634
+ * [0..15) (then right-pad to 30) — undoes a spurious inserted digit;
635
+ * - line 1 (doc record): delete each char in the doc-number..check window
636
+ * [5..15) — undoes an inserted char in the serial.
637
+ * Each candidate is re-padded to 30, the composite is recomputed, and only a
638
+ * fully check-digit-valid parse is accepted, so a wrong edit can never pass.
639
+ */
640
+ const recoverTD1ByIndel = (
641
+ lines: string[]
642
+ ): ReturnType<typeof parse> | null => {
643
+ if (lines.length < 3) return null;
644
+ const pad30 = (s: string) =>
645
+ s.length >= 30 ? s.slice(0, 30) : s.padEnd(30, '<');
646
+
647
+ // Which line/window to try edits in, based on which check digit is failing.
648
+ let base: ReturnType<typeof parse>;
649
+ try {
650
+ base = parse(lines.map(pad30));
651
+ } catch {
652
+ return null;
653
+ }
654
+ if (base.format !== 'TD1') return null;
655
+ const failing = new Set(
656
+ (base.details ?? []).filter((d) => !d.valid).map((d) => d.field)
657
+ );
658
+
659
+ // (lineIndex, editStart, editEndExclusive) regions to attempt deletions in,
660
+ // chosen by the failing check digit. Order: date line first (most common).
661
+ const regions: Array<[number, number, number]> = [];
662
+ if (
663
+ failing.has('expirationDateCheckDigit') ||
664
+ failing.has('birthDateCheckDigit') ||
665
+ failing.has('compositeCheckDigit')
666
+ ) {
667
+ regions.push([1, 0, 15]); // birth..expiry-check on the date record
668
+ }
669
+ if (
670
+ failing.has('documentNumberCheckDigit') ||
671
+ failing.has('compositeCheckDigit')
672
+ ) {
673
+ regions.push([0, 5, 15]); // doc-number..its check on the doc record
674
+ }
675
+ if (regions.length === 0) return null;
676
+
677
+ // Build all single-deletion candidates up front.
678
+ const candidates: string[][] = [];
679
+ for (const [li, from, to] of regions) {
680
+ const original = pad30(lines[li] ?? '');
681
+ for (let i = from; i < to && i < original.length; i++) {
682
+ const edited = pad30(original.slice(0, i) + original.slice(i + 1));
683
+ const candidate = lines.map(pad30);
684
+ candidate[li] = edited;
685
+ candidates.push(candidate);
686
+ }
687
+ }
688
+
689
+ // Cheap pass first: a plain parse or a composite recompute resolves the common
690
+ // case (a dropped/duplicated digit) in microseconds — try ALL deletions this
691
+ // way before paying for any substitution search.
692
+ for (const candidate of candidates) {
693
+ let r: ReturnType<typeof parse>;
694
+ try {
695
+ r = parse(candidate);
696
+ } catch {
697
+ continue;
698
+ }
699
+ if (r.valid) return r;
700
+ const composite = fixTD1Composite(candidate);
701
+ if (composite?.valid) return composite;
702
+ }
703
+
704
+ // Expensive pass only if the cheap pass found nothing: a deletion may align the
705
+ // structure but leave a residual ambiguous char (e.g. B→8 in the TC number).
706
+ for (const candidate of candidates) {
707
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
708
+ const subbed = recoverByFailingFields(candidate, false);
709
+ if (subbed?.valid) return subbed;
710
+ }
711
+ return null;
712
+ };
713
+
714
+ const recoverByFailingFields = (
715
+ lines: string[],
716
+ tryIndel: boolean = true
717
+ ): ReturnType<typeof parse> | null => {
718
+ // `parse` THROWS (not returns invalid) on a wrong line count; a caller passing a
719
+ // noisy/fragmented line set must get null, not an exception that aborts the flow.
720
+ let first: ReturnType<typeof parse>;
721
+ try {
722
+ first = parse(lines);
723
+ } catch {
724
+ return null;
725
+ }
726
+ if (first.valid) return first;
727
+
728
+ // If only the composite check digit is off (common when OCR drops the trailing
729
+ // digit), recompute it deterministically before the search.
730
+ const compositeFixed = fixTD1Composite(lines);
731
+ if (compositeFixed) return compositeFixed;
732
+
733
+ const spans = CHECK_DIGIT_FIELD_DATA_SPANS[first.format ?? ''];
734
+ if (!spans) return null;
735
+
736
+ const isDigit = (c: string) => c >= '0' && c <= '9';
737
+
738
+ // A "change cost" for replacing `orig` with `repl` at a position that, per the
739
+ // MRZ field layout, is expected to hold a digit (`expectDigit`). Lower = more
740
+ // likely. The dominant real-world OCR error is letter↔digit confusion in
741
+ // numeric fields (O→0, S→5, A→4, B→8, I→1), so:
742
+ // - turning a misread letter into the expected digit is cheap (0)
743
+ // - keeping/introducing a non-digit where a digit is expected is expensive
744
+ const changeCost = (
745
+ orig: string,
746
+ repl: string,
747
+ expectDigit: boolean
748
+ ): number => {
749
+ if (repl === orig) return 0; // no change always cheapest
750
+ const origDigit = isDigit(orig);
751
+ const replDigit = isDigit(repl);
752
+ // OCR overwhelmingly confuses a LETTER for a digit in numeric MRZ fields
753
+ // (O→0, S→5, A→4, B→8, I→1), rarely the reverse. So:
754
+ // - letter → digit : very cheap (the common real correction) => 1
755
+ // - letter → letter : plausible only in alpha positions => 3
756
+ // - digit → letter : OCR almost never turns a real digit into a letter => 8
757
+ // - digit → digit : possible but unusual => 4
758
+ if (!origDigit && replDigit) return expectDigit ? 1 : 2;
759
+ if (!origDigit && !replDigit) return expectDigit ? 6 : 3;
760
+ if (origDigit && !replDigit) return 8;
761
+ return 4; // digit -> digit
762
+ };
763
+
764
+ // Per-format map of which data positions are expected to be digits. Document
765
+ // numbers can be alphanumeric, but Turkish-style IDs use letter-then-digits,
766
+ // and dates/personal numbers are always digits. We treat a position as
767
+ // "expectDigit" when its current best guess across candidates is numeric;
768
+ // dates are always numeric.
769
+ const expectsDigitAt = (field: string, indexWithinField: number): boolean => {
770
+ if (
771
+ field === 'birthDateCheckDigit' ||
772
+ field === 'expirationDateCheckDigit'
773
+ ) {
774
+ return true; // dates are all digits
775
+ }
776
+ if (field === 'documentNumberCheckDigit') {
777
+ // Common ID layout: position 0 is a letter, the rest digits.
778
+ return indexWithinField > 0;
779
+ }
780
+ return false;
781
+ };
782
+
783
+ const positions: Array<{
784
+ line: number;
785
+ index: number;
786
+ options: Array<{ ch: string; cost: number }>;
787
+ }> = [];
788
+ for (const d of first.details ?? []) {
789
+ if (d.valid || !spans[d.field]) continue;
790
+ const [ln, start, end] = spans[d.field];
791
+ const line = lines[ln];
792
+ if (line == null) continue;
793
+ for (let i = start; i < end; i++) {
794
+ const orig = line[i];
795
+ const alts = AMBIGUOUS_CHAR_MAP[orig];
796
+ if (alts && alts.length) {
797
+ const expectDigit = expectsDigitAt(d.field, i - start);
798
+ const options = [orig, ...alts]
799
+ .map((ch) => ({ ch, cost: changeCost(orig, ch, expectDigit) }))
800
+ .sort((a, b) => a.cost - b.cost);
801
+ positions.push({ line: ln, index: i, options });
802
+ }
803
+ }
804
+ }
805
+ if (positions.length === 0) return null;
806
+
807
+ const total = positions.reduce((acc, p) => acc * p.options.length, 1);
808
+ // The legitimate search space for a genuine OCR misread is small — a handful of
809
+ // ambiguous characters in the failing check-digit fields. A huge `total` means
810
+ // the frame is garbage (many ambiguous chars, no real MRZ); exhaustively
811
+ // parsing tens of thousands of permutations there would block the JS thread for
812
+ // ~1s per frame and freeze the UI. Cap hard so a noisy frame fails fast.
813
+ const MAX_PERMUTATIONS = 4096;
814
+ if (total > MAX_PERMUTATIONS) return null;
815
+
816
+ // Decode candidate index `n` into a per-position option choice, and compute its
817
+ // total change cost (sum of per-option costs). We then try candidates in
818
+ // ascending total cost so the most plausible OCR correction is accepted first.
819
+ const decode = (n: number): { indices: number[]; cost: number } => {
820
+ let k = n;
821
+ let cost = 0;
822
+ const indices = positions.map((p) => {
823
+ const idx = k % p.options.length;
824
+ k = Math.floor(k / p.options.length);
825
+ cost += p.options[idx].cost;
826
+ return idx;
827
+ });
828
+ return { indices, cost };
829
+ };
830
+
831
+ const order = Array.from({ length: total }, (_, n) => n);
832
+ const costCache = new Map<number, number>();
833
+ const costOf = (n: number): number => {
834
+ let c = costCache.get(n);
835
+ if (c === undefined) {
836
+ c = decode(n).cost;
837
+ costCache.set(n, c);
838
+ }
839
+ return c;
840
+ };
841
+ order.sort((a, b) => costOf(a) - costOf(b) || a - b);
842
+
843
+ for (const n of order) {
844
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
845
+ const { indices } = decode(n);
846
+ const chars: Record<number, string[]> = {};
847
+ for (const p of positions) {
848
+ if (!chars[p.line]) chars[p.line] = lines[p.line].split('');
849
+ }
850
+ positions.forEach((p, pi) => {
851
+ chars[p.line][p.index] = p.options[indices[pi]].ch;
852
+ });
853
+ const candidate = lines.slice();
854
+ for (const lnStr of Object.keys(chars)) {
855
+ candidate[Number(lnStr)] = chars[Number(lnStr)].join('');
856
+ }
857
+ const r = parse(candidate);
858
+ if (r.valid) return r;
859
+ }
860
+
861
+ // Substitution alone couldn't fix it. If OCR inserted/dropped a character
862
+ // (a length/alignment error), try single-char edits and re-validate.
863
+ if (tryIndel) {
864
+ const indel = recoverTD1ByIndel(lines);
865
+ if (indel?.valid) return indel;
866
+ }
867
+
868
+ return null;
869
+ };
870
+
871
+ /**
872
+ * Rebuild the corrected fixed-width MRZ lines from a (valid) parse result.
873
+ * Every field's `ranges` carry the actual post-correction characters at known
874
+ * line/column spans, so laying each `raw` span into a per-line buffer yields the
875
+ * exact MRZ that satisfied the check digits — the genuinely fixed version to show
876
+ * the user, not the lightweight `fixMRZ` pre-clean.
877
+ */
878
+ const correctedMrzFromParse = (
879
+ result: ReturnType<typeof parse>
880
+ ): string | undefined => {
881
+ const widths: Record<string, number> = { TD1: 30, TD2: 36, TD3: 44 };
882
+ const width = widths[result.format ?? ''];
883
+ if (!width) return undefined;
884
+ const lineCount = result.format === 'TD1' ? 3 : 2;
885
+ const buffers: string[][] = Array.from({ length: lineCount }, () =>
886
+ new Array(width).fill('<')
887
+ );
888
+ for (const detail of result.details ?? []) {
889
+ for (const range of detail.ranges ?? []) {
890
+ // `raw` (the actual characters at this span) exists at runtime but isn't in
891
+ // the `mrz` Range type.
892
+ const {
893
+ line,
894
+ start,
895
+ raw = '',
896
+ } = range as typeof range & { raw?: string };
897
+ const buf = buffers[line];
898
+ if (!buf) continue;
899
+ for (let i = 0; i < raw.length && start + i < width; i++) {
900
+ buf[start + i] = raw[i];
901
+ }
902
+ }
903
+ }
904
+ return buffers.map((b) => b.join('')).join('\n');
905
+ };
906
+
345
907
  /**
346
908
  * Validates MRZ text using the mrz npm package
347
909
  * @param mrzText Raw or cleaned MRZ text
@@ -353,17 +915,81 @@ const validateMRZ = (
353
915
  autocorrect: boolean = true
354
916
  ): MRZValidationResult => {
355
917
  try {
918
+ // Arm the recovery wall-clock budget for this call so the search below can't
919
+ // block the JS thread on a garbage frame.
920
+ recoveryDeadline = Date.now() + RECOVERY_BUDGET_MS;
356
921
  const fixedText = fixMRZ(mrzText);
357
- let result = parse(fixedText, { autocorrect });
922
+ // `parse` THROWS on a wrong MRZ-line count (e.g. a noisy frame with a title
923
+ // line + fragments). That must NOT short-circuit the recovery/reconstruction
924
+ // path below — treat a throw here as "no valid parse yet" and keep going.
925
+ let result: ReturnType<typeof parse> | null = null;
926
+ try {
927
+ result = parse(fixedText, { autocorrect });
928
+ } catch {
929
+ result = null;
930
+ }
931
+
932
+ // Primary recovery: exhaustive, CHECK-DIGIT-DRIVEN correction scoped to the
933
+ // fields whose check digit actually fails. It tries every OCR-ambiguous
934
+ // permutation within those fields — ordered by how likely the OCR error is
935
+ // (letter→digit in numeric fields is cheapest) — and only accepts a candidate
936
+ // when the WHOLE MRZ validates (document-number, date and composite check
937
+ // digits all pass). This both (a) fixes a misread document number before the
938
+ // caller advances to the NFC/next screen, and (b) prefers the genuinely
939
+ // correct correction over an arbitrary check-digit-satisfying one.
940
+ if (!result || !result.valid) {
941
+ const fixedLines = fixedText.split('\n').filter((l) => l.trim());
942
+ if (fixedLines.length >= 2) {
943
+ const recovered = recoverByFailingFields(fixedLines);
944
+ if (recovered && recovered.valid) {
945
+ result = recovered;
946
+ }
947
+ }
948
+ }
358
949
 
950
+ // Last-resort fallback: the older whole-string ambiguous sweep, only for
951
+ // inputs the field-scoped recovery can't address (e.g. an unrecognised
952
+ // format with no check-digit span map). Still requires a fully-valid parse.
359
953
  if (!result || !result.valid) {
360
954
  const variants = generateAmbiguousVariants(fixedText);
361
955
  for (const variant of variants) {
956
+ if (recoveryExpired()) break; // bail before blocking the JS thread
362
957
  if (variant === fixedText) continue;
363
- const candidate = parse(variant, { autocorrect });
364
- if (candidate && candidate.valid) {
365
- result = candidate;
366
- break;
958
+ try {
959
+ const candidate = parse(variant, { autocorrect });
960
+ if (candidate && candidate.valid) {
961
+ result = candidate;
962
+ break;
963
+ }
964
+ } catch {
965
+ // Malformed variant — try the next.
966
+ }
967
+ }
968
+ }
969
+
970
+ // Last resort: the standard line-splitter couldn't assemble a parseable MRZ
971
+ // (e.g. a noisy frame where OCR split the band, mixed in front-of-card text,
972
+ // or broke a field with spaces). Reconstruct fixed-width line-sets for every
973
+ // supported format (TD1/TD2/TD3) and validate each WITH CHECK DIGITS, keeping
974
+ // only one that passes — a wrong reconstruction can never leak through.
975
+ if (!result || !result.valid) {
976
+ for (const reLines of reconstructMRZCandidates(mrzText)) {
977
+ // A reconstructed candidate for the wrong format (e.g. a 2-line TD2 guess
978
+ // built from a TD1 frame) makes the `mrz` parser THROW on line count —
979
+ // that must not abort the loop before a good candidate is tried.
980
+ try {
981
+ const direct = parse(reLines);
982
+ if (direct && direct.valid) {
983
+ result = direct;
984
+ break;
985
+ }
986
+ const recovered = recoverByFailingFields(reLines);
987
+ if (recovered && recovered.valid) {
988
+ result = recovered;
989
+ break;
990
+ }
991
+ } catch {
992
+ // Skip this malformed candidate and try the next.
367
993
  }
368
994
  }
369
995
  }
@@ -407,6 +1033,7 @@ const validateMRZ = (
407
1033
  valid: true,
408
1034
  format,
409
1035
  fields,
1036
+ correctedMrz: correctedMrzFromParse(result),
410
1037
  };
411
1038
  } catch (error) {
412
1039
  return {
@@ -517,6 +1144,7 @@ export default {
517
1144
  fixMRZ,
518
1145
  validateMRZ,
519
1146
  validateMRZWithCorrections,
1147
+ reconstructMRZCandidates,
520
1148
  calculateMRZQualityScore,
521
1149
  assessMRZQuality,
522
1150
  isValidOCRBPattern,