@asteby/storefront 0.9.0 → 0.11.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.
- package/README.md +181 -4
- package/dist/cli.js +665 -0
- package/dist/fiscal-document.cjs +659 -0
- package/dist/fiscal-document.cjs.map +1 -0
- package/dist/fiscal-document.d.cts +215 -0
- package/dist/fiscal-document.d.ts +215 -0
- package/dist/fiscal-document.js +641 -0
- package/dist/fiscal-document.js.map +1 -0
- package/dist/index.cjs +111 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +76 -5
- package/dist/index.d.ts +76 -5
- package/dist/index.js +109 -6
- package/dist/index.js.map +1 -1
- package/dist/mock.cjs +1185 -11
- package/dist/mock.cjs.map +1 -1
- package/dist/mock.d.cts +51 -2
- package/dist/mock.d.ts +51 -2
- package/dist/mock.js +1182 -12
- package/dist/mock.js.map +1 -1
- package/dist/mockup.d.cts +1 -1
- package/dist/mockup.d.ts +1 -1
- package/dist/node.cjs +243 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +100 -0
- package/dist/node.d.ts +100 -0
- package/dist/node.js +209 -0
- package/dist/node.js.map +1 -0
- package/dist/{types-CSMuPSQA.d.cts → types-C-Ley-Mt.d.cts} +333 -3
- package/dist/{types-iGGZ9EiC.d.ts → types-D7UJxrba.d.ts} +333 -3
- package/package.json +41 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fiscal-document/registry.ts","../src/fiscal-document/text.ts","../src/fiscal-document/engine.ts","../src/fiscal-document/errors.ts","../src/fiscal-document/pdf.ts","../src/fiscal-document/qr.ts"],"names":["pages","custom"],"mappings":";;;AAEA,IAAM,UAAA,uBAAiB,GAAA,EAAiC;AAQjD,SAAS,yBAAA,CAA0B,KAAa,EAAA,EAAqC;AAC1F,EAAA,IAAI,CAAC,OAAO,OAAO,EAAA,KAAO,YAAY,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAC9G,E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AAG,IAAI,CAAA;AACxC,IAAA,MAAM,KAAA,GAAQ,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,IAAK,CAAA,IAAK,KAAK,IAAI,CAAA;AACpE,IAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,MAAA,IAAI;AACF,QAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAC,CAAA;AACvC,QAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,CAAK,IAAA,EAAM,QAAQ,KAAA,IAAS,CAAA,EAAG,QAAQ,MAAM,CAAA;AACjE,QAAA,IAAA,CAAK,OAAA,IAAU;AACf,QAAA,IAAI,OAAO,OAAO,KAAA;AAAA,MACpB,SAAS,GAAA,EAAK;AACZ,QAAA,IAAI,GAAA,YAAe,uBAAuB,MAAM,GAAA;AAAA,MAClD;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,SAAE;AACA,IAAA,MAAM,OAAO,OAAA,EAAQ;AAAA,EACvB;AACF","file":"fiscal-document.cjs","sourcesContent":["import type { IdentityExtractorFn } from './types.js'\n\nconst extractors = new Map<string, IdentityExtractorFn>()\n\n/**\n * Registers the extractor of a document the `rules@1` engine cannot describe (a country whose document needs\n * code). `key` is the document `kind` (`XX:doc`) or the `<id>` of a spec with `engine: 'plugin:<id>'`; the id\n * wins. The server-side validator stays the region's: a plugin only reads text. Replaces a previous one.\n * Returns a function that unregisters it.\n */\nexport function registerIdentityExtractor(key: string, fn: IdentityExtractorFn): () => void {\n if (!key || typeof fn !== 'function') throw new TypeError('registerIdentityExtractor: key and fn are required')\n extractors.set(key, fn)\n return () => {\n if (extractors.get(key) === fn) extractors.delete(key)\n }\n}\n\nexport function getIdentityExtractor(key: string): IdentityExtractorFn | undefined {\n return extractors.get(key)\n}\n","/**\n * Text helpers of the rules engine. Pure; no DOM, no network.\n */\n\nconst FOLD: Record<string, string> = {}\nfor (const [from, to] of [\n ['áàâãä', 'a'], ['éèêë', 'e'], ['íìîï', 'i'], ['óòôõö', 'o'], ['úùûü', 'u'], ['ñ', 'n'], ['ç', 'c'],\n] as const) for (const ch of from) FOLD[ch] = to\n\n/** Lowercases, strips Latin accents and collapses whitespace; the base of every phrase comparison (punctuation is kept). */\nexport function foldText(s: string): string {\n let out = ''\n for (const ch of s.toLowerCase()) out += FOLD[ch] ?? ch\n return out.split(/\\s+/).filter(Boolean).join(' ')\n}\n\n/** Whole days from `iso` (`YYYY-MM-DD`) to `now`; `null` for an invalid date. Negative: in the future. */\nexport function ageInDays(isoDate: string, now: Date): number | null {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(isoDate)\n if (!m) return null\n const then = Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!)\n const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())\n return Math.floor((today - then) / 86_400_000)\n}\n\n/** Hex SHA-256 of the bytes (Web Crypto: browsers, Node 20+, edge runtimes). */\nexport async function sha256Hex(data: ArrayBuffer | Uint8Array): Promise<string> {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle\n if (!subtle) throw new TypeError('sha256Hex: Web Crypto (crypto.subtle) is not available')\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data)\n const digest = await subtle.digest('SHA-256', bytes as unknown as BufferSource)\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n","import type { IdentityDocumentSpec, IdentityRulesV1, IdentityStrategy, RegionFiscalId } from '../types.js'\nimport { getIdentityExtractor } from './registry.js'\nimport { ageInDays, foldText } from './text.js'\nimport type { EvidenceInput, ExtractOptions, ExtractedValue, FiscalDocumentEvidence, IdentityCatalogs, IdentityExtraction } from './types.js'\n\n/** Longest text the engine reads (a one-page document is a few thousand characters). */\nexport const MAX_TEXT_LENGTH = 400_000\n\nconst MAX_FIELDS = 32\nconst MAX_STRATEGIES = 8\nconst MAX_PATTERN = 1024\nconst STRATEGIES = new Set(['regex', 'labeled_lines', 'concat_labeled', 'catalog_phrases', 'date', 'qr_param'])\nconst STRATEGY_KEYS = new Set([\n 'strategy', 'pattern', 'flags', 'group', 'label', 'labels', 'separator', 'catalog', 'start', 'end', 'order', 'months',\n 'param', 'split', 'parts', 'match', 'upper', 'capture', 'scan',\n])\nconst RULES_KEYS = new Set(['version', 'normalize', 'labels', 'qr_canonical', 'fields'])\nconst PLACEHOLDER = /\\{([a-z0-9_]+)\\}/g\n\n/** Thrown for a spec that cannot run (unknown engine, rules that do not validate, no extractor registered). */\nexport class IdentityRulesError extends Error {\n override readonly name = 'IdentityRulesError'\n}\n\n// ---- regular expressions ---------------------------------------------------\n\nconst cache = new Map<string, RegExp>()\n\nfunction checkPattern(what: string, p: string | undefined, flags = ''): void {\n if (!p) throw new IdentityRulesError(`rules: ${what}: empty pattern`)\n if (p.length > MAX_PATTERN) throw new IdentityRulesError(`rules: ${what}: pattern longer than ${MAX_PATTERN}`)\n for (const f of flags) if (f !== 'i' && f !== 's' && f !== 'm') throw new IdentityRulesError(`rules: ${what}: unknown flag \"${f}\"`)\n if (p.replaceAll('(?:', '').includes('(?')) throw new IdentityRulesError(`rules: ${what}: only (?: groups are portable`)\n for (const bad of ['[[:', '\\\\p', '\\\\P', '\\\\z', '\\\\A', '\\\\Q', '\\\\E', '\\\\C']) {\n if (p.includes(bad)) throw new IdentityRulesError(`rules: ${what}: ${bad} is not portable`)\n }\n try {\n compiled(p, flags)\n } catch (err) {\n throw err instanceof IdentityRulesError ? err : new IdentityRulesError(`rules: ${what}: invalid pattern`)\n }\n}\n\nfunction compiled(p: string, flags = '', global = false): RegExp {\n const k = `${global ? 'g' : ''}${flags}/${p}`\n let re = cache.get(k)\n if (!re) {\n re = new RegExp(p, flags + (global ? 'g' : ''))\n cache.set(k, re)\n }\n re.lastIndex = 0\n return re\n}\n\n// ---- validation (same checks as the reference interpreter) ------------------\n\nfunction validateStrategy(s: IdentityStrategy, haveLabels: boolean): void {\n for (const k of Object.keys(s)) if (!STRATEGY_KEYS.has(k)) throw new IdentityRulesError(`rules: unknown member \"${k}\"`)\n if (s.capture) {\n checkPattern('capture', s.capture.pattern, s.capture.flags)\n const groups = new RegExp(s.capture.pattern + '|').exec('')!.length - 1\n if ((s.capture.group ?? 0) < 0 || (s.capture.group ?? 0) > groups) throw new IdentityRulesError('rules: capture group does not exist')\n }\n switch (s.strategy) {\n case 'regex': {\n checkPattern('pattern', s.pattern, s.flags)\n const groups = new RegExp(s.pattern + '|').exec('')!.length - 1\n if ((s.group ?? 0) < 0 || (s.group ?? 0) > groups) throw new IdentityRulesError('rules: regex group does not exist')\n return\n }\n case 'labeled_lines':\n if (!haveLabels) throw new IdentityRulesError('rules: labeled_lines needs the top-level labels list')\n return checkPattern('label', s.label)\n case 'concat_labeled':\n if (!haveLabels || !s.labels?.length) throw new IdentityRulesError('rules: concat_labeled needs labels')\n return s.labels.forEach((l) => checkPattern('labels', l))\n case 'catalog_phrases':\n if (!s.catalog) throw new IdentityRulesError('rules: catalog_phrases needs a catalog')\n return [s.start, s.end].forEach((p) => p && checkPattern('section', p, 'i'))\n case 'date': {\n checkPattern('pattern', s.pattern, s.flags)\n const order = s.order ?? ''\n if (order.length !== 3 || ![...'dmy'].every((c) => order.split(c).length === 2)) throw new IdentityRulesError(`rules: date order \"${order}\" must be a permutation of d, m, y`)\n if (new RegExp(s.pattern + '|').exec('')!.length - 1 < 3) throw new IdentityRulesError('rules: date pattern needs three groups')\n if (s.months && s.months.length !== 0 && s.months.length !== 12) throw new IdentityRulesError('rules: date months wants 12 names')\n return\n }\n case 'qr_param': {\n if (!s.param && !s.scan) throw new IdentityRulesError('rules: qr_param needs a param or a scan')\n if ((s.parts ?? 0) < 0) throw new IdentityRulesError('rules: qr_param parts must not be negative')\n if (s.scan) {\n checkPattern('scan', s.scan, s.flags)\n const groups = new RegExp(s.scan + '|').exec('')!.length - 1\n if ((s.group ?? 0) < 1 || (s.group ?? 0) > groups) throw new IdentityRulesError('rules: scan group does not exist')\n }\n if (s.param) checkPattern('match', s.match)\n return\n }\n default:\n throw new IdentityRulesError(`rules: unknown strategy \"${String(s.strategy)}\"`)\n }\n}\n\n/** Checks rules are well formed and portable; no rule may produce a `discard` field. Throws `IdentityRulesError`. */\nexport function validateRules(rules: IdentityRulesV1, discard: string[] = []): void {\n for (const k of Object.keys(rules ?? {})) if (!RULES_KEYS.has(k)) throw new IdentityRulesError(`rules: unknown member \"${k}\"`)\n if (rules?.version !== 1) throw new IdentityRulesError(`rules: version ${String(rules?.version)} is not 1`)\n for (const n of rules.normalize ?? []) if (n !== 'nbsp' && n !== 'collapse_ws') throw new IdentityRulesError(`rules: unknown normalize step \"${String(n)}\"`)\n for (const l of rules.labels ?? []) checkPattern('labels', l)\n if (!Array.isArray(rules.fields) || rules.fields.length === 0 || rules.fields.length > MAX_FIELDS) throw new IdentityRulesError(`rules: want 1..${MAX_FIELDS} fields`)\n if (rules.qr_canonical) {\n const keys = new Set(rules.fields.map((f) => f.key))\n for (const m of rules.qr_canonical.matchAll(PLACEHOLDER)) if (!keys.has(m[1]!)) throw new IdentityRulesError(`rules: qr_canonical names unknown field \"${m[1]}\"`)\n }\n const drop = new Set(discard.map((d) => d.trim().toLowerCase()))\n const seen = new Set<string>()\n for (const f of rules.fields) {\n if (!f.key || seen.has(f.key)) throw new IdentityRulesError(`rules: field key \"${f.key}\" is empty or repeated`)\n seen.add(f.key)\n if (drop.has(f.key.toLowerCase())) throw new IdentityRulesError(`rules: field \"${f.key}\" is in discard_fields`)\n if (!Array.isArray(f.strategies) || f.strategies.length === 0 || f.strategies.length > MAX_STRATEGIES) throw new IdentityRulesError(`rules: field \"${f.key}\" wants 1..${MAX_STRATEGIES} strategies`)\n for (const s of f.strategies) {\n if (!STRATEGIES.has(s.strategy)) throw new IdentityRulesError(`rules: unknown strategy \"${String(s.strategy)}\"`)\n validateStrategy(s, (rules.labels?.length ?? 0) > 0)\n }\n }\n}\n\nfunction parseRules(spec: IdentityDocumentSpec): IdentityRulesV1 {\n let rules = spec.rules\n if (typeof rules === 'string') {\n try {\n rules = JSON.parse(rules) as IdentityRulesV1\n } catch {\n throw new IdentityRulesError(`${spec.kind}: rules is not valid JSON`)\n }\n }\n if (!rules || typeof rules !== 'object') throw new IdentityRulesError(`${spec.kind}: rules@1 needs rules`)\n // A rule that produces a discarded field is the publisher's error (`validateRules` flags it); reading still drops it.\n validateRules(rules)\n return rules\n}\n\n// ---- interpreter (mirrors the reference ExtractIdentity) --------------------\n\nfunction normalizeText(s: string, steps: string[] = []): string {\n let t = s.length > MAX_TEXT_LENGTH ? s.slice(0, MAX_TEXT_LENGTH) : s\n for (const st of steps) {\n if (st === 'nbsp') t = t.replaceAll(' ', ' ')\n else if (st === 'collapse_ws') t = t.split(/\\s+/).filter(Boolean).join(' ')\n }\n return t\n}\n\ntype LabelHit = { caption: string; start: number; from: number }\n\nclass LabelIndex {\n private readonly hits: LabelHit[] = []\n constructor(\n labels: string[],\n private readonly text: string,\n ) {\n if (labels.length === 0) return\n for (const m of text.matchAll(new RegExp(`(?:^|\\\\s)(${labels.join('|')})\\\\s*:`, 'gi'))) {\n this.hits.push({ caption: m[1] ?? '', start: m.index, from: m.index + m[0].length })\n }\n }\n\n value(label: string): string {\n const full = compiled(`^(?:${label})$`, 'i')\n for (let i = 0; i < this.hits.length; i++) {\n const h = this.hits[i]!\n if (!full.test(h.caption)) continue\n const end = i + 1 < this.hits.length ? this.hits[i + 1]!.start : this.text.length\n return this.text.slice(h.from, end).trim()\n }\n return ''\n }\n}\n\nfunction section(text: string, start?: string, end?: string): string {\n let from = 0\n if (start) {\n const m = compiled(start, 'is').exec(text)\n if (!m) return ''\n from = m.index + m[0].length\n }\n let to = text.length\n if (end) {\n const m = compiled(end, 'is').exec(text.slice(from))\n if (m) to = from + m.index\n }\n return text.slice(from, to)\n}\n\nfunction phrasesOf(e: { label: string; label_en?: string; match_phrases?: string[] }): string[] {\n const src = e.match_phrases?.length ? e.match_phrases : [e.label, e.label_en ?? '']\n return [...new Set(src.map(foldText).filter(Boolean))]\n}\n\nfunction catalogHits(sec: string, entries: IdentityCatalogs[string] = []): string[] {\n const hay = foldText(sec)\n const hits: { code: string; at: number }[] = []\n for (const e of entries) {\n let best = -1\n for (const p of phrasesOf(e)) {\n const at = hay.indexOf(p)\n if (at >= 0 && (best < 0 || at < best)) best = at\n }\n if (best >= 0) hits.push({ code: e.code, at: best })\n }\n return hits.sort((a, b) => a.at - b.at).map((h) => h.code)\n}\n\nfunction parseDate(text: string, s: IdentityStrategy): string {\n const m = compiled(s.pattern!, s.flags ?? '').exec(text)\n if (!m) return ''\n let d = 0\n let mo = 0\n let y = 0\n for (let i = 0; i < 3; i++) {\n const c = s.order![i]\n const g = (m[i + 1] ?? '').trim()\n let n = /^[+-]?\\d+$/.test(g) ? Number(g) : NaN\n if (Number.isNaN(n) && c === 'm' && s.months?.length === 12) {\n n = 0\n s.months.forEach((name, j) => {\n if (foldText(name) === foldText(g)) n = j + 1\n })\n }\n if (Number.isNaN(n) || n === 0) return ''\n if (c === 'd') d = n\n else if (c === 'm') mo = n\n else y = n\n }\n const t = new Date(Date.UTC(y, mo - 1, d))\n if (y < 1000 || t.getUTCFullYear() !== y || t.getUTCMonth() + 1 !== mo || t.getUTCDate() !== d) return ''\n return `${String(y).padStart(4, '0')}-${String(mo).padStart(2, '0')}-${String(d).padStart(2, '0')}`\n}\n\nfunction qrScan(qr: string, s: IdentityStrategy): string {\n if (!s.scan) return ''\n const m = compiled(s.scan, s.flags ?? '').exec(qr)\n return m ? (m[s.group ?? 0] ?? '').trim().toUpperCase() : ''\n}\n\nfunction qrPart(qr: string, s: IdentityStrategy): string {\n const url = qr.trim()\n if (!url) return ''\n if (!s.param) return qrScan(url, s)\n const m = new RegExp(`[?&]${s.param.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}=([^&\\\\s#]+)`, 'i').exec(url)\n if (!m) return qrScan(url, s)\n let val: string\n try {\n val = decodeURIComponent(m[1]!.replaceAll('+', ' '))\n } catch {\n return ''\n }\n const parts = s.split ? val.split(s.split) : [val]\n if ((s.parts ?? 0) > 0 && parts.length !== s.parts) return qrScan(url, s)\n const re = compiled(s.match!)\n for (const raw of parts) {\n const p = raw.trim().toUpperCase()\n if (re.test(p)) return p\n }\n return qrScan(url, s)\n}\n\n/** Go's url.QueryEscape: space as +, everything but letters, digits and -_.~ percent-encoded. */\nfunction queryEscape(v: string): string {\n return encodeURIComponent(v)\n .replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replaceAll('%20', '+')\n}\n\nfunction post(s: IdentityStrategy, value: string): string {\n let v = value.trim()\n if (!v) return ''\n if (s.upper) v = v.toUpperCase()\n if (s.capture) {\n const m = compiled(s.capture.pattern, s.capture.flags ?? '').exec(v)\n if (!m) return ''\n v = (m[s.capture.group ?? 0] ?? '').trim()\n }\n return v\n}\n\nfunction run(s: IdentityStrategy, text: string, labels: LabelIndex, catalogs: IdentityCatalogs): string[] {\n switch (s.strategy) {\n case 'regex': {\n const m = compiled(s.pattern!, s.flags ?? '').exec(text)\n return m ? [m[s.group ?? 0] ?? ''] : []\n }\n case 'labeled_lines':\n return [labels.value(s.label!)]\n case 'concat_labeled': {\n const parts = (s.labels ?? []).map((l) => labels.value(l).trim()).filter(Boolean)\n return [parts.join(s.separator || ' ')]\n }\n case 'catalog_phrases':\n return catalogHits(section(text, s.start, s.end), catalogs[s.catalog!])\n case 'date':\n return [parseDate(text, s)]\n default:\n return []\n }\n}\n\nconst nonEmpty = (vals: string[]) => vals.map((v) => v.trim()).filter(Boolean)\n\n/**\n * Reads an identity document (the text of a PDF, `readPdfText`) with the rules of its spec: the TypeScript twin of\n * the reference interpreter of the region packs. Generic, the country is data. `discard_fields` never appear in\n * the output. Pure and synchronous; a text that does not match yields `missing`, never an exception; only a spec\n * that cannot run throws `IdentityRulesError`.\n */\nexport function extractIdentityDocument(text: string, spec: IdentityDocumentSpec, options: ExtractOptions = {}): IdentityExtraction {\n const discard = (spec.discard_fields ?? []).map((d) => d.trim().toLowerCase())\n const out: IdentityExtraction = {\n kind: spec.kind,\n extractor: spec.engine,\n fields: {},\n sources: {},\n missing: [],\n discarded: [...(spec.discard_fields ?? [])],\n qr: { match: null, canonical: '' },\n stale: null,\n age_days: null,\n }\n\n if (spec.engine === 'rules@1') {\n const rules = parseRules(spec)\n const body = normalizeText(text, rules.normalize)\n const labels = new LabelIndex(rules.labels ?? [], body)\n const catalogs = options.catalogs ?? {}\n let compared = 0\n let equal = 0\n const qrBest: Record<string, string> = {}\n for (const f of rules.fields) {\n let textVals: string[] = []\n const qrVals: string[] = []\n for (const s of f.strategies) {\n if (s.strategy === 'qr_param') {\n const v = post(s, qrPart(options.qr ?? '', s))\n if (v) qrVals.push(v)\n continue\n }\n if (textVals.length > 0) continue\n textVals = nonEmpty(run(s, body, labels, catalogs).map((v) => post(s, v)))\n }\n let got: string[] = []\n if (textVals.length > 0) {\n got = textVals\n out.sources[f.key] = 'text'\n } else if (qrVals.length > 0) {\n got = qrVals.slice(0, 1)\n out.sources[f.key] = 'qr'\n }\n if (qrVals.length > 0) qrBest[f.key] = qrVals[0]!\n if (textVals.length > 0 && qrVals.length > 0) {\n compared++\n if (textVals[0]!.toUpperCase() === qrVals[0]!.toUpperCase()) equal++\n }\n if (got.length === 0) {\n if (f.required) out.missing.push(f.key)\n } else out.fields[f.key] = f.multiple ? got : got[0]!\n }\n if (compared > 0) out.qr.match = compared === equal\n if (rules.qr_canonical && (options.qr ?? '').trim()) {\n let ok = true\n const canon = rules.qr_canonical.replace(PLACEHOLDER, (_p, key: string) => {\n const v = qrBest[key]\n if (!v) ok = false\n return queryEscape(v ?? '')\n })\n if (ok) out.qr.canonical = canon\n }\n } else {\n const id = spec.engine.startsWith('plugin:') ? spec.engine.slice('plugin:'.length) : spec.engine\n const fn = getIdentityExtractor(id) ?? getIdentityExtractor(spec.kind)\n if (!fn) throw new IdentityRulesError(`${spec.kind}: no extractor registered for engine \"${spec.engine}\"`)\n const res = fn(text, spec, options)\n out.fields = { ...res.fields }\n out.sources = { ...(res.sources ?? {}) }\n out.missing = [...(res.missing ?? [])]\n out.qr.match = res.qr_match ?? null\n }\n\n // The spec's discard list wins over any engine, plugins included.\n for (const k of Object.keys(out.fields)) {\n if (discard.includes(k.toLowerCase())) {\n delete out.fields[k]\n delete out.sources[k]\n }\n }\n\n const issued = out.fields.issued_on\n if (typeof issued === 'string') {\n out.age_days = ageInDays(issued, options.now ?? new Date())\n if (spec.freshness_days && out.age_days !== null) out.stale = out.age_days > spec.freshness_days\n }\n return out\n}\n\n/** The catalogs `catalog_phrases` rules name, from the region: `fiscal_regime` and `invoice_use`. */\nexport function catalogsFromRegion(fiscalId: Pick<RegionFiscalId, 'regimes' | 'invoice_uses'>): IdentityCatalogs {\n return { fiscal_regime: fiscalId.regimes, invoice_use: fiscalId.invoice_uses }\n}\n\n/**\n * The evidence to send with the fiscal data (`InvoiceRequest.document`): where it came from and nothing of the\n * document. `source` is `pdf_client` in the browser, `pdf_server` when a server read it, `manual` for typed data.\n */\nexport function buildDocumentEvidence(extraction: IdentityExtraction, input: EvidenceInput): FiscalDocumentEvidence {\n const id = extraction.fields.document_id\n const issued = extraction.fields.issued_on\n return {\n kind: extraction.kind,\n document_id: typeof id === 'string' ? id : null,\n issued_on: typeof issued === 'string' ? issued : null,\n sha256: input.sha256 ?? null,\n extractor: extraction.extractor,\n source: input.source,\n qr_match: extraction.qr.match,\n }\n}\n\nexport type { ExtractedValue }\n","export type IdentityDocumentErrorCode =\n /** Over `maxBytes`, or more than `maxPages` pages. */\n | 'too_large'\n /** Does not start with `%PDF-`. */\n | 'not_pdf'\n /** Corrupt, unsupported, or it took longer than `timeoutMs`. */\n | 'unreadable'\n /** A PDF without a text layer (a scan): ask for manual entry. */\n | 'no_text'\n /** Encrypted: it needs a password the buyer has not given. */\n | 'password'\n\n/** Why a document could not be read. `code` is stable; `message` is for logs (English) and never holds document text. */\nexport class IdentityDocumentError extends Error {\n override readonly name = 'IdentityDocumentError'\n readonly code: IdentityDocumentErrorCode\n /** Finer cause: `bytes`, `pages`, `timeout`, `aborted`... */\n readonly reason: string | undefined\n\n constructor(code: IdentityDocumentErrorCode, message: string, options?: { reason?: string; cause?: unknown }) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause })\n this.code = code\n this.reason = options?.reason\n }\n}\n\nexport function isIdentityDocumentError(err: unknown): err is IdentityDocumentError {\n return err instanceof IdentityDocumentError || (typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'IdentityDocumentError')\n}\n","import { IdentityDocumentError } from './errors.js'\nimport { sha256Hex } from './text.js'\n\n/** What `readPdfText` accepts: a browser `File`/`Blob`, or bytes (Node `Buffer` included). */\nexport type PdfSource = Blob | ArrayBuffer | ArrayBufferView\n\nexport type ReadPdfOptions = {\n /** Reject files larger than this (default 5 MiB). */\n maxBytes?: number\n /** Reject documents with more pages than this (default 6). */\n maxPages?: number\n /** Give up after this many ms (default 3000). */\n timeoutMs?: number\n /** Fewer non-space characters than this means \"no text layer\" (default 20). */\n minChars?: number\n /**\n * URL of the pdf.js worker (`pdf.worker.mjs` from `pdfjs-dist/legacy/build`) that YOUR site serves. Required in\n * browsers (there is deliberately no default and no CDN); ignored in Node, which needs no worker file.\n */\n workerSrc?: string\n /** Aborts the read. */\n signal?: AbortSignal\n}\n\nexport type PdfTextResult = {\n /** Text of all pages, one line per visual line, pages separated by a blank line. */\n text: string\n pages: number\n /** SHA-256 of the file as received, lowercase hex (evidence for `FiscalDocumentEvidence.sha256`). */\n sha256: string\n}\n\n/** The slice of pdf.js these helpers use. */\nexport type PdfjsLike = {\n getDocument(src: Record<string, unknown>): { promise: Promise<PdfDocumentLike>; destroy(): Promise<void> | void }\n GlobalWorkerOptions?: { workerSrc: string }\n}\nexport type PdfDocumentLike = {\n numPages: number\n getPage(n: number): Promise<PdfPageLike>\n destroy?(): Promise<void> | void\n}\nexport type PdfPageLike = {\n getTextContent(): Promise<{ items: Array<{ str?: string; transform?: number[]; hasEOL?: boolean }> }>\n getViewport(o: { scale: number }): { width: number; height: number }\n render(o: { canvasContext: unknown; viewport: unknown }): { promise: Promise<void> }\n cleanup?(): void\n}\n\nexport const DEFAULT_MAX_BYTES = 5 * 1024 * 1024\nexport const DEFAULT_MAX_PAGES = 6\nexport const DEFAULT_TIMEOUT_MS = 3000\n\nlet custom: (() => Promise<PdfjsLike>) | undefined\n\n/**\n * Replaces how pdf.js is loaded (tests, or a bundler that needs its own import). By default the legacy build of\n * `pdfjs-dist` is imported on first use, so it costs nothing until a document is read.\n */\nexport function setPdfjsLoader(loader: (() => Promise<PdfjsLike>) | undefined): void {\n custom = loader\n}\n\nexport async function loadPdfjs(workerSrc?: string): Promise<PdfjsLike> {\n const mod = custom ? await custom() : ((await import('pdfjs-dist/legacy/build/pdf.mjs')) as unknown as PdfjsLike)\n if (workerSrc && mod.GlobalWorkerOptions) mod.GlobalWorkerOptions.workerSrc = workerSrc\n const inBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'\n if (inBrowser && !mod.GlobalWorkerOptions?.workerSrc) {\n throw new TypeError('readPdfText: set `workerSrc` to a pdf.worker.mjs your site serves (there is no default and no CDN)')\n }\n return mod\n}\n\nasync function toBytes(source: PdfSource): Promise<Uint8Array> {\n if (typeof Blob !== 'undefined' && source instanceof Blob) return new Uint8Array(await source.arrayBuffer())\n if (source instanceof ArrayBuffer) return new Uint8Array(source)\n if (ArrayBuffer.isView(source)) return new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n throw new TypeError('readPdfText: expected a File, Blob, ArrayBuffer or Uint8Array')\n}\n\nfunction sizeOf(source: PdfSource): number {\n if (typeof Blob !== 'undefined' && source instanceof Blob) return source.size\n return (source as ArrayBuffer | ArrayBufferView).byteLength\n}\n\n/** `%PDF-` at the very start: a cheap check before any parsing. */\nexport function hasPdfSignature(bytes: Uint8Array): boolean {\n return bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d\n}\n\nexport type OpenedPdf = { bytes: Uint8Array; sha256: string; pdfjs: PdfjsLike; doc: PdfDocumentLike; destroy(): Promise<void> }\n\nfunction mapPdfjsError(err: unknown): IdentityDocumentError {\n const name = (err as { name?: string } | null)?.name ?? ''\n if (name === 'PasswordException') return new IdentityDocumentError('password', 'The PDF is password protected', { cause: err })\n if (name === 'InvalidPDFException') return new IdentityDocumentError('unreadable', 'The PDF is corrupt or unsupported', { cause: err, reason: 'invalid' })\n return new IdentityDocumentError('unreadable', 'The PDF could not be read', { cause: err })\n}\n\n/** Validates the file, opens it with pdf.js and enforces the limits. The caller must `destroy()`. */\nexport async function openPdf(source: PdfSource, options: ReadPdfOptions = {}): Promise<OpenedPdf> {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES\n const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n if (sizeOf(source) > maxBytes) throw new IdentityDocumentError('too_large', `The file is larger than ${maxBytes} bytes`, { reason: 'bytes' })\n const bytes = await toBytes(source)\n if (bytes.byteLength > maxBytes) throw new IdentityDocumentError('too_large', `The file is larger than ${maxBytes} bytes`, { reason: 'bytes' })\n if (!hasPdfSignature(bytes)) throw new IdentityDocumentError('not_pdf', 'The file is not a PDF')\n const sha256 = await sha256Hex(bytes)\n if (options.signal?.aborted) throw new IdentityDocumentError('unreadable', 'Aborted', { reason: 'aborted' })\n\n const pdfjs = await loadPdfjs(options.workerSrc)\n // pdf.js takes ownership of `data` (it transfers it to the worker): give it a copy.\n const task = pdfjs.getDocument({\n data: bytes.slice(),\n isEvalSupported: false,\n enableXfa: false,\n useSystemFonts: false,\n disableAutoFetch: true,\n disableStream: true,\n useWorkerFetch: false,\n verbosity: 0,\n })\n task.promise.catch(() => undefined)\n let doc: PdfDocumentLike | undefined\n const destroy = async () => {\n try {\n await (doc?.destroy ? doc.destroy() : task.destroy())\n } catch {\n /* already gone */\n }\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n const limit = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new IdentityDocumentError('unreadable', `Reading took longer than ${timeoutMs} ms`, { reason: 'timeout' })), timeoutMs)\n if (options.signal) {\n onAbort = () => reject(new IdentityDocumentError('unreadable', 'Aborted', { reason: 'aborted' }))\n options.signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n const cleanup = () => {\n if (timer) clearTimeout(timer)\n if (onAbort) options.signal?.removeEventListener('abort', onAbort)\n }\n try {\n doc = await Promise.race([task.promise, limit])\n if (doc.numPages > maxPages) throw new IdentityDocumentError('too_large', `The PDF has more than ${maxPages} pages`, { reason: 'pages' })\n cleanup()\n // The deadline covers `readOpened` too: keep a fresh one there.\n return { bytes, sha256, pdfjs, doc, destroy }\n } catch (err) {\n cleanup()\n await destroy()\n throw err instanceof IdentityDocumentError ? err : mapPdfjsError(err)\n }\n}\n\ntype Item = { str?: string; transform?: number[]; hasEOL?: boolean }\n\n/** Joins the text items of a page into visual lines (top to bottom, left to right). */\nexport function itemsToLines(items: Item[]): string {\n const rows: { y: number; parts: { x: number; s: string }[] }[] = []\n for (const it of items) {\n const s = it.str\n if (!s || !s.trim()) continue\n const x = it.transform?.[4] ?? 0\n const y = it.transform?.[5] ?? 0\n const row = rows.find((r) => Math.abs(r.y - y) <= 2)\n if (row) row.parts.push({ x, s })\n else rows.push({ y, parts: [{ x, s }] })\n }\n rows.sort((a, b) => b.y - a.y)\n return rows.map((r) => r.parts.sort((a, b) => a.x - b.x).map((p) => p.s.trim()).join(' ')).join('\\n')\n}\n\n/**\n * Text of a PDF, in the browser or in Node, with pdf.js (legacy build, `isEvalSupported: false`) imported on\n * demand. The file is read in memory: nothing is uploaded, written or logged. Throws `IdentityDocumentError`\n * (`too_large`, `not_pdf`, `unreadable`, `no_text`, `password`). In browsers pass `workerSrc`.\n */\nexport async function readPdfText(source: PdfSource, options: ReadPdfOptions = {}): Promise<PdfTextResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const opened = await openPdf(source, options)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const read = (async () => {\n const pages: string[] = []\n for (let n = 1; n <= opened.doc.numPages; n++) {\n const page = await opened.doc.getPage(n)\n pages.push(itemsToLines((await page.getTextContent()).items))\n page.cleanup?.()\n }\n return pages\n })()\n const limit = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new IdentityDocumentError('unreadable', `Reading took longer than ${timeoutMs} ms`, { reason: 'timeout' })), timeoutMs)\n })\n const pages = await Promise.race([read, limit])\n const text = pages.join('\\n\\n')\n if (text.replace(/\\s+/g, '').length < (options.minChars ?? 20)) throw new IdentityDocumentError('no_text', 'The PDF has no text layer')\n return { text, pages: pages.length, sha256: opened.sha256 }\n } catch (err) {\n throw err instanceof IdentityDocumentError ? err : mapPdfjsError(err)\n } finally {\n if (timer) clearTimeout(timer)\n await opened.destroy()\n }\n}\n","import { IdentityDocumentError } from './errors.js'\nimport { openPdf, type PdfSource, type PdfPageLike, type ReadPdfOptions } from './pdf.js'\n\nexport type DecodePdfQrOptions = ReadPdfOptions & {\n /** Pages to scan, 1-based (default `[1]`, then the last page). */\n pages?: number[]\n /** Render scale (default 2: enough for a printed QR). */\n scale?: number\n /** Your own decoder for the rendered image (e.g. a server canvas in Node). Returns the QR text or `null`. */\n decode?: (image: ImageData) => string | null | Promise<string | null>\n}\n\ntype CanvasLike = { width: number; height: number; getContext(kind: '2d'): unknown }\n\nfunction makeCanvas(width: number, height: number): CanvasLike | null {\n const g = globalThis as { OffscreenCanvas?: new (w: number, h: number) => CanvasLike; document?: { createElement(tag: 'canvas'): CanvasLike } }\n if (g.OffscreenCanvas) return new g.OffscreenCanvas(width, height)\n if (g.document) {\n const c = g.document.createElement('canvas')\n c.width = width\n c.height = height\n return c\n }\n return null\n}\n\nasync function decodeImage(image: ImageData, canvas: CanvasLike, custom?: DecodePdfQrOptions['decode']): Promise<string | null> {\n if (custom) return (await custom(image)) ?? null\n const Detector = (globalThis as { BarcodeDetector?: new (o: { formats: string[] }) => { detect(i: unknown): Promise<{ rawValue: string }[]> } }).BarcodeDetector\n if (Detector) {\n try {\n const found = await new Detector({ formats: ['qr_code'] }).detect(canvas)\n if (found[0]?.rawValue) return found[0].rawValue\n } catch {\n /* fall through to jsQR */\n }\n }\n try {\n const mod = (await import('jsqr')) as unknown as { default: (d: Uint8ClampedArray, w: number, h: number) => { data: string } | null }\n return mod.default(image.data, image.width, image.height)?.data ?? null\n } catch {\n return null\n }\n}\n\nasync function scan(page: PdfPageLike, scale: number, custom?: DecodePdfQrOptions['decode']): Promise<string | null> {\n const viewport = page.getViewport({ scale })\n const canvas = makeCanvas(Math.ceil(viewport.width), Math.ceil(viewport.height))\n if (!canvas && !custom) return null\n const c = canvas ?? { width: Math.ceil(viewport.width), height: Math.ceil(viewport.height), getContext: () => null }\n const context = c.getContext('2d') as { getImageData(x: number, y: number, w: number, h: number): ImageData } | null\n if (!context) return null\n await page.render({ canvasContext: context, viewport }).promise\n return decodeImage(context.getImageData(0, 0, c.width, c.height), c, custom)\n}\n\n/**\n * Text of the first QR code found in a PDF (the document's validator URL), or `null`. Best effort: it needs a\n * canvas (browsers; Node has none unless you pass `decode` with your own), and `BarcodeDetector` or the\n * optional `jsqr` package, both loaded on demand. Anything that goes wrong yields `null`, except the\n * `IdentityDocumentError`s of opening the file (`too_large`, `not_pdf`, `password`, `unreadable`).\n */\nexport async function decodePdfQr(source: PdfSource, options: DecodePdfQrOptions = {}): Promise<string | null> {\n const opened = await openPdf(source, options)\n try {\n const last = opened.doc.numPages\n const wanted = options.pages ?? [1, last]\n const pages = [...new Set(wanted)].filter((n) => n >= 1 && n <= last)\n for (const n of pages) {\n try {\n const page = await opened.doc.getPage(n)\n const found = await scan(page, options.scale ?? 2, options.decode)\n page.cleanup?.()\n if (found) return found\n } catch (err) {\n if (err instanceof IdentityDocumentError) throw err\n }\n }\n return null\n } finally {\n await opened.destroy()\n }\n}\n"]}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { U as FiscalDocumentSource, aR as RegionFiscalEntry, Z as IdentityDocumentSpec, T as FiscalDocumentEvidence, aS as RegionFiscalId, $ as IdentityRulesV1 } from './types-C-Ley-Mt.cjs';
|
|
2
|
+
export { Y as IdentityCapture, _ as IdentityFieldRule, a0 as IdentityStrategy } from './types-C-Ley-Mt.cjs';
|
|
3
|
+
import './geo.cjs';
|
|
4
|
+
|
|
5
|
+
/** A value read from a document: text, or the codes of a catalog (`multiple` fields). */
|
|
6
|
+
type ExtractedValue = string | string[];
|
|
7
|
+
/** Catalogs `catalog_phrases` matches against, by name. See `catalogsFromRegion`. */
|
|
8
|
+
type IdentityCatalogs = Record<string, RegionFiscalEntry[]>;
|
|
9
|
+
type ExtractOptions = {
|
|
10
|
+
/** Catalogs for `catalog_phrases`. Pass `catalogsFromRegion(region.fiscal_id)`. */
|
|
11
|
+
catalogs?: IdentityCatalogs;
|
|
12
|
+
/** The URL the QR of the document encodes (`decodePdfQr`). */
|
|
13
|
+
qr?: string | null;
|
|
14
|
+
/** Clock for the freshness check (default `new Date()`). */
|
|
15
|
+
now?: Date;
|
|
16
|
+
};
|
|
17
|
+
type IdentityExtraction = {
|
|
18
|
+
/** `IdentityDocumentSpec.kind`. */
|
|
19
|
+
kind: string;
|
|
20
|
+
/** `rules@1` or `plugin:<id>`. */
|
|
21
|
+
extractor: string;
|
|
22
|
+
/**
|
|
23
|
+
* What was read, by field (`multiple` fields are arrays). NEVER contains a `discard_fields` field.
|
|
24
|
+
* Conventional names: `tax_id`, `legal_name`, `postal_code`, `tax_regime`, `document_id`, `issued_on`.
|
|
25
|
+
*/
|
|
26
|
+
fields: Record<string, ExtractedValue>;
|
|
27
|
+
/** Where each field came from: the document text or its QR. */
|
|
28
|
+
sources: Record<string, 'text' | 'qr'>;
|
|
29
|
+
/** Required fields that were not found. Show them empty for the buyer to fill in. */
|
|
30
|
+
missing: string[];
|
|
31
|
+
/** Names (never values) of the fields the spec discards: the store does not keep them, and the UI can say so. */
|
|
32
|
+
discarded: string[];
|
|
33
|
+
/**
|
|
34
|
+
* `match`: every field present in both the text and the QR agrees (`null`: nothing to compare). `canonical`: the
|
|
35
|
+
* rules' `qr_canonical` URL rebuilt from what the QR carried, even if the reader garbled it; `''` when none.
|
|
36
|
+
*/
|
|
37
|
+
qr: {
|
|
38
|
+
match: boolean | null;
|
|
39
|
+
canonical: string;
|
|
40
|
+
};
|
|
41
|
+
/** `issued_on` is older than `freshness_days`. `null` when it cannot be told. */
|
|
42
|
+
stale: boolean | null;
|
|
43
|
+
age_days: number | null;
|
|
44
|
+
};
|
|
45
|
+
/** Plugin extractor of a country whose document cannot be described with rules. Synchronous and pure. */
|
|
46
|
+
type IdentityExtractorFn = (text: string, spec: IdentityDocumentSpec, options: ExtractOptions) => {
|
|
47
|
+
fields: Record<string, ExtractedValue>;
|
|
48
|
+
sources?: Record<string, 'text' | 'qr'>;
|
|
49
|
+
qr_match?: boolean | null;
|
|
50
|
+
missing?: string[];
|
|
51
|
+
};
|
|
52
|
+
type EvidenceInput = {
|
|
53
|
+
/** SHA-256 of the file (`PdfTextResult.sha256`). */
|
|
54
|
+
sha256?: string | null;
|
|
55
|
+
source: FiscalDocumentSource;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Longest text the engine reads (a one-page document is a few thousand characters). */
|
|
59
|
+
declare const MAX_TEXT_LENGTH = 400000;
|
|
60
|
+
/** Thrown for a spec that cannot run (unknown engine, rules that do not validate, no extractor registered). */
|
|
61
|
+
declare class IdentityRulesError extends Error {
|
|
62
|
+
readonly name = "IdentityRulesError";
|
|
63
|
+
}
|
|
64
|
+
/** Checks rules are well formed and portable; no rule may produce a `discard` field. Throws `IdentityRulesError`. */
|
|
65
|
+
declare function validateRules(rules: IdentityRulesV1, discard?: string[]): void;
|
|
66
|
+
/**
|
|
67
|
+
* Reads an identity document (the text of a PDF, `readPdfText`) with the rules of its spec: the TypeScript twin of
|
|
68
|
+
* the reference interpreter of the region packs. Generic, the country is data. `discard_fields` never appear in
|
|
69
|
+
* the output. Pure and synchronous; a text that does not match yields `missing`, never an exception; only a spec
|
|
70
|
+
* that cannot run throws `IdentityRulesError`.
|
|
71
|
+
*/
|
|
72
|
+
declare function extractIdentityDocument(text: string, spec: IdentityDocumentSpec, options?: ExtractOptions): IdentityExtraction;
|
|
73
|
+
/** The catalogs `catalog_phrases` rules name, from the region: `fiscal_regime` and `invoice_use`. */
|
|
74
|
+
declare function catalogsFromRegion(fiscalId: Pick<RegionFiscalId, 'regimes' | 'invoice_uses'>): IdentityCatalogs;
|
|
75
|
+
/**
|
|
76
|
+
* The evidence to send with the fiscal data (`InvoiceRequest.document`): where it came from and nothing of the
|
|
77
|
+
* document. `source` is `pdf_client` in the browser, `pdf_server` when a server read it, `manual` for typed data.
|
|
78
|
+
*/
|
|
79
|
+
declare function buildDocumentEvidence(extraction: IdentityExtraction, input: EvidenceInput): FiscalDocumentEvidence;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Registers the extractor of a document the `rules@1` engine cannot describe (a country whose document needs
|
|
83
|
+
* code). `key` is the document `kind` (`XX:doc`) or the `<id>` of a spec with `engine: 'plugin:<id>'`; the id
|
|
84
|
+
* wins. The server-side validator stays the region's: a plugin only reads text. Replaces a previous one.
|
|
85
|
+
* Returns a function that unregisters it.
|
|
86
|
+
*/
|
|
87
|
+
declare function registerIdentityExtractor(key: string, fn: IdentityExtractorFn): () => void;
|
|
88
|
+
|
|
89
|
+
/** What `readPdfText` accepts: a browser `File`/`Blob`, or bytes (Node `Buffer` included). */
|
|
90
|
+
type PdfSource = Blob | ArrayBuffer | ArrayBufferView;
|
|
91
|
+
type ReadPdfOptions = {
|
|
92
|
+
/** Reject files larger than this (default 5 MiB). */
|
|
93
|
+
maxBytes?: number;
|
|
94
|
+
/** Reject documents with more pages than this (default 6). */
|
|
95
|
+
maxPages?: number;
|
|
96
|
+
/** Give up after this many ms (default 3000). */
|
|
97
|
+
timeoutMs?: number;
|
|
98
|
+
/** Fewer non-space characters than this means "no text layer" (default 20). */
|
|
99
|
+
minChars?: number;
|
|
100
|
+
/**
|
|
101
|
+
* URL of the pdf.js worker (`pdf.worker.mjs` from `pdfjs-dist/legacy/build`) that YOUR site serves. Required in
|
|
102
|
+
* browsers (there is deliberately no default and no CDN); ignored in Node, which needs no worker file.
|
|
103
|
+
*/
|
|
104
|
+
workerSrc?: string;
|
|
105
|
+
/** Aborts the read. */
|
|
106
|
+
signal?: AbortSignal;
|
|
107
|
+
};
|
|
108
|
+
type PdfTextResult = {
|
|
109
|
+
/** Text of all pages, one line per visual line, pages separated by a blank line. */
|
|
110
|
+
text: string;
|
|
111
|
+
pages: number;
|
|
112
|
+
/** SHA-256 of the file as received, lowercase hex (evidence for `FiscalDocumentEvidence.sha256`). */
|
|
113
|
+
sha256: string;
|
|
114
|
+
};
|
|
115
|
+
/** The slice of pdf.js these helpers use. */
|
|
116
|
+
type PdfjsLike = {
|
|
117
|
+
getDocument(src: Record<string, unknown>): {
|
|
118
|
+
promise: Promise<PdfDocumentLike>;
|
|
119
|
+
destroy(): Promise<void> | void;
|
|
120
|
+
};
|
|
121
|
+
GlobalWorkerOptions?: {
|
|
122
|
+
workerSrc: string;
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
type PdfDocumentLike = {
|
|
126
|
+
numPages: number;
|
|
127
|
+
getPage(n: number): Promise<PdfPageLike>;
|
|
128
|
+
destroy?(): Promise<void> | void;
|
|
129
|
+
};
|
|
130
|
+
type PdfPageLike = {
|
|
131
|
+
getTextContent(): Promise<{
|
|
132
|
+
items: Array<{
|
|
133
|
+
str?: string;
|
|
134
|
+
transform?: number[];
|
|
135
|
+
hasEOL?: boolean;
|
|
136
|
+
}>;
|
|
137
|
+
}>;
|
|
138
|
+
getViewport(o: {
|
|
139
|
+
scale: number;
|
|
140
|
+
}): {
|
|
141
|
+
width: number;
|
|
142
|
+
height: number;
|
|
143
|
+
};
|
|
144
|
+
render(o: {
|
|
145
|
+
canvasContext: unknown;
|
|
146
|
+
viewport: unknown;
|
|
147
|
+
}): {
|
|
148
|
+
promise: Promise<void>;
|
|
149
|
+
};
|
|
150
|
+
cleanup?(): void;
|
|
151
|
+
};
|
|
152
|
+
declare const DEFAULT_MAX_BYTES: number;
|
|
153
|
+
declare const DEFAULT_MAX_PAGES = 6;
|
|
154
|
+
declare const DEFAULT_TIMEOUT_MS = 3000;
|
|
155
|
+
/**
|
|
156
|
+
* Replaces how pdf.js is loaded (tests, or a bundler that needs its own import). By default the legacy build of
|
|
157
|
+
* `pdfjs-dist` is imported on first use, so it costs nothing until a document is read.
|
|
158
|
+
*/
|
|
159
|
+
declare function setPdfjsLoader(loader: (() => Promise<PdfjsLike>) | undefined): void;
|
|
160
|
+
/**
|
|
161
|
+
* Text of a PDF, in the browser or in Node, with pdf.js (legacy build, `isEvalSupported: false`) imported on
|
|
162
|
+
* demand. The file is read in memory: nothing is uploaded, written or logged. Throws `IdentityDocumentError`
|
|
163
|
+
* (`too_large`, `not_pdf`, `unreadable`, `no_text`, `password`). In browsers pass `workerSrc`.
|
|
164
|
+
*/
|
|
165
|
+
declare function readPdfText(source: PdfSource, options?: ReadPdfOptions): Promise<PdfTextResult>;
|
|
166
|
+
|
|
167
|
+
type DecodePdfQrOptions = ReadPdfOptions & {
|
|
168
|
+
/** Pages to scan, 1-based (default `[1]`, then the last page). */
|
|
169
|
+
pages?: number[];
|
|
170
|
+
/** Render scale (default 2: enough for a printed QR). */
|
|
171
|
+
scale?: number;
|
|
172
|
+
/** Your own decoder for the rendered image (e.g. a server canvas in Node). Returns the QR text or `null`. */
|
|
173
|
+
decode?: (image: ImageData) => string | null | Promise<string | null>;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Text of the first QR code found in a PDF (the document's validator URL), or `null`. Best effort: it needs a
|
|
177
|
+
* canvas (browsers; Node has none unless you pass `decode` with your own), and `BarcodeDetector` or the
|
|
178
|
+
* optional `jsqr` package, both loaded on demand. Anything that goes wrong yields `null`, except the
|
|
179
|
+
* `IdentityDocumentError`s of opening the file (`too_large`, `not_pdf`, `password`, `unreadable`).
|
|
180
|
+
*/
|
|
181
|
+
declare function decodePdfQr(source: PdfSource, options?: DecodePdfQrOptions): Promise<string | null>;
|
|
182
|
+
|
|
183
|
+
type IdentityDocumentErrorCode =
|
|
184
|
+
/** Over `maxBytes`, or more than `maxPages` pages. */
|
|
185
|
+
'too_large'
|
|
186
|
+
/** Does not start with `%PDF-`. */
|
|
187
|
+
| 'not_pdf'
|
|
188
|
+
/** Corrupt, unsupported, or it took longer than `timeoutMs`. */
|
|
189
|
+
| 'unreadable'
|
|
190
|
+
/** A PDF without a text layer (a scan): ask for manual entry. */
|
|
191
|
+
| 'no_text'
|
|
192
|
+
/** Encrypted: it needs a password the buyer has not given. */
|
|
193
|
+
| 'password';
|
|
194
|
+
/** Why a document could not be read. `code` is stable; `message` is for logs (English) and never holds document text. */
|
|
195
|
+
declare class IdentityDocumentError extends Error {
|
|
196
|
+
readonly name = "IdentityDocumentError";
|
|
197
|
+
readonly code: IdentityDocumentErrorCode;
|
|
198
|
+
/** Finer cause: `bytes`, `pages`, `timeout`, `aborted`... */
|
|
199
|
+
readonly reason: string | undefined;
|
|
200
|
+
constructor(code: IdentityDocumentErrorCode, message: string, options?: {
|
|
201
|
+
reason?: string;
|
|
202
|
+
cause?: unknown;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
declare function isIdentityDocumentError(err: unknown): err is IdentityDocumentError;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Text helpers of the rules engine. Pure; no DOM, no network.
|
|
209
|
+
*/
|
|
210
|
+
/** Lowercases, strips Latin accents and collapses whitespace; the base of every phrase comparison (punctuation is kept). */
|
|
211
|
+
declare function foldText(s: string): string;
|
|
212
|
+
/** Hex SHA-256 of the bytes (Web Crypto: browsers, Node 20+, edge runtimes). */
|
|
213
|
+
declare function sha256Hex(data: ArrayBuffer | Uint8Array): Promise<string>;
|
|
214
|
+
|
|
215
|
+
export { DEFAULT_MAX_BYTES, DEFAULT_MAX_PAGES, DEFAULT_TIMEOUT_MS, type DecodePdfQrOptions, type EvidenceInput, type ExtractOptions, type ExtractedValue, FiscalDocumentEvidence, type IdentityCatalogs, IdentityDocumentError, type IdentityDocumentErrorCode, IdentityDocumentSpec, type IdentityExtraction, type IdentityExtractorFn, IdentityRulesError, IdentityRulesV1, MAX_TEXT_LENGTH, type PdfSource, type PdfTextResult, type PdfjsLike, type ReadPdfOptions, buildDocumentEvidence, catalogsFromRegion, decodePdfQr, extractIdentityDocument, foldText, isIdentityDocumentError, readPdfText, registerIdentityExtractor, setPdfjsLoader, sha256Hex, validateRules };
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { U as FiscalDocumentSource, aR as RegionFiscalEntry, Z as IdentityDocumentSpec, T as FiscalDocumentEvidence, aS as RegionFiscalId, $ as IdentityRulesV1 } from './types-D7UJxrba.js';
|
|
2
|
+
export { Y as IdentityCapture, _ as IdentityFieldRule, a0 as IdentityStrategy } from './types-D7UJxrba.js';
|
|
3
|
+
import './geo.js';
|
|
4
|
+
|
|
5
|
+
/** A value read from a document: text, or the codes of a catalog (`multiple` fields). */
|
|
6
|
+
type ExtractedValue = string | string[];
|
|
7
|
+
/** Catalogs `catalog_phrases` matches against, by name. See `catalogsFromRegion`. */
|
|
8
|
+
type IdentityCatalogs = Record<string, RegionFiscalEntry[]>;
|
|
9
|
+
type ExtractOptions = {
|
|
10
|
+
/** Catalogs for `catalog_phrases`. Pass `catalogsFromRegion(region.fiscal_id)`. */
|
|
11
|
+
catalogs?: IdentityCatalogs;
|
|
12
|
+
/** The URL the QR of the document encodes (`decodePdfQr`). */
|
|
13
|
+
qr?: string | null;
|
|
14
|
+
/** Clock for the freshness check (default `new Date()`). */
|
|
15
|
+
now?: Date;
|
|
16
|
+
};
|
|
17
|
+
type IdentityExtraction = {
|
|
18
|
+
/** `IdentityDocumentSpec.kind`. */
|
|
19
|
+
kind: string;
|
|
20
|
+
/** `rules@1` or `plugin:<id>`. */
|
|
21
|
+
extractor: string;
|
|
22
|
+
/**
|
|
23
|
+
* What was read, by field (`multiple` fields are arrays). NEVER contains a `discard_fields` field.
|
|
24
|
+
* Conventional names: `tax_id`, `legal_name`, `postal_code`, `tax_regime`, `document_id`, `issued_on`.
|
|
25
|
+
*/
|
|
26
|
+
fields: Record<string, ExtractedValue>;
|
|
27
|
+
/** Where each field came from: the document text or its QR. */
|
|
28
|
+
sources: Record<string, 'text' | 'qr'>;
|
|
29
|
+
/** Required fields that were not found. Show them empty for the buyer to fill in. */
|
|
30
|
+
missing: string[];
|
|
31
|
+
/** Names (never values) of the fields the spec discards: the store does not keep them, and the UI can say so. */
|
|
32
|
+
discarded: string[];
|
|
33
|
+
/**
|
|
34
|
+
* `match`: every field present in both the text and the QR agrees (`null`: nothing to compare). `canonical`: the
|
|
35
|
+
* rules' `qr_canonical` URL rebuilt from what the QR carried, even if the reader garbled it; `''` when none.
|
|
36
|
+
*/
|
|
37
|
+
qr: {
|
|
38
|
+
match: boolean | null;
|
|
39
|
+
canonical: string;
|
|
40
|
+
};
|
|
41
|
+
/** `issued_on` is older than `freshness_days`. `null` when it cannot be told. */
|
|
42
|
+
stale: boolean | null;
|
|
43
|
+
age_days: number | null;
|
|
44
|
+
};
|
|
45
|
+
/** Plugin extractor of a country whose document cannot be described with rules. Synchronous and pure. */
|
|
46
|
+
type IdentityExtractorFn = (text: string, spec: IdentityDocumentSpec, options: ExtractOptions) => {
|
|
47
|
+
fields: Record<string, ExtractedValue>;
|
|
48
|
+
sources?: Record<string, 'text' | 'qr'>;
|
|
49
|
+
qr_match?: boolean | null;
|
|
50
|
+
missing?: string[];
|
|
51
|
+
};
|
|
52
|
+
type EvidenceInput = {
|
|
53
|
+
/** SHA-256 of the file (`PdfTextResult.sha256`). */
|
|
54
|
+
sha256?: string | null;
|
|
55
|
+
source: FiscalDocumentSource;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Longest text the engine reads (a one-page document is a few thousand characters). */
|
|
59
|
+
declare const MAX_TEXT_LENGTH = 400000;
|
|
60
|
+
/** Thrown for a spec that cannot run (unknown engine, rules that do not validate, no extractor registered). */
|
|
61
|
+
declare class IdentityRulesError extends Error {
|
|
62
|
+
readonly name = "IdentityRulesError";
|
|
63
|
+
}
|
|
64
|
+
/** Checks rules are well formed and portable; no rule may produce a `discard` field. Throws `IdentityRulesError`. */
|
|
65
|
+
declare function validateRules(rules: IdentityRulesV1, discard?: string[]): void;
|
|
66
|
+
/**
|
|
67
|
+
* Reads an identity document (the text of a PDF, `readPdfText`) with the rules of its spec: the TypeScript twin of
|
|
68
|
+
* the reference interpreter of the region packs. Generic, the country is data. `discard_fields` never appear in
|
|
69
|
+
* the output. Pure and synchronous; a text that does not match yields `missing`, never an exception; only a spec
|
|
70
|
+
* that cannot run throws `IdentityRulesError`.
|
|
71
|
+
*/
|
|
72
|
+
declare function extractIdentityDocument(text: string, spec: IdentityDocumentSpec, options?: ExtractOptions): IdentityExtraction;
|
|
73
|
+
/** The catalogs `catalog_phrases` rules name, from the region: `fiscal_regime` and `invoice_use`. */
|
|
74
|
+
declare function catalogsFromRegion(fiscalId: Pick<RegionFiscalId, 'regimes' | 'invoice_uses'>): IdentityCatalogs;
|
|
75
|
+
/**
|
|
76
|
+
* The evidence to send with the fiscal data (`InvoiceRequest.document`): where it came from and nothing of the
|
|
77
|
+
* document. `source` is `pdf_client` in the browser, `pdf_server` when a server read it, `manual` for typed data.
|
|
78
|
+
*/
|
|
79
|
+
declare function buildDocumentEvidence(extraction: IdentityExtraction, input: EvidenceInput): FiscalDocumentEvidence;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Registers the extractor of a document the `rules@1` engine cannot describe (a country whose document needs
|
|
83
|
+
* code). `key` is the document `kind` (`XX:doc`) or the `<id>` of a spec with `engine: 'plugin:<id>'`; the id
|
|
84
|
+
* wins. The server-side validator stays the region's: a plugin only reads text. Replaces a previous one.
|
|
85
|
+
* Returns a function that unregisters it.
|
|
86
|
+
*/
|
|
87
|
+
declare function registerIdentityExtractor(key: string, fn: IdentityExtractorFn): () => void;
|
|
88
|
+
|
|
89
|
+
/** What `readPdfText` accepts: a browser `File`/`Blob`, or bytes (Node `Buffer` included). */
|
|
90
|
+
type PdfSource = Blob | ArrayBuffer | ArrayBufferView;
|
|
91
|
+
type ReadPdfOptions = {
|
|
92
|
+
/** Reject files larger than this (default 5 MiB). */
|
|
93
|
+
maxBytes?: number;
|
|
94
|
+
/** Reject documents with more pages than this (default 6). */
|
|
95
|
+
maxPages?: number;
|
|
96
|
+
/** Give up after this many ms (default 3000). */
|
|
97
|
+
timeoutMs?: number;
|
|
98
|
+
/** Fewer non-space characters than this means "no text layer" (default 20). */
|
|
99
|
+
minChars?: number;
|
|
100
|
+
/**
|
|
101
|
+
* URL of the pdf.js worker (`pdf.worker.mjs` from `pdfjs-dist/legacy/build`) that YOUR site serves. Required in
|
|
102
|
+
* browsers (there is deliberately no default and no CDN); ignored in Node, which needs no worker file.
|
|
103
|
+
*/
|
|
104
|
+
workerSrc?: string;
|
|
105
|
+
/** Aborts the read. */
|
|
106
|
+
signal?: AbortSignal;
|
|
107
|
+
};
|
|
108
|
+
type PdfTextResult = {
|
|
109
|
+
/** Text of all pages, one line per visual line, pages separated by a blank line. */
|
|
110
|
+
text: string;
|
|
111
|
+
pages: number;
|
|
112
|
+
/** SHA-256 of the file as received, lowercase hex (evidence for `FiscalDocumentEvidence.sha256`). */
|
|
113
|
+
sha256: string;
|
|
114
|
+
};
|
|
115
|
+
/** The slice of pdf.js these helpers use. */
|
|
116
|
+
type PdfjsLike = {
|
|
117
|
+
getDocument(src: Record<string, unknown>): {
|
|
118
|
+
promise: Promise<PdfDocumentLike>;
|
|
119
|
+
destroy(): Promise<void> | void;
|
|
120
|
+
};
|
|
121
|
+
GlobalWorkerOptions?: {
|
|
122
|
+
workerSrc: string;
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
type PdfDocumentLike = {
|
|
126
|
+
numPages: number;
|
|
127
|
+
getPage(n: number): Promise<PdfPageLike>;
|
|
128
|
+
destroy?(): Promise<void> | void;
|
|
129
|
+
};
|
|
130
|
+
type PdfPageLike = {
|
|
131
|
+
getTextContent(): Promise<{
|
|
132
|
+
items: Array<{
|
|
133
|
+
str?: string;
|
|
134
|
+
transform?: number[];
|
|
135
|
+
hasEOL?: boolean;
|
|
136
|
+
}>;
|
|
137
|
+
}>;
|
|
138
|
+
getViewport(o: {
|
|
139
|
+
scale: number;
|
|
140
|
+
}): {
|
|
141
|
+
width: number;
|
|
142
|
+
height: number;
|
|
143
|
+
};
|
|
144
|
+
render(o: {
|
|
145
|
+
canvasContext: unknown;
|
|
146
|
+
viewport: unknown;
|
|
147
|
+
}): {
|
|
148
|
+
promise: Promise<void>;
|
|
149
|
+
};
|
|
150
|
+
cleanup?(): void;
|
|
151
|
+
};
|
|
152
|
+
declare const DEFAULT_MAX_BYTES: number;
|
|
153
|
+
declare const DEFAULT_MAX_PAGES = 6;
|
|
154
|
+
declare const DEFAULT_TIMEOUT_MS = 3000;
|
|
155
|
+
/**
|
|
156
|
+
* Replaces how pdf.js is loaded (tests, or a bundler that needs its own import). By default the legacy build of
|
|
157
|
+
* `pdfjs-dist` is imported on first use, so it costs nothing until a document is read.
|
|
158
|
+
*/
|
|
159
|
+
declare function setPdfjsLoader(loader: (() => Promise<PdfjsLike>) | undefined): void;
|
|
160
|
+
/**
|
|
161
|
+
* Text of a PDF, in the browser or in Node, with pdf.js (legacy build, `isEvalSupported: false`) imported on
|
|
162
|
+
* demand. The file is read in memory: nothing is uploaded, written or logged. Throws `IdentityDocumentError`
|
|
163
|
+
* (`too_large`, `not_pdf`, `unreadable`, `no_text`, `password`). In browsers pass `workerSrc`.
|
|
164
|
+
*/
|
|
165
|
+
declare function readPdfText(source: PdfSource, options?: ReadPdfOptions): Promise<PdfTextResult>;
|
|
166
|
+
|
|
167
|
+
type DecodePdfQrOptions = ReadPdfOptions & {
|
|
168
|
+
/** Pages to scan, 1-based (default `[1]`, then the last page). */
|
|
169
|
+
pages?: number[];
|
|
170
|
+
/** Render scale (default 2: enough for a printed QR). */
|
|
171
|
+
scale?: number;
|
|
172
|
+
/** Your own decoder for the rendered image (e.g. a server canvas in Node). Returns the QR text or `null`. */
|
|
173
|
+
decode?: (image: ImageData) => string | null | Promise<string | null>;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Text of the first QR code found in a PDF (the document's validator URL), or `null`. Best effort: it needs a
|
|
177
|
+
* canvas (browsers; Node has none unless you pass `decode` with your own), and `BarcodeDetector` or the
|
|
178
|
+
* optional `jsqr` package, both loaded on demand. Anything that goes wrong yields `null`, except the
|
|
179
|
+
* `IdentityDocumentError`s of opening the file (`too_large`, `not_pdf`, `password`, `unreadable`).
|
|
180
|
+
*/
|
|
181
|
+
declare function decodePdfQr(source: PdfSource, options?: DecodePdfQrOptions): Promise<string | null>;
|
|
182
|
+
|
|
183
|
+
type IdentityDocumentErrorCode =
|
|
184
|
+
/** Over `maxBytes`, or more than `maxPages` pages. */
|
|
185
|
+
'too_large'
|
|
186
|
+
/** Does not start with `%PDF-`. */
|
|
187
|
+
| 'not_pdf'
|
|
188
|
+
/** Corrupt, unsupported, or it took longer than `timeoutMs`. */
|
|
189
|
+
| 'unreadable'
|
|
190
|
+
/** A PDF without a text layer (a scan): ask for manual entry. */
|
|
191
|
+
| 'no_text'
|
|
192
|
+
/** Encrypted: it needs a password the buyer has not given. */
|
|
193
|
+
| 'password';
|
|
194
|
+
/** Why a document could not be read. `code` is stable; `message` is for logs (English) and never holds document text. */
|
|
195
|
+
declare class IdentityDocumentError extends Error {
|
|
196
|
+
readonly name = "IdentityDocumentError";
|
|
197
|
+
readonly code: IdentityDocumentErrorCode;
|
|
198
|
+
/** Finer cause: `bytes`, `pages`, `timeout`, `aborted`... */
|
|
199
|
+
readonly reason: string | undefined;
|
|
200
|
+
constructor(code: IdentityDocumentErrorCode, message: string, options?: {
|
|
201
|
+
reason?: string;
|
|
202
|
+
cause?: unknown;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
declare function isIdentityDocumentError(err: unknown): err is IdentityDocumentError;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Text helpers of the rules engine. Pure; no DOM, no network.
|
|
209
|
+
*/
|
|
210
|
+
/** Lowercases, strips Latin accents and collapses whitespace; the base of every phrase comparison (punctuation is kept). */
|
|
211
|
+
declare function foldText(s: string): string;
|
|
212
|
+
/** Hex SHA-256 of the bytes (Web Crypto: browsers, Node 20+, edge runtimes). */
|
|
213
|
+
declare function sha256Hex(data: ArrayBuffer | Uint8Array): Promise<string>;
|
|
214
|
+
|
|
215
|
+
export { DEFAULT_MAX_BYTES, DEFAULT_MAX_PAGES, DEFAULT_TIMEOUT_MS, type DecodePdfQrOptions, type EvidenceInput, type ExtractOptions, type ExtractedValue, FiscalDocumentEvidence, type IdentityCatalogs, IdentityDocumentError, type IdentityDocumentErrorCode, IdentityDocumentSpec, type IdentityExtraction, type IdentityExtractorFn, IdentityRulesError, IdentityRulesV1, MAX_TEXT_LENGTH, type PdfSource, type PdfTextResult, type PdfjsLike, type ReadPdfOptions, buildDocumentEvidence, catalogsFromRegion, decodePdfQr, extractIdentityDocument, foldText, isIdentityDocumentError, readPdfText, registerIdentityExtractor, setPdfjsLoader, sha256Hex, validateRules };
|