@trustchex/react-native-sdk 1.472.0 → 1.475.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.
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 +639 -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 +15 -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 +704 -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,18 @@
1
1
  "use strict";
2
2
 
3
3
  import { parse } from 'mrz';
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 = () => Date.now() > recoveryDeadline;
4
16
 
5
17
  /**
6
18
  * MRZ Format Types according to ICAO 9303
@@ -78,6 +90,28 @@ const fixMRZ = rawText => {
78
90
  // e.g., "<<K<<" → "<<<<<" (clearly a filler position)
79
91
  cleanedText = cleanedText.replace(/(<+)K(<+)/g, '$1<$2');
80
92
 
93
+ // Pattern 3b: "K" is the dominant OCR misread of the "<" filler glyph in OCR-B.
94
+ // Normalise "K" → "<" ONLY in the trailing filler region (the run after the
95
+ // last real data), which is unambiguously padding. A mid-line "K" is left
96
+ // intact: a single "<" also separates given names (e.g. "KAYA<KEMAL"), so a
97
+ // lone "K" beside fillers cannot be safely distinguished from a real name
98
+ // letter — a surname like "AKTAS" must keep its "K".
99
+ cleanedText = cleanedText.split('\n').map(line => {
100
+ if (!line.includes('<')) return line;
101
+ // Collapse a trailing run of fillers + K to "<" (e.g. "…TEST<KK"→"…TEST<<<").
102
+ let out = line.replace(/(?<=<)[<K]+$/g, m => '<'.repeat(m.length));
103
+ // Document-code filler: a TD1 line-1 starts with the doc code, a "<", a
104
+ // short issuing state, and then the DOCUMENT NUMBER (a long alphanumeric
105
+ // run). When the filler after the code is misread as "K" ("IKD<<SPEC1234…"
106
+ // for "I<D<<SPEC1234…"), fix it — but ONLY when that long doc-number run is
107
+ // present, so a short NAME line that merely starts with a doc-code letter
108
+ // (e.g. "AKTAS<<MEHMET" or "AK<<MERT") never matches and keeps its real "K".
109
+ if (/^[ACIPV]K[A-Z0-9<]{0,2}<[A-Z0-9]{6,}/.test(out)) {
110
+ out = out.replace(/^([ACIPV])K/, '$1<');
111
+ }
112
+ return out;
113
+ }).join('\n');
114
+
81
115
  // Pattern 4: Fix trailing filler area corruption at line end
82
116
  // e.g., "TUR<<<<<KK" → "TUR<<<<<<<" (only at end after clear filler sequence)
83
117
  cleanedText = cleanedText.replace(/(<{5,})[KGB]+$/gm, (match, fillers) => {
@@ -163,6 +197,148 @@ const fixMRZ = rawText => {
163
197
  const fixedMRZ = mrzLines.join('\n');
164
198
  return fixedMRZ;
165
199
  };
200
+
201
+ /**
202
+ * Reconstructs fixed-width MRZ line-sets from a noisy multi-block OCR frame
203
+ * where the band may be split across extra newlines, mixed with front-of-card
204
+ * text, broken by internal spaces, or missing its trailing fillers.
205
+ *
206
+ * Supports all ICAO 9303 machine-readable formats:
207
+ * - TD1: 3 lines × 30 (national ID cards)
208
+ * - TD2: 2 lines × 36
209
+ * - TD3: 2 lines × 44 (passports)
210
+ *
211
+ * It returns an array of CANDIDATE line-sets (most-likely first). Each
212
+ * candidate is just a structural guess — the caller MUST validate every
213
+ * candidate with the `mrz` parser + check-digit recovery and keep only one
214
+ * that passes its check digits. A wrong reconstruction therefore never leaks
215
+ * through; it simply fails validation and is discarded.
216
+ */
217
+ const reconstructMRZCandidates = rawText => {
218
+ if (!rawText) return [];
219
+ const upper = applyOCRBCorrections(rawText.toUpperCase());
220
+
221
+ // Per-OCR-line strip to MRZ-legal chars (drops spaces, punctuation, « …).
222
+ // The "<" filler glyph in OCR-B is frequently misread as a letter — most often
223
+ // "K", but under glare also "C", "E" and "G". Normalise those letters to "<"
224
+ // ONLY in an UNAMBIGUOUS filler context, never where the letter could be part
225
+ // of a real name. The safe contexts are runs (the trailing/internal filler
226
+ // region) or a single filler-letter flanked by 2+ real fillers — NOT a lone
227
+ // letter next to a single "<", because a single "<" also separates given names
228
+ // (e.g. "KAYA<KEMAL"), so the "K" of "KEMAL" must be left intact. The
229
+ // check-digit recovery downstream still vets the result.
230
+ // Only normalise filler-letters in the TRAILING filler region — the run of
231
+ // characters after the last real data, which is unambiguously "<" padding. A
232
+ // mid-line filler-letter cannot be distinguished from a real name letter
233
+ // (names follow the "<<" separator and may start with K/C/E/G, e.g.
234
+ // "KAYA<<KEMAL"), so we never touch those — leaving them avoids corrupting
235
+ // names, and the trailing region is where the K↔< glare misread actually shows.
236
+ const FILLER_LETTERS = 'KCEG';
237
+ const fillerClass = `[${FILLER_LETTERS}]`;
238
+ const normaliseFillers = l =>
239
+ // A tail of fillers and filler-letters (with at least one real "<" present)
240
+ // is the padding region — collapse the whole tail to "<".
241
+ l.replace(new RegExp(`(?<=<)(?:<|${fillerClass}){1,}$`), m => '<'.repeat(m.length));
242
+ const ocrLines = upper.split('\n').map(l => normaliseFillers(l.replace(/[^A-Z0-9<]/g, ''))).filter(l => l.length > 0);
243
+ const flat = ocrLines.join('');
244
+ const pad = (s, len) => s.length >= len ? s.slice(0, len) : s.padEnd(len, '<');
245
+
246
+ // Restore the filler right after the document code. In TD1/TD2/TD3 the second
247
+ // character of line 1 is always "<". OCR commonly reads it as "K" or drops it:
248
+ // "IKD…" -> "I<D…", "ITUR…" -> "I<TUR…", "I<D…" unchanged.
249
+ const fixDocStart = s => s.replace(/^([ACIPV])([A-Z0-9<])/, (_m, code, next) => next === '<' ? code + next : code + '<' + (next === 'K' ? '' : next));
250
+ const candidates = [];
251
+
252
+ // Helper: the OCR line that actually starts the MRZ (doc code + state pattern),
253
+ // so title/front-of-card text mixed into the blob can't create a false anchor.
254
+ const docLine = ocrLines.find(l => /^[ACIPV][A-Z0-9<]{3,}<</.test(l));
255
+
256
+ // ---- TD3 (passport): line1 "P<XXX…", line2 starts with a 9-char doc number ----
257
+ // Line 2 signature: docNumber(9) + check + nationality(3) + birth(6)+check+sex+expiry(6)+check…
258
+ {
259
+ const l1m = flat.match(/P[<A-Z]TUR[A-Z<]{2,}|P<[A-Z]{3}[A-Z<]+/);
260
+ const l2m = flat.match(/[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/);
261
+ if (l1m && l2m) {
262
+ candidates.push([pad(fixDocStart(l1m[0]), 44), pad(l2m[0], 44)]);
263
+ }
264
+ }
265
+
266
+ // ---- TD2: line1 "X<XXX…", line2 starts with docNumber ----
267
+ {
268
+ const l1m = flat.match(/[ACIPV]<[A-Z]{3}[A-Z<]+/);
269
+ const l2m = flat.match(/[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/);
270
+ if (l1m && l2m) {
271
+ candidates.push([pad(fixDocStart(l1m[0]), 36), pad(l2m[0], 36)]);
272
+ }
273
+ }
274
+
275
+ // ---- TD1 (national ID): 3 independent 30-char records ----
276
+ {
277
+ // Prefer the dedicated MRZ line (avoids title/front text in the blob); fall
278
+ // back to a blob match if OCR merged the line with adjacent content.
279
+ const l1Source = docLine ?? flat.match(/[ACIPV][A-Z0-9<]{4}[A-Z0-9<]{9}[0-9<][A-Z0-9<]*/)?.[0];
280
+ // Line 2: the OCR line (or blob slice) that looks like the date record:
281
+ // birth(6)+check+sex+expiry(6)+check+state(3). Allow letters in date spans
282
+ // for OCR slips; check-digit recovery resolves them.
283
+ const l2Line = ocrLines.find(l => /^[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z<]{2,}/.test(l));
284
+ const l2m = l2Line ?? flat.match(/[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z]{2,3}/)?.[0];
285
+ if (l1Source) {
286
+ let l1 = pad(fixDocStart(l1Source), 30);
287
+ // The issuing-state field (TD1 line 1, positions 2–5) is structurally
288
+ // fillers/letters only — never a personal name — so a "K" there flanked by
289
+ // a filler is an unambiguous "<" misread and safe to normalise. This is
290
+ // position-scoped so it can NEVER touch the name field (positions 5+).
291
+ l1 = l1.slice(0, 2) + l1.slice(2, 5).replace(/K(?=<)|(?<=<)K|(?<=[A-Z])K$/g, '<') + l1.slice(5);
292
+ let l2;
293
+ if (l2m) {
294
+ // Use the matched date record, padded to 30.
295
+ l2 = pad(l2m, 30);
296
+ } else {
297
+ const after = flat.indexOf(l1Source) + l1Source.length;
298
+ l2 = pad(flat.slice(after, after + 30), 30);
299
+ }
300
+ // Line 3 (name): the longest mostly-letters+filler OCR line that is NOT the
301
+ // doc or date line. OCR mangles the name line too — a leading "O" reads as
302
+ // "0", and the trailing "<" fillers read as K/C — so we DON'T require a
303
+ // pure [A-Z<] line (that wrongly drops "0ZCAN<<ERDAL…" entirely). Accept a
304
+ // line that is predominantly letters/fillers, then normalise it.
305
+ const isNameLike = l => {
306
+ if (l === l1Source || l === l2Line || l.length < 5) return false;
307
+ if (!/</.test(l)) return false; // must have at least one filler
308
+ // Must look like "SURNAME<<NAMES…": starts with a letter (or its digit
309
+ // look-alike) and is dominated by letters/fillers, not a numeric record.
310
+ if (!/^[A-Z0-9]/.test(l)) return false;
311
+ const letters = (l.match(/[A-Z]/g) || []).length;
312
+ const digits = (l.match(/[0-9]/g) || []).length;
313
+ // A date/doc record is digit-heavy; a name is letter-heavy.
314
+ return letters >= 3 && letters >= digits;
315
+ };
316
+ // Normalise a name line: digit look-alikes back to letters (O/I/S/B/Z/G),
317
+ // and the filler-letter run misreads (K/C/E/G adjacent to fillers) to "<".
318
+ const normaliseName = l => {
319
+ const digitToLetter = {
320
+ '0': 'O',
321
+ '1': 'I',
322
+ '5': 'S',
323
+ '8': 'B',
324
+ '2': 'Z',
325
+ '6': 'G'
326
+ };
327
+ return l
328
+ // digit look-alikes inside the name → letters
329
+ .replace(/[015862]/g, d => digitToLetter[d] ?? d)
330
+ // a run of filler-letters (K/C/E/G) flanked by fillers or at the tail
331
+ // is the trailing/internal filler region
332
+ .replace(/(?<=<)[KCEG]+(?=<|$)/g, m => '<'.repeat(m.length)).replace(/[KCEG]+$/g, m => '<'.repeat(m.length));
333
+ };
334
+ const nameRuns = ocrLines.filter(isNameLike);
335
+ const bestName = nameRuns.sort((a, b) => b.length - a.length)[0] ?? '';
336
+ const l3 = pad(normaliseName(bestName), 30);
337
+ candidates.push([l1, l2, l3]);
338
+ }
339
+ }
340
+ return candidates;
341
+ };
166
342
  const AMBIGUOUS_CHAR_MAP = {
167
343
  '0': ['O', 'Q', 'D'],
168
344
  'O': ['0', 'Q', 'D'],
@@ -192,19 +368,28 @@ const AMBIGUOUS_CHAR_MAP = {
192
368
  */
193
369
  const OCRB_SPECIFIC_MAP = {
194
370
  // Glyph confusion in OCR-B (low contrast scanning)
195
- Ø: '0',
371
+ 'Ø': '0',
196
372
  // Slashed zero sometimes appears as capital O with slash
197
- ø: '0',
373
+ 'ø': '0',
198
374
  // Lowercase variant
199
- œ: 'O',
375
+ 'œ': 'O',
200
376
  // Ligature
201
377
 
378
+ // The "<" filler chevron is frequently OCR'd as a guillemet/angle-quote glyph,
379
+ // especially in the trailing filler run. Map these to "<" so they KEEP their
380
+ // position (rather than being stripped, which would shift the line).
381
+ '«': '<',
382
+ '»': '<',
383
+ '‹': '<',
384
+ '›': '<',
385
+ '《': '<',
386
+ '》': '<',
202
387
  // Common in monospace OCR
203
- Ι: 'I',
388
+ 'Ι': 'I',
204
389
  // Greek capital iota confused with I
205
- ι: 'i',
390
+ 'ι': 'i',
206
391
  // Greek lowercase iota
207
- l: 'I' // Lowercase L as I (common with serif OCR-B variants)
392
+ 'l': 'I' // Lowercase L as I (common with serif OCR-B variants)
208
393
  };
209
394
 
210
395
  /**
@@ -311,6 +496,356 @@ const generateAmbiguousVariants = (text, maxChanges = 2, maxVariants = 64) => {
311
496
  return entries.map(e => e.text);
312
497
  };
313
498
 
499
+ /**
500
+ * Maps a failing check-digit field (as reported by the `mrz` package) to the
501
+ * [line, start, endExclusive] span of the DATA it protects, per the ICAO 9303
502
+ * fixed layout for each format. Spans are 0-based, relative to fixed-width lines.
503
+ */
504
+ const CHECK_DIGIT_FIELD_DATA_SPANS = {
505
+ // TD1: line0 docNumber[5..14]; line1 birth[0..6], expiry[8..14]
506
+ TD1: {
507
+ documentNumberCheckDigit: [0, 5, 14],
508
+ birthDateCheckDigit: [1, 0, 6],
509
+ expirationDateCheckDigit: [1, 8, 14]
510
+ },
511
+ // TD2: line1 docNumber[0..9], birth[13..19], expiry[21..27]
512
+ TD2: {
513
+ documentNumberCheckDigit: [1, 0, 9],
514
+ birthDateCheckDigit: [1, 13, 19],
515
+ expirationDateCheckDigit: [1, 21, 27]
516
+ },
517
+ // TD3 (passport): line1 docNumber[0..9], birth[13..19], expiry[21..27]
518
+ TD3: {
519
+ documentNumberCheckDigit: [1, 0, 9],
520
+ birthDateCheckDigit: [1, 13, 19],
521
+ expirationDateCheckDigit: [1, 21, 27]
522
+ }
523
+ };
524
+
525
+ /**
526
+ * Exhaustively tries every ambiguous-character permutation (0↔O, 5↔S, A↔4, …)
527
+ * WITHIN the data spans of the check-digit fields that are currently failing,
528
+ * re-parsing after each candidate, until the FULL MRZ validates (all check
529
+ * digits, including the composite).
530
+ *
531
+ * Because the search is scoped to the small failing fields, it is genuinely
532
+ * exhaustive — every permutation is tried — without the combinatorial blow-up of
533
+ * permuting the entire MRZ. This is what allows a misread document number
534
+ * (e.g. O→0, A→4, S→5) to be corrected before any downstream screen.
535
+ *
536
+ * @returns the parse result if a fully-valid MRZ is found, otherwise null.
537
+ */
538
+ /** ICAO 9303 7-3-1 weighted check digit. */
539
+ const icaoCheckDigit = str => {
540
+ const weights = [7, 3, 1];
541
+ let sum = 0;
542
+ for (let i = 0; i < str.length; i++) {
543
+ const c = str[i];
544
+ const v = c === '<' ? 0 : c >= '0' && c <= '9' ? c.charCodeAt(0) - 48 : c.charCodeAt(0) - 55;
545
+ sum = (sum + weights[i % 3] * v) % 10;
546
+ }
547
+ return String(sum);
548
+ };
549
+
550
+ /**
551
+ * When a TD1 MRZ fails ONLY on its composite check digit (every per-field check
552
+ * digit is valid), the composite is deterministically derivable from the other
553
+ * fields — OCR often just drops the trailing digit. Recompute and set it.
554
+ * Returns the corrected parse result, or null if not applicable.
555
+ */
556
+ const fixTD1Composite = lines => {
557
+ if (lines.length < 3 || lines[0].length !== 30 || lines[1].length !== 30) {
558
+ return null;
559
+ }
560
+ const r = parse(lines);
561
+ const bad = (r.details ?? []).filter(d => !d.valid);
562
+ if (bad.length !== 1 || bad[0].field !== 'compositeCheckDigit') return null;
563
+
564
+ // TD1 composite covers: line1[5..30) + line2[0..7) + line2[8..15) + line2[18..29)
565
+ const l1 = lines[0];
566
+ const l2 = lines[1];
567
+ const composite = l1.slice(5, 30) + l2.slice(0, 7) + l2.slice(8, 15) + l2.slice(18, 29);
568
+ const fixedL2 = l2.slice(0, 29) + icaoCheckDigit(composite);
569
+ const fixed = parse([l1, fixedL2, lines[2]]);
570
+ return fixed.valid ? fixed : null;
571
+ };
572
+
573
+ /**
574
+ * Recovers a TD1 MRZ when OCR INSERTED or DROPPED a character inside a numeric
575
+ * field — a real failure mode on glossy cards (e.g. expiry "360118"+check"7"
576
+ * read as "36011187", which shifts the nationality and overflows the line).
577
+ *
578
+ * Pure character substitution can't fix a length/alignment error, so this tries
579
+ * single-character edits in the relevant region and re-validates by check digit:
580
+ * - line 2 (date record): delete each char in the birth..expiry-check window
581
+ * [0..15) (then right-pad to 30) — undoes a spurious inserted digit;
582
+ * - line 1 (doc record): delete each char in the doc-number..check window
583
+ * [5..15) — undoes an inserted char in the serial.
584
+ * Each candidate is re-padded to 30, the composite is recomputed, and only a
585
+ * fully check-digit-valid parse is accepted, so a wrong edit can never pass.
586
+ */
587
+ const recoverTD1ByIndel = lines => {
588
+ if (lines.length < 3) return null;
589
+ const pad30 = s => s.length >= 30 ? s.slice(0, 30) : s.padEnd(30, '<');
590
+
591
+ // Which line/window to try edits in, based on which check digit is failing.
592
+ let base;
593
+ try {
594
+ base = parse(lines.map(pad30));
595
+ } catch {
596
+ return null;
597
+ }
598
+ if (base.format !== 'TD1') return null;
599
+ const failing = new Set((base.details ?? []).filter(d => !d.valid).map(d => d.field));
600
+
601
+ // (lineIndex, editStart, editEndExclusive) regions to attempt deletions in,
602
+ // chosen by the failing check digit. Order: date line first (most common).
603
+ const regions = [];
604
+ if (failing.has('expirationDateCheckDigit') || failing.has('birthDateCheckDigit') || failing.has('compositeCheckDigit')) {
605
+ regions.push([1, 0, 15]); // birth..expiry-check on the date record
606
+ }
607
+ if (failing.has('documentNumberCheckDigit') || failing.has('compositeCheckDigit')) {
608
+ regions.push([0, 5, 15]); // doc-number..its check on the doc record
609
+ }
610
+ if (regions.length === 0) return null;
611
+
612
+ // Build all single-deletion candidates up front.
613
+ const candidates = [];
614
+ for (const [li, from, to] of regions) {
615
+ const original = pad30(lines[li] ?? '');
616
+ for (let i = from; i < to && i < original.length; i++) {
617
+ const edited = pad30(original.slice(0, i) + original.slice(i + 1));
618
+ const candidate = lines.map(pad30);
619
+ candidate[li] = edited;
620
+ candidates.push(candidate);
621
+ }
622
+ }
623
+
624
+ // Cheap pass first: a plain parse or a composite recompute resolves the common
625
+ // case (a dropped/duplicated digit) in microseconds — try ALL deletions this
626
+ // way before paying for any substitution search.
627
+ for (const candidate of candidates) {
628
+ let r;
629
+ try {
630
+ r = parse(candidate);
631
+ } catch {
632
+ continue;
633
+ }
634
+ if (r.valid) return r;
635
+ const composite = fixTD1Composite(candidate);
636
+ if (composite?.valid) return composite;
637
+ }
638
+
639
+ // Expensive pass only if the cheap pass found nothing: a deletion may align the
640
+ // structure but leave a residual ambiguous char (e.g. B→8 in the TC number).
641
+ for (const candidate of candidates) {
642
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
643
+ const subbed = recoverByFailingFields(candidate, false);
644
+ if (subbed?.valid) return subbed;
645
+ }
646
+ return null;
647
+ };
648
+ const recoverByFailingFields = (lines, tryIndel = true) => {
649
+ // `parse` THROWS (not returns invalid) on a wrong line count; a caller passing a
650
+ // noisy/fragmented line set must get null, not an exception that aborts the flow.
651
+ let first;
652
+ try {
653
+ first = parse(lines);
654
+ } catch {
655
+ return null;
656
+ }
657
+ if (first.valid) return first;
658
+
659
+ // If only the composite check digit is off (common when OCR drops the trailing
660
+ // digit), recompute it deterministically before the search.
661
+ const compositeFixed = fixTD1Composite(lines);
662
+ if (compositeFixed) return compositeFixed;
663
+ const spans = CHECK_DIGIT_FIELD_DATA_SPANS[first.format ?? ''];
664
+ if (!spans) return null;
665
+ const isDigit = c => c >= '0' && c <= '9';
666
+
667
+ // A "change cost" for replacing `orig` with `repl` at a position that, per the
668
+ // MRZ field layout, is expected to hold a digit (`expectDigit`). Lower = more
669
+ // likely. The dominant real-world OCR error is letter↔digit confusion in
670
+ // numeric fields (O→0, S→5, A→4, B→8, I→1), so:
671
+ // - turning a misread letter into the expected digit is cheap (0)
672
+ // - keeping/introducing a non-digit where a digit is expected is expensive
673
+ const changeCost = (orig, repl, expectDigit) => {
674
+ if (repl === orig) return 0; // no change always cheapest
675
+ const origDigit = isDigit(orig);
676
+ const replDigit = isDigit(repl);
677
+ // OCR overwhelmingly confuses a LETTER for a digit in numeric MRZ fields
678
+ // (O→0, S→5, A→4, B→8, I→1), rarely the reverse. So:
679
+ // - letter → digit : very cheap (the common real correction) => 1
680
+ // - letter → letter : plausible only in alpha positions => 3
681
+ // - digit → letter : OCR almost never turns a real digit into a letter => 8
682
+ // - digit → digit : possible but unusual => 4
683
+ if (!origDigit && replDigit) return expectDigit ? 1 : 2;
684
+ if (!origDigit && !replDigit) return expectDigit ? 6 : 3;
685
+ if (origDigit && !replDigit) return 8;
686
+ return 4; // digit -> digit
687
+ };
688
+
689
+ // Per-format map of which data positions are expected to be digits. Document
690
+ // numbers can be alphanumeric, but Turkish-style IDs use letter-then-digits,
691
+ // and dates/personal numbers are always digits. We treat a position as
692
+ // "expectDigit" when its current best guess across candidates is numeric;
693
+ // dates are always numeric.
694
+ const expectsDigitAt = (field, indexWithinField) => {
695
+ if (field === 'birthDateCheckDigit' || field === 'expirationDateCheckDigit') {
696
+ return true; // dates are all digits
697
+ }
698
+ if (field === 'documentNumberCheckDigit') {
699
+ // Common ID layout: position 0 is a letter, the rest digits.
700
+ return indexWithinField > 0;
701
+ }
702
+ return false;
703
+ };
704
+ const positions = [];
705
+ for (const d of first.details ?? []) {
706
+ if (d.valid || !spans[d.field]) continue;
707
+ const [ln, start, end] = spans[d.field];
708
+ const line = lines[ln];
709
+ if (line == null) continue;
710
+ for (let i = start; i < end; i++) {
711
+ const orig = line[i];
712
+ const alts = AMBIGUOUS_CHAR_MAP[orig];
713
+ if (alts && alts.length) {
714
+ const expectDigit = expectsDigitAt(d.field, i - start);
715
+ const options = [orig, ...alts].map(ch => ({
716
+ ch,
717
+ cost: changeCost(orig, ch, expectDigit)
718
+ })).sort((a, b) => a.cost - b.cost);
719
+ positions.push({
720
+ line: ln,
721
+ index: i,
722
+ options
723
+ });
724
+ }
725
+ }
726
+ }
727
+ if (positions.length === 0) return null;
728
+ const total = positions.reduce((acc, p) => acc * p.options.length, 1);
729
+ // The legitimate search space for a genuine OCR misread is small — a handful of
730
+ // ambiguous characters in the failing check-digit fields. A huge `total` means
731
+ // the frame is garbage (many ambiguous chars, no real MRZ); exhaustively
732
+ // parsing tens of thousands of permutations there would block the JS thread for
733
+ // ~1s per frame and freeze the UI. Cap hard so a noisy frame fails fast.
734
+ const MAX_PERMUTATIONS = 4096;
735
+ if (total > MAX_PERMUTATIONS) return null;
736
+
737
+ // Decode candidate index `n` into a per-position option choice, and compute its
738
+ // total change cost (sum of per-option costs). We then try candidates in
739
+ // ascending total cost so the most plausible OCR correction is accepted first.
740
+ const decode = n => {
741
+ let k = n;
742
+ let cost = 0;
743
+ const indices = positions.map(p => {
744
+ const idx = k % p.options.length;
745
+ k = Math.floor(k / p.options.length);
746
+ cost += p.options[idx].cost;
747
+ return idx;
748
+ });
749
+ return {
750
+ indices,
751
+ cost
752
+ };
753
+ };
754
+ const order = Array.from({
755
+ length: total
756
+ }, (_, n) => n);
757
+ const costCache = new Map();
758
+ const costOf = n => {
759
+ let c = costCache.get(n);
760
+ if (c === undefined) {
761
+ c = decode(n).cost;
762
+ costCache.set(n, c);
763
+ }
764
+ return c;
765
+ };
766
+ order.sort((a, b) => costOf(a) - costOf(b) || a - b);
767
+ for (const n of order) {
768
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
769
+ const {
770
+ indices
771
+ } = decode(n);
772
+ const chars = {};
773
+ for (const p of positions) {
774
+ if (!chars[p.line]) chars[p.line] = lines[p.line].split('');
775
+ }
776
+ positions.forEach((p, pi) => {
777
+ chars[p.line][p.index] = p.options[indices[pi]].ch;
778
+ });
779
+ const candidate = lines.slice();
780
+ for (const lnStr of Object.keys(chars)) {
781
+ candidate[Number(lnStr)] = chars[Number(lnStr)].join('');
782
+ }
783
+ const r = parse(candidate);
784
+ if (r.valid) return r;
785
+ }
786
+
787
+ // Substitution alone couldn't fix it. If OCR inserted/dropped a character
788
+ // (a length/alignment error), try single-char edits and re-validate.
789
+ if (tryIndel) {
790
+ const indel = recoverTD1ByIndel(lines);
791
+ if (indel?.valid) return indel;
792
+ }
793
+ return null;
794
+ };
795
+
796
+ /**
797
+ * Rebuild the corrected fixed-width MRZ lines from a (valid) parse result.
798
+ * Every field's `ranges` carry the actual post-correction characters at known
799
+ * line/column spans, so laying each `raw` span into a per-line buffer yields the
800
+ * exact MRZ that satisfied the check digits — the genuinely fixed version to show
801
+ * the user, not the lightweight `fixMRZ` pre-clean.
802
+ */
803
+ const correctedMrzFromParse = result => {
804
+ const widths = {
805
+ TD1: 30,
806
+ TD2: 36,
807
+ TD3: 44
808
+ };
809
+ const width = widths[result.format ?? ''];
810
+ if (!width) return undefined;
811
+ const lineCount = result.format === 'TD1' ? 3 : 2;
812
+ const buffers = Array.from({
813
+ length: lineCount
814
+ }, () => new Array(width).fill('<'));
815
+ for (const detail of result.details ?? []) {
816
+ for (const range of detail.ranges ?? []) {
817
+ // `raw` (the actual characters at this span) exists at runtime but isn't in
818
+ // the `mrz` Range type.
819
+ const {
820
+ line,
821
+ start,
822
+ raw = ''
823
+ } = range;
824
+ const buf = buffers[line];
825
+ if (!buf) continue;
826
+ for (let i = 0; i < raw.length && start + i < width; i++) {
827
+ buf[start + i] = raw[i];
828
+ }
829
+ }
830
+ }
831
+ return buffers.map(b => b.join('')).join('\n');
832
+ };
833
+
834
+ /**
835
+ * Heuristic: does a parsed result's name look like it still carries OCR noise
836
+ * (a digit where a name letter belongs, or a run of filler-confusable letters
837
+ * that should have been "<")? Names are letters only, so any digit is noise; a
838
+ * 3+ run of K/C/E/G is very likely misread fillers leaking into the given names.
839
+ */
840
+ const nameLooksNoisy = r => {
841
+ const name = `${r.fields?.lastName ?? ''} ${r.fields?.firstName ?? ''}`;
842
+ // A DIGIT in a name is unambiguous OCR noise (MRZ names are letters only).
843
+ // A 5+ run of filler-confusable letters is almost certainly misread padding —
844
+ // real given names like "ECE"/"GECE" are short, so keep the threshold high to
845
+ // avoid false positives on legitimate names.
846
+ return /[0-9]/.test(name) || /[KCEG]{5,}/.test(name);
847
+ };
848
+
314
849
  /**
315
850
  * Validates MRZ text using the mrz npm package
316
851
  * @param mrzText Raw or cleaned MRZ text
@@ -319,20 +854,106 @@ const generateAmbiguousVariants = (text, maxChanges = 2, maxVariants = 64) => {
319
854
  */
320
855
  const validateMRZ = (mrzText, autocorrect = true) => {
321
856
  try {
857
+ // Arm the recovery wall-clock budget for this call so the search below can't
858
+ // block the JS thread on a garbage frame.
859
+ recoveryDeadline = Date.now() + RECOVERY_BUDGET_MS;
322
860
  const fixedText = fixMRZ(mrzText);
323
- let result = parse(fixedText, {
324
- autocorrect
325
- });
861
+ // `parse` THROWS on a wrong MRZ-line count (e.g. a noisy frame with a title
862
+ // line + fragments). That must NOT short-circuit the recovery/reconstruction
863
+ // path below — treat a throw here as "no valid parse yet" and keep going.
864
+ let result = null;
865
+ try {
866
+ result = parse(fixedText, {
867
+ autocorrect
868
+ });
869
+ } catch {
870
+ result = null;
871
+ }
872
+
873
+ // The direct parse can validate (the name field has no check digit) while the
874
+ // name line still carries OCR noise — a leading "O" read as "0", or trailing
875
+ // "<" fillers read as K/C/E/G that leak into the given names. The
876
+ // reconstruction path normalises the name line; when the direct result's name
877
+ // looks noisy, prefer a reconstructed candidate that validates with a cleaner
878
+ // name. This only ever swaps in another fully check-digit-valid reading.
879
+ if (result?.valid && nameLooksNoisy(result)) {
880
+ for (const reLines of reconstructMRZCandidates(mrzText)) {
881
+ let cand;
882
+ try {
883
+ cand = parse(reLines);
884
+ } catch {
885
+ continue;
886
+ }
887
+ if (cand.valid && !nameLooksNoisy(cand)) {
888
+ result = cand;
889
+ break;
890
+ }
891
+ }
892
+ }
893
+
894
+ // Primary recovery: exhaustive, CHECK-DIGIT-DRIVEN correction scoped to the
895
+ // fields whose check digit actually fails. It tries every OCR-ambiguous
896
+ // permutation within those fields — ordered by how likely the OCR error is
897
+ // (letter→digit in numeric fields is cheapest) — and only accepts a candidate
898
+ // when the WHOLE MRZ validates (document-number, date and composite check
899
+ // digits all pass). This both (a) fixes a misread document number before the
900
+ // caller advances to the NFC/next screen, and (b) prefers the genuinely
901
+ // correct correction over an arbitrary check-digit-satisfying one.
902
+ if (!result || !result.valid) {
903
+ const fixedLines = fixedText.split('\n').filter(l => l.trim());
904
+ if (fixedLines.length >= 2) {
905
+ const recovered = recoverByFailingFields(fixedLines);
906
+ if (recovered && recovered.valid) {
907
+ result = recovered;
908
+ }
909
+ }
910
+ }
911
+
912
+ // Last-resort fallback: the older whole-string ambiguous sweep, only for
913
+ // inputs the field-scoped recovery can't address (e.g. an unrecognised
914
+ // format with no check-digit span map). Still requires a fully-valid parse.
326
915
  if (!result || !result.valid) {
327
916
  const variants = generateAmbiguousVariants(fixedText);
328
917
  for (const variant of variants) {
918
+ if (recoveryExpired()) break; // bail before blocking the JS thread
329
919
  if (variant === fixedText) continue;
330
- const candidate = parse(variant, {
331
- autocorrect
332
- });
333
- if (candidate && candidate.valid) {
334
- result = candidate;
335
- break;
920
+ try {
921
+ const candidate = parse(variant, {
922
+ autocorrect
923
+ });
924
+ if (candidate && candidate.valid) {
925
+ result = candidate;
926
+ break;
927
+ }
928
+ } catch {
929
+ // Malformed variant — try the next.
930
+ }
931
+ }
932
+ }
933
+
934
+ // Last resort: the standard line-splitter couldn't assemble a parseable MRZ
935
+ // (e.g. a noisy frame where OCR split the band, mixed in front-of-card text,
936
+ // or broke a field with spaces). Reconstruct fixed-width line-sets for every
937
+ // supported format (TD1/TD2/TD3) and validate each WITH CHECK DIGITS, keeping
938
+ // only one that passes — a wrong reconstruction can never leak through.
939
+ if (!result || !result.valid) {
940
+ for (const reLines of reconstructMRZCandidates(mrzText)) {
941
+ // A reconstructed candidate for the wrong format (e.g. a 2-line TD2 guess
942
+ // built from a TD1 frame) makes the `mrz` parser THROW on line count —
943
+ // that must not abort the loop before a good candidate is tried.
944
+ try {
945
+ const direct = parse(reLines);
946
+ if (direct && direct.valid) {
947
+ result = direct;
948
+ break;
949
+ }
950
+ const recovered = recoverByFailingFields(reLines);
951
+ if (recovered && recovered.valid) {
952
+ result = recovered;
953
+ break;
954
+ }
955
+ } catch {
956
+ // Skip this malformed candidate and try the next.
336
957
  }
337
958
  }
338
959
  }
@@ -371,7 +992,8 @@ const validateMRZ = (mrzText, autocorrect = true) => {
371
992
  return {
372
993
  valid: true,
373
994
  format,
374
- fields
995
+ fields,
996
+ correctedMrz: correctedMrzFromParse(result)
375
997
  };
376
998
  } catch (error) {
377
999
  return {
@@ -472,6 +1094,7 @@ export default {
472
1094
  fixMRZ,
473
1095
  validateMRZ,
474
1096
  validateMRZWithCorrections,
1097
+ reconstructMRZCandidates,
475
1098
  calculateMRZQualityScore,
476
1099
  assessMRZQuality,
477
1100
  isValidOCRBPattern,