nf-key-extractor 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +427 -0
- package/benchmarks/README.md +53 -0
- package/dist/cli.cjs +1665 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1644 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +1546 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +141 -0
- package/dist/index.d.ts +141 -0
- package/dist/index.js +1511 -0
- package/dist/index.js.map +1 -0
- package/package.json +90 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/pdf/render-page.ts","../src/recognition/barcode-reader.ts","../src/recognition/ocr-reader.ts","../src/extractor.ts","../src/validation/access-key.ts","../src/candidates/from-text.ts","../src/candidates/from-ocr.ts","../src/deadline.ts","../src/options.ts","../src/pdf/extract-text.ts","../src/pdf/load-input.ts","../src/pdf/open-document.ts","../src/scoring/merge-results.ts","../src/cli/run.ts","../src/cli.ts"],"sourcesContent":["import type { ExtractionErrorCode } from \"./types\";\n\nexport class ExtractionFailure extends Error {\n public readonly code: ExtractionErrorCode;\n\n public constructor(code: ExtractionErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ExtractionFailure\";\n this.code = code;\n }\n}\n\nexport function messageFromUnknown(error: unknown): string {\n return error instanceof Error ? error.message : \"Unknown processing error.\";\n}\n","import { ExtractionFailure } from \"../errors\";\nimport type { RenderRecipe } from \"../options\";\nimport type { PdfPageLike } from \"./types\";\n\nconst MAX_CANVAS_DIMENSION = 32_767;\n\nexport interface RenderedPage {\n width: number;\n height: number;\n appliedScale: number;\n rotation: number;\n getPixels(): Uint8ClampedArray;\n toPng(): Buffer;\n}\n\nexport async function renderPage(page: PdfPageLike, recipe: RenderRecipe, maxPixels: number): Promise<RenderedPage> {\n const { createCanvas } = await import(\"@napi-rs/canvas\");\n const rotation = (((page.rotate + recipe.rotation) % 360) + 360) % 360;\n let scale = recipe.scale;\n let viewport = page.getViewport({ scale, rotation });\n let width = 0;\n let height = 0;\n\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (!Number.isFinite(viewport.width) || !Number.isFinite(viewport.height) || viewport.width <= 0 || viewport.height <= 0) {\n throw new ExtractionFailure(\"INVALID_PDF\", \"A PDF page has invalid dimensions.\");\n }\n\n width = Math.max(1, Math.ceil(viewport.width));\n height = Math.max(1, Math.ceil(viewport.height));\n const allocatedPixels = width * height;\n if (width <= MAX_CANVAS_DIMENSION && height <= MAX_CANVAS_DIMENSION && allocatedPixels <= maxPixels) {\n break;\n }\n\n const hasSubpixelAxis = viewport.width < 1 || viewport.height < 1;\n const pixelFactor = hasSubpixelAxis ? maxPixels / allocatedPixels : Math.sqrt(maxPixels / allocatedPixels);\n const reduction = Math.min(pixelFactor, MAX_CANVAS_DIMENSION / width, MAX_CANVAS_DIMENSION / height) * 0.999;\n if (!Number.isFinite(reduction) || reduction <= 0 || reduction >= 1) {\n throw new ExtractionFailure(\"INVALID_PDF\", \"A PDF page exceeds the supported render dimensions.\");\n }\n scale *= reduction;\n viewport = page.getViewport({ scale, rotation });\n }\n\n if (width > MAX_CANVAS_DIMENSION || height > MAX_CANVAS_DIMENSION || width * height > maxPixels) {\n throw new ExtractionFailure(\"INVALID_PDF\", \"A PDF page exceeds the supported render dimensions.\");\n }\n const canvas = createCanvas(width, height);\n const context = canvas.getContext(\"2d\");\n context.fillStyle = \"#ffffff\";\n context.fillRect(0, 0, width, height);\n await page.render({\n canvas,\n canvasContext: context,\n viewport,\n intent: \"display\",\n background: \"#ffffff\",\n }).promise;\n let pixels: Uint8ClampedArray | null = null;\n\n return {\n width,\n height,\n appliedScale: scale,\n rotation,\n getPixels(): Uint8ClampedArray {\n pixels ??= context.getImageData(0, 0, width, height).data;\n return pixels;\n },\n toPng(): Buffer {\n return canvas.toBuffer(\"image/png\");\n },\n };\n}\n","import type { BinaryBitmap, DecodeHintType, LuminanceSource, Reader, RGBLuminanceSource } from \"@zxing/library\";\n\nimport type { RenderedPage } from \"../pdf/render-page\";\n\nexport interface DecodedBarcode {\n text: string;\n source: \"code128\" | \"qr-code\";\n}\n\nfunction scanRegions(source: RGBLuminanceSource, width: number, height: number): LuminanceSource[] {\n const regions: LuminanceSource[] = [source];\n const lowerRegionTop = Math.floor(height * 0.45);\n const rightRegionLeft = Math.floor(width * 0.45);\n const crops = [\n [0, 0, width, Math.min(height, Math.ceil(height * 0.55))],\n [0, lowerRegionTop, width, height - lowerRegionTop],\n [0, 0, Math.min(width, Math.ceil(width * 0.55)), height],\n [rightRegionLeft, 0, width - rightRegionLeft, height],\n ] as const;\n for (const [left, top, cropWidth, cropHeight] of crops) {\n if (cropWidth >= 32 && cropHeight >= 32) {\n regions.push(source.crop(left, top, cropWidth, cropHeight));\n }\n }\n return regions;\n}\n\nfunction decodeBitmap(reader: Reader, bitmap: BinaryBitmap, hints: Map<DecodeHintType, unknown>, source: DecodedBarcode[\"source\"]): DecodedBarcode | null {\n try {\n const result = reader.decode(bitmap, hints);\n return {\n text: result.getText(),\n source,\n };\n } catch {\n return null;\n } finally {\n reader.reset();\n }\n}\n\nexport async function readBarcodes(rendered: RenderedPage): Promise<DecodedBarcode[]> {\n const { BarcodeFormat, BinaryBitmap, Code128Reader, DecodeHintType, HybridBinarizer, InvertedLuminanceSource, QRCodeReader, RGBLuminanceSource } = await import(\"@zxing/library\");\n const hints = new Map<DecodeHintType, unknown>();\n hints.set(DecodeHintType.POSSIBLE_FORMATS, [BarcodeFormat.CODE_128, BarcodeFormat.QR_CODE]);\n hints.set(DecodeHintType.TRY_HARDER, true);\n\n const pixels = rendered.getPixels();\n const luminance = new Uint8ClampedArray(rendered.width * rendered.height);\n for (let pixel = 0, rgba = 0; pixel < luminance.length; pixel += 1, rgba += 4) {\n const red = pixels[rgba] ?? 255;\n const green = pixels[rgba + 1] ?? 255;\n const blue = pixels[rgba + 2] ?? 255;\n luminance[pixel] = (red + green * 2 + blue) / 4;\n }\n const source = new RGBLuminanceSource(luminance, rendered.width, rendered.height);\n const attempts: Array<{\n reader: Reader;\n source: DecodedBarcode[\"source\"];\n }> = [\n { reader: new Code128Reader(), source: \"code128\" },\n { reader: new QRCodeReader(), source: \"qr-code\" },\n ];\n\n const unique = new Map<string, DecodedBarcode>();\n const regions = scanRegions(source, rendered.width, rendered.height);\n for (const [regionIndex, region] of regions.entries()) {\n const candidateSources: LuminanceSource[] = [region];\n if (regionIndex === 0) {\n candidateSources.push(new InvertedLuminanceSource(region));\n }\n for (const attempt of attempts) {\n for (const candidateSource of candidateSources) {\n const result = decodeBitmap(attempt.reader, new BinaryBitmap(new HybridBinarizer(candidateSource)), hints, attempt.source);\n if (result !== null) {\n unique.set(`${result.source}:${result.text}`, result);\n }\n }\n }\n }\n return [...unique.values()];\n}\n","export interface OcrRecognition {\n text: string;\n confidence: number;\n}\n\nexport interface OcrSession {\n recognize(image: Buffer): Promise<OcrRecognition>;\n terminate(): Promise<void>;\n}\n\nexport async function createOcrSession(): Promise<OcrSession> {\n const [{ createWorker, OEM, PSM }, languageData] = await Promise.all([import(\"tesseract.js\"), import(\"@tesseract.js-data/eng\")]);\n const worker = await createWorker(\"eng\", OEM.LSTM_ONLY, {\n langPath: languageData.default.langPath,\n cacheMethod: \"none\",\n gzip: true,\n });\n try {\n await worker.setParameters({\n tessedit_char_whitelist: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",\n tessedit_pageseg_mode: PSM.SPARSE_TEXT,\n preserve_interword_spaces: \"1\",\n });\n } catch (error) {\n await worker.terminate().catch(() => undefined);\n throw error;\n }\n\n return {\n async recognize(image: Buffer): Promise<OcrRecognition> {\n const result = await worker.recognize(image);\n return {\n text: result.data.text,\n confidence: result.data.confidence,\n };\n },\n async terminate(): Promise<void> {\n await worker.terminate();\n },\n };\n}\n","import { performance } from \"node:perf_hooks\";\n\nimport { findCandidatesInDecodedValue, findCandidatesInText } from \"./candidates/from-text\";\nimport { findCandidatesInOcrText } from \"./candidates/from-ocr\";\nimport type { CandidateEvidence } from \"./candidates/types\";\nimport { WorkGuard } from \"./deadline\";\nimport { ExtractionFailure, messageFromUnknown } from \"./errors\";\nimport { getRenderRecipes, InvalidOptionsError, resolveOptions, type RenderRecipe, type ResolvedOptions } from \"./options\";\nimport { extractPageText, type ExtractedPageText } from \"./pdf/extract-text\";\nimport { loadPdfInput } from \"./pdf/load-input\";\nimport { openPdfDocument } from \"./pdf/open-document\";\nimport type { PdfHandle, PdfPageLike } from \"./pdf/types\";\nimport type { OcrSession } from \"./recognition/ocr-reader\";\nimport { mergeEvidence } from \"./scoring/merge-results\";\nimport type { ExtractOptions, ExtractedAccessKey, ExtractionErrorInfo, ExtractionMetadata, ExtractionResult, ExtractionStatus, PdfInput } from \"./types\";\n\ninterface MutableRunState {\n evidence: CandidateEvidence[];\n warnings: string[];\n pagesTotal: number;\n pagesProcessed: number;\n renderedPages: Set<number>;\n ocrPages: Set<number>;\n passesUsed: number;\n fileSizeBytes: number;\n complete: boolean;\n}\n\nfunction emptyState(): MutableRunState {\n return {\n evidence: [],\n warnings: [],\n pagesTotal: 0,\n pagesProcessed: 0,\n renderedPages: new Set(),\n ocrPages: new Set(),\n passesUsed: 0,\n fileSizeBytes: 0,\n complete: true,\n };\n}\n\nfunction textEvidence(pageText: ExtractedPageText, page: number): CandidateEvidence[] {\n const candidates = [...findCandidatesInText(pageText.orderedText, page), ...findCandidatesInText(pageText.visualLines.join(\"\\n\"), page)];\n const unique = new Map<string, CandidateEvidence>();\n for (const candidate of candidates) {\n const signature = `${candidate.accessKey}:${candidate.source}`;\n const current = unique.get(signature);\n if (current === undefined || (!current.nearLabel && candidate.nearLabel)) {\n unique.set(signature, candidate);\n }\n }\n return [...unique.values()];\n}\n\nfunction hasPageEvidence(evidence: CandidateEvidence[], page: number): boolean {\n return evidence.some((candidate) => candidate.page === page);\n}\n\nfunction metadata(options: ResolvedOptions, state: MutableRunState, startedAt: number): ExtractionMetadata {\n return {\n performance: options.performance,\n ocrMode: options.ocr,\n passesRequested: options.passes,\n passesUsed: state.passesUsed,\n pagesTotal: state.pagesTotal,\n pagesProcessed: state.pagesProcessed,\n pagesRendered: state.renderedPages.size,\n ocrPages: state.ocrPages.size,\n fileSizeBytes: state.fileSizeBytes,\n maxPixelsPerPage: options.maxPixelsPerPage,\n maxSourceImagePixels: options.maxSourceImagePixels,\n durationMs: Number((performance.now() - startedAt).toFixed(2)),\n complete: state.complete,\n confidenceVersion: \"1.0.0\",\n };\n}\n\nfunction resultFromState(options: ResolvedOptions, state: MutableRunState, startedAt: number, error: ExtractionErrorInfo | null = null): ExtractionResult {\n const results = mergeEvidence(state.evidence);\n let status: ExtractionStatus;\n if (error !== null) {\n status = results.length > 0 ? \"partial\" : \"error\";\n } else if (!state.complete) {\n status = \"partial\";\n } else {\n status = results.length > 0 ? \"success\" : \"not_found\";\n }\n const precisionScore = results.length === 0 ? 0 : Math.min(...results.map((candidate) => candidate.precisionScore));\n\n return {\n status,\n success: results.length > 0,\n precisionScore: Number(precisionScore.toFixed(3)),\n bestMatch: results[0] ?? null,\n results,\n metadata: metadata(options, state, startedAt),\n warnings: state.warnings,\n error,\n };\n}\n\nfunction invalidOptionsResult(error: InvalidOptionsError, startedAt: number): ExtractionResult {\n const options = resolveOptions();\n const state = emptyState();\n state.complete = false;\n return resultFromState(options, state, startedAt, {\n code: \"INVALID_OPTIONS\",\n message: error.message,\n });\n}\n\nasync function withPage<T>(handle: PdfHandle, pageNumber: number, work: (page: PdfPageLike) => Promise<T>): Promise<T> {\n const page = await handle.document.getPage(pageNumber);\n try {\n return await work(page);\n } finally {\n page.cleanup();\n }\n}\n\nfunction ocrRecipes(recipes: RenderRecipe[], options: ResolvedOptions): RenderRecipe[] {\n const unrotated = recipes.filter((recipe) => recipe.rotation === 0).sort((left, right) => right.scale - left.scale)[0];\n const selected = unrotated === undefined ? [] : [unrotated];\n if (options.performance === \"accurate\") {\n selected.push(...recipes.filter((recipe) => recipe.rotation !== 0));\n }\n return selected;\n}\n\nasync function collectTextEvidence(handle: PdfHandle, state: MutableRunState, pageLimit: number, options: ResolvedOptions, guard: WorkGuard): Promise<number[]> {\n const processedPages: number[] = [];\n for (let pageNumber = 1; pageNumber <= pageLimit; pageNumber += 1) {\n guard.check();\n const candidates = await withPage(handle, pageNumber, async (page) => textEvidence(await extractPageText(page), pageNumber));\n guard.check();\n state.evidence.push(...candidates);\n state.pagesProcessed += 1;\n processedPages.push(pageNumber);\n if (options.stopAfterFirst && candidates.length > 0) {\n break;\n }\n }\n return processedPages;\n}\n\nasync function collectBarcodeEvidence(handle: PdfHandle, state: MutableRunState, pages: number[], recipes: RenderRecipe[], options: ResolvedOptions, guard: WorkGuard): Promise<void> {\n const exhaustive = options.ocr === \"always\" || options.performance === \"accurate\";\n let pending = exhaustive ? [...pages] : pages.filter((page) => !hasPageEvidence(state.evidence, page));\n\n if (pending.length === 0) {\n return;\n }\n\n const [{ renderPage }, { readBarcodes }] = await Promise.all([import(\"./pdf/render-page\"), import(\"./recognition/barcode-reader\")]);\n\n for (let passIndex = 0; passIndex < recipes.length && pending.length > 0; passIndex += 1) {\n const recipe = recipes[passIndex];\n if (recipe === undefined) {\n break;\n }\n state.passesUsed = Math.max(state.passesUsed, passIndex + 1);\n const unresolved: number[] = [];\n for (const pageNumber of pending) {\n guard.check();\n const candidates = await withPage(handle, pageNumber, async (page) => {\n const rendered = await renderPage(page, recipe, options.maxPixelsPerPage);\n state.renderedPages.add(pageNumber);\n return (await readBarcodes(rendered)).flatMap((barcode) => findCandidatesInDecodedValue(barcode.text, pageNumber, barcode.source, passIndex + 1));\n });\n guard.check();\n state.evidence.push(...candidates);\n if (candidates.length === 0 || exhaustive) {\n unresolved.push(pageNumber);\n }\n if (options.stopAfterFirst && candidates.length > 0) {\n return;\n }\n }\n pending = unresolved;\n }\n}\n\nasync function collectOcrEvidence(handle: PdfHandle, state: MutableRunState, pages: number[], recipes: RenderRecipe[], options: ResolvedOptions, guard: WorkGuard): Promise<OcrSession | null> {\n if (options.ocr === \"never\") {\n return null;\n }\n const pending = options.ocr === \"always\" ? pages : pages.filter((page) => !hasPageEvidence(state.evidence, page));\n if (pending.length === 0) {\n return null;\n }\n\n const selectedRecipes = ocrRecipes(recipes, options);\n if (selectedRecipes.length === 0) {\n return null;\n }\n\n const [{ renderPage }, { createOcrSession }] = await Promise.all([import(\"./pdf/render-page\"), import(\"./recognition/ocr-reader\")]);\n const session = await createOcrSession();\n try {\n for (const pageNumber of pending) {\n for (const recipe of selectedRecipes) {\n guard.check();\n const candidates = await withPage(handle, pageNumber, async (page) => {\n const rendered = await renderPage(page, recipe, options.maxPixelsPerPage);\n state.renderedPages.add(pageNumber);\n state.ocrPages.add(pageNumber);\n const recognized = await session.recognize(rendered.toPng());\n return findCandidatesInOcrText(recognized.text, pageNumber, recipes.indexOf(recipe) + 1, recognized.confidence);\n });\n guard.check();\n state.evidence.push(...candidates);\n if (options.stopAfterFirst && candidates.length > 0) {\n return session;\n }\n }\n }\n return session;\n } catch (error) {\n await session.terminate().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Extracts validated NF-e/NFC-e access keys from a local path, HTTP(S) URL,\n * or in-memory PDF.\n * This function resolves to a JSON-safe result for expected input and processing errors.\n */\nexport async function extractNFeAccessKeys(input: PdfInput, optionsInput: ExtractOptions = {}): Promise<ExtractionResult> {\n const startedAt = performance.now();\n let options: ResolvedOptions;\n try {\n options = resolveOptions(optionsInput);\n } catch (error) {\n if (error instanceof InvalidOptionsError) {\n return invalidOptionsResult(error, startedAt);\n }\n return invalidOptionsResult(new InvalidOptionsError(\"Extraction options are invalid.\"), startedAt);\n }\n\n const state = emptyState();\n const guard = new WorkGuard(options, startedAt);\n let handle: PdfHandle | null = null;\n let ocrSession: OcrSession | null = null;\n try {\n guard.check();\n const loaded = await loadPdfInput(input, options.maxFileSizeBytes, {\n ...(options.requestHeaders === undefined ? {} : { requestHeaders: options.requestHeaders }),\n signal: guard.signal,\n });\n guard.check();\n state.fileSizeBytes = loaded.size;\n handle = await openPdfDocument(loaded.data, options.maxSourceImagePixels, options.maxPixelsPerPage);\n guard.check();\n state.pagesTotal = handle.document.numPages;\n const pageLimit = Math.min(state.pagesTotal, options.maxPages);\n if (pageLimit < state.pagesTotal) {\n state.complete = false;\n state.warnings.push(`Only the first ${pageLimit} of ${state.pagesTotal} pages were processed because of maxPages.`);\n }\n\n const processedPages = await collectTextEvidence(handle, state, pageLimit, options, guard);\n if (!(options.stopAfterFirst && state.evidence.length > 0)) {\n const recipes = getRenderRecipes(options);\n await collectBarcodeEvidence(handle, state, processedPages, recipes, options, guard);\n if (!(options.stopAfterFirst && state.evidence.length > 0)) {\n ocrSession = await collectOcrEvidence(handle, state, processedPages, recipes, options, guard);\n }\n }\n\n guard.check();\n if (options.stopAfterFirst && state.evidence.length > 0) {\n state.complete = true;\n }\n return resultFromState(options, state, startedAt);\n } catch (error) {\n state.complete = false;\n let resolvedError: unknown = error;\n try {\n guard.check();\n } catch (guardError) {\n resolvedError = guardError;\n }\n const failure =\n resolvedError instanceof ExtractionFailure\n ? resolvedError\n : new ExtractionFailure(\"PROCESSING_ERROR\", \"The PDF could not be processed.\", {\n cause: resolvedError,\n });\n if (!(resolvedError instanceof ExtractionFailure)) {\n state.warnings.push(`Internal detail: ${messageFromUnknown(resolvedError)}`);\n }\n return resultFromState(options, state, startedAt, {\n code: failure.code,\n message: failure.message,\n });\n } finally {\n guard.dispose();\n await ocrSession?.terminate().catch(() => undefined);\n await handle?.close().catch(() => undefined);\n }\n}\n\nexport type { ExtractedAccessKey };\n","const NUMERIC_ACCESS_KEY_PATTERN = /^[0-9]{44}$/;\nconst CURRENT_ACCESS_KEY_PATTERN = /^[0-9]{6}[A-Z0-9]{12}[0-9]{26}$/;\nconst ACCESS_KEY_BODY_PATTERN = /^[0-9]{6}[A-Z0-9]{12}[0-9]{25}$/;\nconst ISSUER_IDENTIFIER_PATTERN = /^[A-Z0-9]{12}[0-9]{2}$/;\nconst ZERO_PADDED_CPF_PATTERN = /^000[0-9]{11}$/;\n\nconst VALID_STATE_CODES = new Set([\"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"31\", \"32\", \"33\", \"35\", \"41\", \"42\", \"43\", \"50\", \"51\", \"52\", \"53\"]);\n\nconst VALID_MODELS = new Set([\"55\", \"65\"]);\n\nexport const ACCESS_KEY_ISSUE_CODES = {\n INVALID_FORMAT: \"INVALID_FORMAT\",\n INVALID_CHECK_DIGIT: \"INVALID_CHECK_DIGIT\",\n INVALID_MODEL: \"INVALID_MODEL\",\n INVALID_STATE_CODE: \"INVALID_STATE_CODE\",\n INVALID_MONTH: \"INVALID_MONTH\",\n INVALID_ISSUER_IDENTIFIER: \"INVALID_ISSUER_IDENTIFIER\",\n INVALID_INVOICE_NUMBER: \"INVALID_INVOICE_NUMBER\",\n} as const;\n\nexport type AccessKeyIssueCode = (typeof ACCESS_KEY_ISSUE_CODES)[keyof typeof ACCESS_KEY_ISSUE_CODES];\n\nexport type AccessKeyFormat = \"numeric\" | \"alphanumeric\";\n\nexport type AccessKeyDocumentType = \"NFe\" | \"NFCe\";\n\nexport interface AccessKeyIssue {\n code: AccessKeyIssueCode;\n message: string;\n}\n\nexport interface AccessKeyComponents {\n accessKey: string;\n format: AccessKeyFormat;\n stateCode: string;\n yearMonth: string;\n year: string;\n month: string;\n issuerId: string;\n model: string;\n documentType: AccessKeyDocumentType | null;\n series: string;\n invoiceNumber: string;\n emissionType: string;\n numericCode: string;\n checkDigit: number;\n}\n\nexport interface AccessKeyValidation {\n isValid: boolean;\n normalizedValue: string;\n format: AccessKeyFormat | null;\n components: AccessKeyComponents | null;\n expectedCheckDigit: number | null;\n issues: AccessKeyIssue[];\n}\n\nfunction normalizeAccessKey(value: unknown): string {\n return typeof value === \"string\" ? value.toUpperCase() : \"\";\n}\n\nfunction getAccessKeyFormat(value: string): AccessKeyFormat | null {\n if (NUMERIC_ACCESS_KEY_PATTERN.test(value)) {\n return \"numeric\";\n }\n\n if (CURRENT_ACCESS_KEY_PATTERN.test(value)) {\n return \"alphanumeric\";\n }\n\n return null;\n}\n\nfunction getDocumentType(model: string): AccessKeyDocumentType | null {\n if (model === \"55\") {\n return \"NFe\";\n }\n\n if (model === \"65\") {\n return \"NFCe\";\n }\n\n return null;\n}\n\nfunction calculateAsciiModulo11Digit(body: string): number {\n let sum = 0;\n let weight = 2;\n\n for (let index = body.length - 1; index >= 0; index -= 1) {\n sum += (body.charCodeAt(index) - 48) * weight;\n weight = weight === 9 ? 2 : weight + 1;\n }\n\n const remainder = sum % 11;\n return remainder === 0 || remainder === 1 ? 0 : 11 - remainder;\n}\n\nfunction hasRepeatedCharacters(value: string): boolean {\n return value.length > 0 && new Set(value).size === 1;\n}\n\nfunction validateCnpj(value: string): boolean {\n const base = value.slice(0, 12);\n\n if (hasRepeatedCharacters(base)) {\n return false;\n }\n\n const firstCheckDigit = calculateAsciiModulo11Digit(base);\n const secondCheckDigit = calculateAsciiModulo11Digit(`${base}${firstCheckDigit}`);\n\n return value.slice(12) === `${firstCheckDigit}${secondCheckDigit}`;\n}\n\nfunction calculateCpfCheckDigit(body: string): number {\n let sum = 0;\n\n for (let index = 0; index < body.length; index += 1) {\n sum += (body.charCodeAt(index) - 48) * (body.length + 1 - index);\n }\n\n const remainder = sum % 11;\n return remainder === 0 || remainder === 1 ? 0 : 11 - remainder;\n}\n\nfunction validateZeroPaddedCpf(value: string): boolean {\n if (!ZERO_PADDED_CPF_PATTERN.test(value)) {\n return false;\n }\n\n const cpf = value.slice(3);\n const base = cpf.slice(0, 9);\n\n if (hasRepeatedCharacters(cpf) || hasRepeatedCharacters(base)) {\n return false;\n }\n\n const firstCheckDigit = calculateCpfCheckDigit(base);\n const secondCheckDigit = calculateCpfCheckDigit(`${base}${firstCheckDigit}`);\n\n return cpf.slice(9) === `${firstCheckDigit}${secondCheckDigit}`;\n}\n\n/**\n * Validates the 14-character issuer field as either a numeric/alphanumeric\n * CNPJ or an 11-digit CPF padded with three leading zeroes.\n */\nexport function validateIssuerIdentifier(value: string): boolean {\n const normalizedValue = normalizeAccessKey(value);\n\n if (!ISSUER_IDENTIFIER_PATTERN.test(normalizedValue)) {\n return false;\n }\n\n return validateCnpj(normalizedValue) || validateZeroPaddedCpf(normalizedValue);\n}\n\n/**\n * Calculates the final digit of a 44-character NF-e/NFC-e access key.\n * Alphanumeric characters use their ASCII value minus 48, as required for\n * access keys containing an alphanumeric CNPJ.\n */\nexport function calculateAccessKeyCheckDigit(body: string): number {\n const normalizedBody = normalizeAccessKey(body);\n\n if (!ACCESS_KEY_BODY_PATTERN.test(normalizedBody)) {\n throw new TypeError(\"Access key body must have 43 characters and match the supported access key format.\");\n }\n\n return calculateAsciiModulo11Digit(normalizedBody);\n}\n\n/**\n * Splits a format-valid access key into the fields defined by the NF-e layout.\n * Semantic checks such as model, state code and month are performed by\n * validateAccessKey so callers can inspect malformed-but-parseable candidates.\n */\nexport function parseAccessKey(value: string): AccessKeyComponents {\n const normalizedValue = normalizeAccessKey(value);\n const format = getAccessKeyFormat(normalizedValue);\n\n if (format === null) {\n throw new TypeError(\"Access key does not match a supported 44-character format.\");\n }\n\n const model = normalizedValue.slice(20, 22);\n const yearMonth = normalizedValue.slice(2, 6);\n\n return {\n accessKey: normalizedValue,\n format,\n stateCode: normalizedValue.slice(0, 2),\n yearMonth,\n year: yearMonth.slice(0, 2),\n month: yearMonth.slice(2, 4),\n issuerId: normalizedValue.slice(6, 20),\n model,\n documentType: getDocumentType(model),\n series: normalizedValue.slice(22, 25),\n invoiceNumber: normalizedValue.slice(25, 34),\n emissionType: normalizedValue.slice(34, 35),\n numericCode: normalizedValue.slice(35, 43),\n checkDigit: Number(normalizedValue[43]),\n };\n}\n\nexport function validateAccessKey(value: string): AccessKeyValidation {\n const normalizedValue = normalizeAccessKey(value);\n const format = getAccessKeyFormat(normalizedValue);\n\n if (format === null) {\n return {\n isValid: false,\n normalizedValue,\n format: null,\n components: null,\n expectedCheckDigit: null,\n issues: [\n {\n code: ACCESS_KEY_ISSUE_CODES.INVALID_FORMAT,\n message: \"Access key does not match a supported 44-character format.\",\n },\n ],\n };\n }\n\n const components = parseAccessKey(normalizedValue);\n const expectedCheckDigit = calculateAccessKeyCheckDigit(normalizedValue.slice(0, 43));\n const issues: AccessKeyIssue[] = [];\n\n if (!VALID_STATE_CODES.has(components.stateCode)) {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_STATE_CODE,\n message: `State code ${components.stateCode} is not an official IBGE UF code.`,\n });\n }\n\n const month = Number(components.month);\n if (month < 1 || month > 12) {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_MONTH,\n message: `Month ${components.month} must be between 01 and 12.`,\n });\n }\n\n if (!VALID_MODELS.has(components.model)) {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_MODEL,\n message: `Model ${components.model} is not supported; expected 55 or 65.`,\n });\n }\n\n if (components.invoiceNumber === \"000000000\") {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_INVOICE_NUMBER,\n message: \"Invoice number must be between 000000001 and 999999999.\",\n });\n }\n\n if (!validateIssuerIdentifier(components.issuerId)) {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_ISSUER_IDENTIFIER,\n message: `Issuer identifier ${components.issuerId} is not a valid CNPJ or zero-padded CPF.`,\n });\n }\n\n if (components.checkDigit !== expectedCheckDigit) {\n issues.push({\n code: ACCESS_KEY_ISSUE_CODES.INVALID_CHECK_DIGIT,\n message: `Check digit ${components.checkDigit} does not match expected digit ${expectedCheckDigit}.`,\n });\n }\n\n return {\n isValid: issues.length === 0,\n normalizedValue,\n format,\n components,\n expectedCheckDigit,\n issues,\n };\n}\n","import { validateAccessKey } from \"../validation/access-key\";\nimport type { CandidateEvidence } from \"./types\";\nimport type { ExtractionSource } from \"../types\";\n\nconst ACCESS_KEY_PATTERN = /[0-9]{6}[A-Z0-9]{12}[0-9]{26}/g;\nconst SEPARATOR_PATTERN = /[\\s.\\-_/]/;\nconst ALPHANUMERIC_PATTERN = /[A-Z0-9]/;\nconst LABEL_PATTERN = /CHAVE\\s+DE\\s+ACESSO|ACCESS\\s+KEY/;\n\nfunction normalizedText(value: string): string {\n return value.normalize(\"NFKC\").replace(/\\u00a0/g, \" \").toUpperCase();\n}\n\nfunction isNearLabel(text: string, start: number): boolean {\n const context = text.slice(Math.max(0, start - 120), start + 12);\n return LABEL_PATTERN.test(context);\n}\n\nfunction addIfValid(output: CandidateEvidence[], seen: Set<string>, accessKey: string, page: number, source: ExtractionSource, pass: number, nearLabel: boolean): void {\n const validation = validateAccessKey(accessKey);\n const signature = `${accessKey}:${source}:${pass}:${nearLabel}`;\n if (!validation.isValid || seen.has(signature)) {\n return;\n }\n seen.add(signature);\n output.push({ accessKey, page, source, pass, nearLabel });\n}\n\nexport function findCandidatesInText(text: string, page: number): CandidateEvidence[] {\n const normalized = normalizedText(text);\n const output: CandidateEvidence[] = [];\n const seen = new Set<string>();\n\n for (const match of normalized.matchAll(ACCESS_KEY_PATTERN)) {\n const accessKey = match[0];\n const start = match.index;\n const before = start > 0 ? normalized[start - 1] : undefined;\n const after = normalized[start + accessKey.length];\n if ((before !== undefined && ALPHANUMERIC_PATTERN.test(before)) || (after !== undefined && ALPHANUMERIC_PATTERN.test(after))) {\n continue;\n }\n addIfValid(output, seen, accessKey, page, \"pdf-text\", 0, isNearLabel(normalized, start));\n }\n\n for (let start = 0; start < normalized.length; start += 1) {\n const first = normalized[start];\n if (first === undefined || !/[0-9]/.test(first)) {\n continue;\n }\n\n let accessKey = \"\";\n let cursor = start;\n let hadSeparator = false;\n while (cursor < normalized.length && cursor - start <= 100) {\n const character = normalized[cursor];\n if (character === undefined) {\n break;\n }\n if (ALPHANUMERIC_PATTERN.test(character)) {\n accessKey += character;\n } else if (SEPARATOR_PATTERN.test(character)) {\n hadSeparator = true;\n } else {\n break;\n }\n\n cursor += 1;\n if (accessKey.length === 44) {\n const nearLabel = isNearLabel(normalized, start);\n const rawSpan = normalized.slice(start, cursor);\n let lookahead = cursor;\n while (SEPARATOR_PATTERN.test(normalized[lookahead] ?? \"\")) {\n lookahead += 1;\n }\n const likelyLongerNumericCluster = /[0-9]/.test(normalized[lookahead] ?? \"\") && !nearLabel;\n const crossesLinesWithoutContext = rawSpan.includes(\"\\n\") && !nearLabel;\n if (hadSeparator && !likelyLongerNumericCluster && !crossesLinesWithoutContext) {\n addIfValid(output, seen, accessKey, page, \"pdf-text-reconstructed\", 0, nearLabel);\n }\n break;\n }\n if (accessKey.length > 44) {\n break;\n }\n }\n }\n\n return output;\n}\n\nexport function findCandidatesInDecodedValue(value: string, page: number, source: Extract<\"code128\" | \"qr-code\", ExtractionSource>, pass: number): CandidateEvidence[] {\n let decoded = normalizedText(value);\n try {\n decoded = decodeURIComponent(decoded);\n } catch {\n // Barcode payloads may contain literal percent signs; keep the normalized value.\n }\n\n const output: CandidateEvidence[] = [];\n const seen = new Set<string>();\n for (const match of decoded.matchAll(ACCESS_KEY_PATTERN)) {\n addIfValid(output, seen, match[0], page, source, pass, true);\n }\n return output;\n}\n","import { findCandidatesInText } from \"./from-text\";\nimport { validateAccessKey } from \"../validation/access-key\";\nimport type { CandidateEvidence } from \"./types\";\n\nconst OCR_CLUSTER = /[A-Z0-9](?:[\\s.\\-_/]*[A-Z0-9]){43}/g;\nconst OCR_TO_DIGIT: Readonly<Record<string, string>> = {\n O: \"0\",\n Q: \"0\",\n D: \"0\",\n I: \"1\",\n L: \"1\",\n Z: \"2\",\n S: \"5\",\n G: \"6\",\n B: \"8\",\n};\nconst DIGIT_TO_OCR_LETTERS: Readonly<Record<string, readonly string[]>> = {\n \"0\": [\"O\", \"Q\", \"D\"],\n \"1\": [\"I\", \"L\"],\n \"2\": [\"Z\"],\n \"5\": [\"S\"],\n \"6\": [\"G\"],\n \"8\": [\"B\"],\n};\n\nfunction correctedAlternatives(raw: string): Array<{ value: string; corrections: number }> {\n const characters = raw.match(/[A-Z0-9]/g);\n if (characters === null || characters.length !== 44) {\n return [];\n }\n\n let corrections = 0;\n const issuerAlternatives: Array<{ index: number; replacement: string }> = [];\n for (let index = 0; index < characters.length; index += 1) {\n const character = characters[index];\n if (character === undefined) {\n continue;\n }\n const isAlphanumericIssuerPosition = index >= 6 && index < 18;\n if (/[0-9]/.test(character)) {\n if (isAlphanumericIssuerPosition) {\n for (const letter of DIGIT_TO_OCR_LETTERS[character] ?? []) {\n issuerAlternatives.push({ index, replacement: letter });\n }\n }\n continue;\n }\n if (isAlphanumericIssuerPosition) {\n const digit = OCR_TO_DIGIT[character];\n if (digit !== undefined) {\n issuerAlternatives.push({ index, replacement: digit });\n }\n continue;\n }\n const corrected = OCR_TO_DIGIT[character];\n if (corrected === undefined) {\n return [];\n }\n characters[index] = corrected;\n corrections += 1;\n }\n\n if (corrections > 1) {\n return [];\n }\n\n const uncorrectedValue = characters.join(\"\");\n const alternatives = [{ value: uncorrectedValue, corrections }];\n if (corrections === 0 && !validateAccessKey(uncorrectedValue).isValid) {\n for (const { index, replacement } of issuerAlternatives) {\n const corrected = [...characters];\n corrected[index] = replacement;\n alternatives.push({ value: corrected.join(\"\"), corrections: 1 });\n }\n }\n return alternatives;\n}\n\nexport function findCandidatesInOcrText(text: string, page: number, pass: number, confidence: number): CandidateEvidence[] {\n const normalized = text.normalize(\"NFKC\").toUpperCase();\n const exact = findCandidatesInText(normalized, page).map((candidate) => ({\n ...candidate,\n source: \"ocr\" as const,\n pass,\n ocrConfidence: confidence,\n }));\n const output = [...exact];\n const seen = new Set(exact.map((candidate) => candidate.accessKey));\n\n for (const match of normalized.matchAll(OCR_CLUSTER)) {\n for (const corrected of correctedAlternatives(match[0])) {\n if (corrected.corrections === 0 || seen.has(corrected.value) || !validateAccessKey(corrected.value).isValid) {\n continue;\n }\n seen.add(corrected.value);\n output.push({\n accessKey: corrected.value,\n page,\n source: \"ocr\",\n pass,\n nearLabel: false,\n ocrConfidence: confidence,\n corrections: corrected.corrections,\n });\n }\n }\n\n return output;\n}\n","import { performance } from \"node:perf_hooks\";\n\nimport { ExtractionFailure } from \"./errors\";\nimport type { ResolvedOptions } from \"./options\";\n\nexport class WorkGuard {\n readonly #startedAt: number;\n readonly #options: ResolvedOptions;\n readonly #controller = new AbortController();\n readonly #abortListener?: () => void;\n readonly #timeout?: NodeJS.Timeout;\n #stopReason: \"aborted\" | \"timeout\" | null = null;\n\n public constructor(options: ResolvedOptions, startedAt = performance.now()) {\n this.#options = options;\n this.#startedAt = startedAt;\n\n if (options.signal?.aborted === true) {\n this.#stop(\"aborted\");\n } else if (options.signal !== undefined) {\n this.#abortListener = (): void => {\n this.#stop(\"aborted\");\n };\n options.signal.addEventListener(\"abort\", this.#abortListener, { once: true });\n }\n\n if (options.timeoutMs > 0 && this.#stopReason === null) {\n const elapsed = performance.now() - this.#startedAt;\n this.#timeout = setTimeout(\n () => {\n this.#stop(\"timeout\");\n },\n Math.max(0, options.timeoutMs - elapsed),\n );\n this.#timeout.unref();\n }\n }\n\n public get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n public check(): void {\n if (this.#options.signal?.aborted === true || this.#stopReason === \"aborted\") {\n this.#stop(\"aborted\");\n throw new ExtractionFailure(\"ABORTED\", \"Extraction was aborted.\");\n }\n if (this.#stopReason === \"timeout\" || (this.#options.timeoutMs > 0 && performance.now() - this.#startedAt >= this.#options.timeoutMs)) {\n this.#stop(\"timeout\");\n throw new ExtractionFailure(\"TIMEOUT\", \"Extraction exceeded its configured deadline.\");\n }\n }\n\n public dispose(): void {\n if (this.#timeout !== undefined) {\n clearTimeout(this.#timeout);\n }\n if (this.#abortListener !== undefined && this.#options.signal !== undefined) {\n this.#options.signal.removeEventListener(\"abort\", this.#abortListener);\n }\n }\n\n #stop(reason: \"aborted\" | \"timeout\"): void {\n if (this.#stopReason !== null) {\n return;\n }\n this.#stopReason = reason;\n this.#controller.abort();\n }\n}\n","import { validateHeaderName, validateHeaderValue } from \"node:http\";\n\nimport type { ExtractOptions, OcrMode, PerformanceProfile } from \"./types\";\n\nconst MEBIBYTE = 1024 * 1024;\n\nconst BLOCKED_REQUEST_HEADERS = new Set([\"accept-encoding\", \"connection\", \"content-length\", \"expect\", \"host\", \"if-range\", \"keep-alive\", \"proxy-connection\", \"range\", \"te\", \"trailer\", \"transfer-encoding\", \"upgrade\"]);\n\ninterface ProfileDefaults {\n passes: number;\n ocr: OcrMode;\n maxPages: number;\n maxPixelsPerPage: number;\n maxSourceImagePixels: number;\n timeoutMs: number;\n}\n\nconst PROFILE_DEFAULTS: Record<PerformanceProfile, ProfileDefaults> = {\n fast: {\n passes: 1,\n ocr: \"never\",\n maxPages: 10,\n maxPixelsPerPage: 8_000_000,\n maxSourceImagePixels: 40_000_000,\n timeoutMs: 30_000,\n },\n balanced: {\n passes: 2,\n ocr: \"fallback\",\n maxPages: 30,\n maxPixelsPerPage: 12_000_000,\n maxSourceImagePixels: 60_000_000,\n timeoutMs: 120_000,\n },\n accurate: {\n passes: 3,\n ocr: \"fallback\",\n maxPages: 50,\n maxPixelsPerPage: 20_000_000,\n maxSourceImagePixels: 100_000_000,\n timeoutMs: 300_000,\n },\n};\n\nexport interface ResolvedOptions {\n performance: PerformanceProfile;\n passes: number;\n ocr: OcrMode;\n maxPages: number;\n maxFileSizeBytes: number;\n maxPixelsPerPage: number;\n maxSourceImagePixels: number;\n timeoutMs: number;\n stopAfterFirst: boolean;\n requestHeaders?: Readonly<Record<string, string>>;\n signal?: AbortSignal;\n}\n\nexport class InvalidOptionsError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"InvalidOptionsError\";\n }\n}\n\nfunction integerInRange(name: string, value: number | undefined, fallback: number, minimum: number, maximum: number): number {\n const resolved = value ?? fallback;\n if (!Number.isInteger(resolved) || resolved < minimum || resolved > maximum) {\n throw new InvalidOptionsError(`${name} must be an integer between ${minimum} and ${maximum}.`);\n }\n return resolved;\n}\n\nfunction normalizeRequestHeaders(requestHeaders: ExtractOptions[\"requestHeaders\"]): Readonly<Record<string, string>> | undefined {\n if (requestHeaders === undefined) {\n return undefined;\n }\n if (typeof requestHeaders !== \"object\" || requestHeaders === null || Array.isArray(requestHeaders)) {\n throw new InvalidOptionsError(\"requestHeaders must be a record of strings.\");\n }\n\n let prototype: object | null;\n try {\n prototype = Object.getPrototypeOf(requestHeaders) as object | null;\n } catch {\n throw new InvalidOptionsError(\"requestHeaders could not be read.\");\n }\n if (prototype !== Object.prototype && prototype !== null) {\n throw new InvalidOptionsError(\"requestHeaders must be a record of strings.\");\n }\n\n const normalized = Object.create(null) as Record<string, string>;\n let entries: [string, unknown][];\n try {\n entries = Object.entries(requestHeaders);\n } catch {\n throw new InvalidOptionsError(\"requestHeaders could not be read.\");\n }\n\n for (const [name, value] of entries) {\n const normalizedName = name.toLowerCase();\n if (typeof value !== \"string\") {\n throw new InvalidOptionsError(\"Every requestHeaders value must be a string.\");\n }\n try {\n validateHeaderName(name);\n validateHeaderValue(name, value);\n } catch {\n throw new InvalidOptionsError(\"requestHeaders contains an invalid header.\");\n }\n if (BLOCKED_REQUEST_HEADERS.has(normalizedName)) {\n throw new InvalidOptionsError(\"requestHeaders contains a header that cannot be overridden.\");\n }\n if (Object.hasOwn(normalized, normalizedName)) {\n throw new InvalidOptionsError(\"requestHeaders contains duplicate case-insensitive names.\");\n }\n normalized[normalizedName] = value;\n }\n return Object.freeze(normalized);\n}\n\nexport function resolveOptions(options: ExtractOptions = {}): ResolvedOptions {\n const performance = options.performance ?? \"balanced\";\n if (!Object.hasOwn(PROFILE_DEFAULTS, performance)) {\n throw new InvalidOptionsError(\"performance must be fast, balanced, or accurate.\");\n }\n\n const profile = PROFILE_DEFAULTS[performance];\n const ocr = options.ocr ?? profile.ocr;\n if (![\"never\", \"fallback\", \"always\"].includes(ocr)) {\n throw new InvalidOptionsError(\"ocr must be never, fallback, or always.\");\n }\n\n const requestHeaders = normalizeRequestHeaders(options.requestHeaders);\n\n return {\n performance,\n passes: integerInRange(\"passes\", options.passes, profile.passes, 1, 5),\n ocr,\n maxPages: integerInRange(\"maxPages\", options.maxPages, profile.maxPages, 1, 10_000),\n maxFileSizeBytes: integerInRange(\"maxFileSizeBytes\", options.maxFileSizeBytes, 30 * MEBIBYTE, 1, 1024 * MEBIBYTE),\n maxPixelsPerPage: integerInRange(\"maxPixelsPerPage\", options.maxPixelsPerPage, profile.maxPixelsPerPage, 250_000, 100_000_000),\n maxSourceImagePixels: integerInRange(\"maxSourceImagePixels\", options.maxSourceImagePixels, profile.maxSourceImagePixels, 250_000, 200_000_000),\n timeoutMs: integerInRange(\"timeoutMs\", options.timeoutMs, profile.timeoutMs, 0, 3_600_000),\n stopAfterFirst: options.stopAfterFirst ?? false,\n ...(requestHeaders === undefined ? {} : { requestHeaders }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n };\n}\n\nexport interface RenderRecipe {\n scale: number;\n rotation: 0 | 90 | 270;\n}\n\nconst RECIPES: Record<PerformanceProfile, readonly RenderRecipe[]> = {\n fast: [\n { scale: 1.25, rotation: 0 },\n { scale: 1.6, rotation: 0 },\n { scale: 2, rotation: 0 },\n { scale: 1.6, rotation: 90 },\n { scale: 1.6, rotation: 270 },\n ],\n balanced: [\n { scale: 1.5, rotation: 0 },\n { scale: 2, rotation: 0 },\n { scale: 2.5, rotation: 0 },\n { scale: 2, rotation: 90 },\n { scale: 2, rotation: 270 },\n ],\n accurate: [\n { scale: 1.75, rotation: 0 },\n { scale: 2.25, rotation: 0 },\n { scale: 3, rotation: 0 },\n { scale: 2.25, rotation: 90 },\n { scale: 2.25, rotation: 270 },\n ],\n};\n\nexport function getRenderRecipes(options: ResolvedOptions): RenderRecipe[] {\n return RECIPES[options.performance].slice(0, options.passes);\n}\n","import { ExtractionFailure } from \"../errors\";\nimport type { PdfPageLike, PdfTextItemLike } from \"./types\";\n\nconst MAX_TEXT_ITEMS_PER_PAGE = 50_000;\nconst MAX_TEXT_CHARACTERS_PER_PAGE = 250_000;\n\ninterface PositionedTextItem {\n str: string;\n x: number;\n y: number;\n width: number;\n height: number;\n hasEOL: boolean;\n}\n\ninterface TextLine {\n y: number;\n height: number;\n items: PositionedTextItem[];\n}\n\nexport interface ExtractedPageText {\n orderedText: string;\n visualLines: string[];\n hasText: boolean;\n}\n\nfunction isTextItem(value: unknown): value is PdfTextItemLike {\n return typeof value === \"object\" && value !== null && \"str\" in value && typeof value.str === \"string\";\n}\n\nfunction positionedItem(item: PdfTextItemLike): PositionedTextItem {\n const transform = item.transform ?? [];\n return {\n str: item.str,\n x: transform[4] ?? 0,\n y: transform[5] ?? 0,\n width: item.width ?? 0,\n height: Math.abs(item.height ?? transform[3] ?? 10),\n hasEOL: item.hasEOL ?? false,\n };\n}\n\nfunction reconstructLines(items: PositionedTextItem[]): string[] {\n const sorted = [...items].sort((left, right) => right.y - left.y || left.x - right.x);\n const lines: TextLine[] = [];\n\n for (const item of sorted) {\n const line = lines.at(-1);\n if (line === undefined || Math.abs(line.y - item.y) > Math.max(2, item.height * 0.45)) {\n lines.push({ y: item.y, height: item.height, items: [item] });\n } else {\n line.items.push(item);\n line.height = Math.max(line.height, item.height);\n }\n }\n\n return lines.sort((left, right) => right.y - left.y).map((line) => {\n const lineItems = line.items.sort((left, right) => left.x - right.x);\n let text = \"\";\n let rightEdge: number | null = null;\n for (const item of lineItems) {\n if (rightEdge !== null && item.x - rightEdge > Math.max(0.75, line.height * 0.08)) {\n text += \" \";\n }\n text += item.str;\n rightEdge = item.x + item.width;\n }\n return text.trim();\n }).filter((line) => line.length > 0);\n}\n\nexport async function extractPageText(page: PdfPageLike): Promise<ExtractedPageText> {\n const content = await page.getTextContent();\n if (content.items.length > MAX_TEXT_ITEMS_PER_PAGE) {\n throw new ExtractionFailure(\"RESOURCE_LIMIT\", \"A PDF page contains too many text items to process safely.\");\n }\n\n const items: PositionedTextItem[] = [];\n let characterCount = 0;\n for (const value of content.items) {\n if (!isTextItem(value)) {\n continue;\n }\n characterCount += value.str.length;\n if (characterCount > MAX_TEXT_CHARACTERS_PER_PAGE) {\n throw new ExtractionFailure(\"RESOURCE_LIMIT\", \"A PDF page contains too much text to process safely.\");\n }\n items.push(positionedItem(value));\n }\n\n const orderedText = items.map((item) => `${item.str}${item.hasEOL ? \"\\n\" : \" \"}`).join(\"\").trim();\n const visualLines = reconstructLines(items);\n return {\n orderedText,\n visualLines,\n hasText: items.some((item) => item.str.trim().length > 0),\n };\n}\n","import { readFile, stat } from \"node:fs/promises\";\n\nimport { ExtractionFailure } from \"../errors\";\nimport type { PdfInput } from \"../types\";\n\nconst MAX_REDIRECTS = 5;\nconst INITIAL_DOWNLOAD_BUFFER_BYTES = 64 * 1024;\nconst MAX_INITIAL_CONTENT_LENGTH_ALLOCATION = 1024 * 1024;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\nconst CREDENTIAL_HEADERS = [\"authorization\", \"cookie\", \"proxy-authorization\"] as const;\nconst WINDOWS_DRIVE_PATH = /^[a-z]:/i;\nconst HTTP_URL = /^https?:\\/\\//i;\nconst URI_SCHEME = /^[a-z][a-z0-9+.-]*:/i;\n\nexport interface LoadedInput {\n data: Uint8Array;\n size: number;\n}\n\nexport interface LoadPdfInputControls {\n requestHeaders?: Readonly<Record<string, string>>;\n signal?: AbortSignal;\n}\n\nfunction hasPdfSignature(data: Uint8Array): boolean {\n const prefix = Buffer.from(data.buffer, data.byteOffset, Math.min(data.byteLength, 1024));\n return prefix.indexOf(\"%PDF-\") >= 0;\n}\n\nfunction validatePdfBytes(data: Uint8Array, maxFileSizeBytes: number): void {\n if (data.byteLength === 0) {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"The PDF input is empty.\");\n }\n if (data.byteLength > maxFileSizeBytes) {\n throw new ExtractionFailure(\"FILE_TOO_LARGE\", `The PDF exceeds the configured ${maxFileSizeBytes}-byte limit.`);\n }\n if (!hasPdfSignature(data)) {\n throw new ExtractionFailure(\"INVALID_PDF\", \"The input does not contain a PDF signature.\");\n }\n}\n\nfunction checkedBytes(data: Uint8Array, maxFileSizeBytes: number): LoadedInput {\n validatePdfBytes(data, maxFileSizeBytes);\n const bytes = new Uint8Array(data.byteLength);\n bytes.set(data);\n return { data: bytes, size: data.byteLength };\n}\n\nfunction checkedRemoteUrl(url: URL): URL {\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"Only HTTP and HTTPS remote URLs are accepted.\");\n }\n if (url.username !== \"\" || url.password !== \"\") {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"URL credentials are not accepted; use requestHeaders instead.\");\n }\n return url;\n}\n\nfunction remoteUrlFromInput(input: string): URL | null {\n const value = input.trim();\n if (value === \"\") {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"A non-empty PDF path or HTTP(S) URL is required.\");\n }\n if (WINDOWS_DRIVE_PATH.test(value)) {\n return null;\n }\n if (!HTTP_URL.test(value)) {\n if (URI_SCHEME.test(value)) {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"Only complete HTTP and HTTPS remote URLs are accepted.\");\n }\n return null;\n }\n\n try {\n return checkedRemoteUrl(new URL(value));\n } catch (error) {\n if (error instanceof ExtractionFailure) {\n throw error;\n }\n throw new ExtractionFailure(\"INVALID_INPUT\", \"The remote URL is invalid.\", {\n cause: error,\n });\n }\n}\n\nfunction remoteHeaders(requestHeaders: Readonly<Record<string, string>> | undefined): Headers {\n try {\n const headers = new Headers(requestHeaders === undefined ? undefined : Object.entries(requestHeaders));\n headers.set(\"accept-encoding\", \"identity\");\n return headers;\n } catch (error) {\n throw new ExtractionFailure(\"INVALID_OPTIONS\", \"requestHeaders contains an invalid header.\", { cause: error });\n }\n}\n\nfunction stripRedirectCredentials(headers: Headers): void {\n for (const name of CREDENTIAL_HEADERS) {\n headers.delete(name);\n }\n}\n\nfunction cancelResponse(response: Response): void {\n void response.body?.cancel().catch(() => undefined);\n}\n\nfunction cancelReader(reader: ReadableStreamDefaultReader<Uint8Array>): void {\n void reader.cancel().catch(() => undefined);\n}\n\nfunction advertisedSize(response: Response): bigint | null {\n const value = response.headers.get(\"content-length\")?.trim();\n if (value === undefined || !/^\\d+$/.test(value)) {\n return null;\n }\n try {\n return BigInt(value);\n } catch {\n return null;\n }\n}\n\nasync function readRemoteBody(response: Response, maxFileSizeBytes: number, signal: AbortSignal | undefined): Promise<LoadedInput> {\n const size = advertisedSize(response);\n if (size !== null && size > BigInt(maxFileSizeBytes)) {\n cancelResponse(response);\n throw new ExtractionFailure(\"FILE_TOO_LARGE\", `The PDF exceeds the configured ${maxFileSizeBytes}-byte limit.`);\n }\n if (response.body === null) {\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF response did not contain a body.\");\n }\n\n const advertisedInitialSize = size === null ? INITIAL_DOWNLOAD_BUFFER_BYTES : Math.min(Number(size), MAX_INITIAL_CONTENT_LENGTH_ALLOCATION);\n let data: Uint8Array<ArrayBuffer>;\n try {\n data = new Uint8Array(Math.min(maxFileSizeBytes, advertisedInitialSize));\n } catch (error) {\n await cancelResponse(response);\n throw new ExtractionFailure(\"RESOURCE_LIMIT\", \"The remote PDF could not be buffered within available memory.\", { cause: error });\n }\n\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n try {\n reader = response.body.getReader();\n } catch (error) {\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF response could not be read.\", { cause: error });\n }\n let total = 0;\n try {\n while (true) {\n const chunk = await reader.read();\n if (chunk.done) {\n break;\n }\n if (chunk.value === undefined) {\n continue;\n }\n const requiredSize = total + chunk.value.byteLength;\n if (requiredSize > maxFileSizeBytes) {\n cancelReader(reader);\n throw new ExtractionFailure(\"FILE_TOO_LARGE\", `The PDF exceeds the configured ${maxFileSizeBytes}-byte limit.`);\n }\n if (requiredSize > data.byteLength) {\n const doubledSize = data.byteLength === 0 ? INITIAL_DOWNLOAD_BUFFER_BYTES : data.byteLength * 2;\n const expanded = new Uint8Array(Math.min(maxFileSizeBytes, Math.max(requiredSize, doubledSize)));\n expanded.set(data.subarray(0, total));\n data = expanded;\n }\n data.set(chunk.value, total);\n total = requiredSize;\n }\n } catch (error) {\n if (error instanceof ExtractionFailure || signal?.aborted === true) {\n throw error;\n }\n if (error instanceof RangeError) {\n cancelReader(reader);\n throw new ExtractionFailure(\"RESOURCE_LIMIT\", \"The remote PDF could not be buffered within available memory.\", { cause: error });\n }\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF response could not be read.\", { cause: error });\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // A cleanup failure must not replace the download result or its primary error.\n }\n }\n\n const bytes = data.subarray(0, total);\n validatePdfBytes(bytes, maxFileSizeBytes);\n return { data: bytes, size: total };\n}\n\nasync function downloadPdf(initialUrl: URL, maxFileSizeBytes: number, controls: LoadPdfInputControls): Promise<LoadedInput> {\n let currentUrl = initialUrl;\n const headers = remoteHeaders(controls.requestHeaders);\n let redirects = 0;\n\n while (true) {\n let response: Response;\n try {\n response = await fetch(currentUrl, {\n method: \"GET\",\n headers,\n redirect: \"manual\",\n ...(controls.signal === undefined ? {} : { signal: controls.signal }),\n });\n } catch (error) {\n if (controls.signal?.aborted === true) {\n throw error;\n }\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF could not be downloaded.\", { cause: error });\n }\n\n if (REDIRECT_STATUSES.has(response.status)) {\n const location = response.headers.get(\"location\");\n cancelResponse(response);\n if (redirects >= MAX_REDIRECTS) {\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", `The remote PDF exceeded the ${MAX_REDIRECTS}-redirect limit.`);\n }\n if (location === null) {\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF returned a redirect without a destination.\");\n }\n\n let nextUrl: URL;\n try {\n nextUrl = checkedRemoteUrl(new URL(location, currentUrl));\n } catch (error) {\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", \"The remote PDF returned an invalid redirect destination.\", { cause: error });\n }\n\n if (nextUrl.origin !== currentUrl.origin || (currentUrl.protocol === \"https:\" && nextUrl.protocol === \"http:\")) {\n stripRedirectCredentials(headers);\n }\n currentUrl = nextUrl;\n redirects += 1;\n continue;\n }\n\n if (!response.ok) {\n const status = response.status;\n cancelResponse(response);\n throw new ExtractionFailure(\"DOWNLOAD_ERROR\", `The remote PDF request returned HTTP status ${status}.`);\n }\n return readRemoteBody(response, maxFileSizeBytes, controls.signal);\n }\n}\n\nexport async function loadPdfInput(input: PdfInput, maxFileSizeBytes: number, controls: LoadPdfInputControls = {}): Promise<LoadedInput> {\n if (typeof input === \"string\") {\n const remoteUrl = remoteUrlFromInput(input);\n if (remoteUrl !== null) {\n return downloadPdf(remoteUrl, maxFileSizeBytes, controls);\n }\n if (controls.requestHeaders !== undefined) {\n throw new ExtractionFailure(\"INVALID_OPTIONS\", \"requestHeaders can only be used with an HTTP(S) URL input.\");\n }\n try {\n const file = await stat(input);\n if (!file.isFile()) {\n throw new ExtractionFailure(\"INVALID_INPUT\", \"The supplied path is not a file.\");\n }\n if (file.size > maxFileSizeBytes) {\n throw new ExtractionFailure(\"FILE_TOO_LARGE\", `The PDF exceeds the configured ${maxFileSizeBytes}-byte limit.`);\n }\n return checkedBytes(await readFile(input), maxFileSizeBytes);\n } catch (error) {\n if (error instanceof ExtractionFailure) {\n throw error;\n }\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n if (code === \"ENOENT\") {\n throw new ExtractionFailure(\"FILE_NOT_FOUND\", \"The PDF file was not found.\", {\n cause: error,\n });\n }\n throw new ExtractionFailure(\"INVALID_INPUT\", \"The PDF file could not be read.\", {\n cause: error,\n });\n }\n }\n\n if (controls.requestHeaders !== undefined) {\n throw new ExtractionFailure(\"INVALID_OPTIONS\", \"requestHeaders can only be used with an HTTP(S) URL input.\");\n }\n\n if (input instanceof Uint8Array) {\n return checkedBytes(input, maxFileSizeBytes);\n }\n if (input instanceof ArrayBuffer) {\n return checkedBytes(new Uint8Array(input), maxFileSizeBytes);\n }\n throw new ExtractionFailure(\"INVALID_INPUT\", \"Input must be a local path, HTTP(S) URL, ArrayBuffer, Buffer, or Uint8Array.\");\n}\n","import { ExtractionFailure, messageFromUnknown } from \"../errors\";\nimport type { PdfDocumentLike, PdfHandle } from \"./types\";\n\nasync function installCanvasGlobals(): Promise<void> {\n const canvas = await import(\"@napi-rs/canvas\");\n const target = globalThis as unknown as Record<string, unknown>;\n target[\"DOMMatrix\"] ??= canvas.DOMMatrix;\n target[\"ImageData\"] ??= canvas.ImageData;\n target[\"Path2D\"] ??= canvas.Path2D;\n}\n\nexport async function openPdfDocument(data: Uint8Array, maxSourceImagePixels: number, maxCanvasPixels: number): Promise<PdfHandle> {\n await installCanvasGlobals();\n const pdfjs = await import(\"pdfjs-dist/legacy/build/pdf.mjs\");\n const loadingTask = pdfjs.getDocument({\n data,\n isEvalSupported: false,\n maxImageSize: maxSourceImagePixels,\n canvasMaxAreaInBytes: maxCanvasPixels * 4,\n useSystemFonts: true,\n stopAtErrors: false,\n verbosity: 0,\n });\n\n try {\n const document = (await loadingTask.promise) as unknown as PdfDocumentLike;\n return {\n document,\n async close(): Promise<void> {\n await loadingTask.destroy();\n },\n };\n } catch (error) {\n await loadingTask.destroy().catch(() => undefined);\n const name = error instanceof Error ? error.name : \"\";\n const message = messageFromUnknown(error);\n if (name === \"PasswordException\" || /password/i.test(message)) {\n throw new ExtractionFailure(\"PASSWORD_REQUIRED\", \"The PDF is encrypted and requires a password.\", { cause: error });\n }\n throw new ExtractionFailure(\"INVALID_PDF\", \"The PDF could not be parsed.\", {\n cause: error,\n });\n }\n}\n","import type { CandidateEvidence } from \"../candidates/types\";\nimport type { ExtractedAccessKey, ExtractionSource } from \"../types\";\nimport { validateAccessKey } from \"../validation/access-key\";\n\nconst SOURCE_BASE_SCORE: Record<ExtractionSource, number> = {\n \"qr-code\": 0.995,\n code128: 0.995,\n \"pdf-text\": 0.985,\n \"pdf-text-reconstructed\": 0.97,\n ocr: 0.82,\n};\n\nconst SOURCE_ORDER: ExtractionSource[] = [\"qr-code\", \"code128\", \"pdf-text\", \"pdf-text-reconstructed\", \"ocr\"];\n\nfunction evidenceScore(evidence: CandidateEvidence): number {\n let score = SOURCE_BASE_SCORE[evidence.source];\n if (evidence.source === \"ocr\") {\n const ocrConfidence = Math.max(0, Math.min(100, evidence.ocrConfidence ?? 0));\n score = Math.max(0.75, 0.72 + (ocrConfidence / 100) * 0.2);\n if (evidence.nearLabel) {\n score += 0.04;\n }\n score -= (evidence.corrections ?? 0) * 0.1;\n }\n if (evidence.nearLabel && evidence.source.startsWith(\"pdf-text\")) {\n score += 0.005;\n }\n return Math.max(0, Math.min(0.995, score));\n}\n\nfunction independentFamilies(sources: Set<ExtractionSource>): number {\n let families = 0;\n if ([...sources].some((source) => source.startsWith(\"pdf-text\"))) {\n families += 1;\n }\n if (sources.has(\"code128\") || sources.has(\"qr-code\")) {\n families += 1;\n }\n if (sources.has(\"ocr\")) {\n families += 1;\n }\n return families;\n}\n\nexport function mergeEvidence(evidence: CandidateEvidence[]): ExtractedAccessKey[] {\n const grouped = new Map<string, CandidateEvidence[]>();\n for (const item of evidence) {\n const current = grouped.get(item.accessKey) ?? [];\n current.push(item);\n grouped.set(item.accessKey, current);\n }\n\n const results: ExtractedAccessKey[] = [];\n for (const [accessKey, items] of grouped) {\n const validation = validateAccessKey(accessKey);\n const components = validation.components;\n if (!validation.isValid || components?.documentType === null || components === null) {\n continue;\n }\n\n const sources = new Set(items.map((item) => item.source));\n const pages = [...new Set(items.map((item) => item.page))].sort((a, b) => a - b);\n let precisionScore = Math.max(...items.map(evidenceScore));\n if (independentFamilies(sources) > 1) {\n precisionScore = Math.min(0.999, precisionScore + 0.004);\n }\n\n results.push({\n accessKey,\n documentType: components.documentType,\n model: components.model as \"55\" | \"65\",\n format: components.format,\n isValid: true,\n precisionScore: Number(precisionScore.toFixed(3)),\n pages,\n sources: SOURCE_ORDER.filter((source) => sources.has(source)),\n occurrences: items.length,\n components,\n });\n }\n\n return results.sort((left, right) => {\n if (right.precisionScore !== left.precisionScore) {\n return right.precisionScore - left.precisionScore;\n }\n return left.pages[0]! - right.pages[0]!;\n });\n}\n","import { extractNFeAccessKeys } from \"../extractor\";\nimport type { ExtractOptions, ExtractionResult } from \"../types\";\n\nexport interface CliIo {\n stdout: Pick<NodeJS.WriteStream, \"write\">;\n}\n\ninterface ParsedCliArguments {\n source: string;\n options: ExtractOptions;\n pretty: boolean;\n}\n\nconst HELP = {\n name: \"nf-key-extractor\",\n usage: \"nf-key-extractor <file-or-url> [--performance fast|balanced|accurate] [--passes 1..5]\",\n options: [\"--performance <profile>\", \"--passes <number>\", \"--ocr <never|fallback|always>\", \"--max-pages <number>\", \"--max-file-size <bytes>\", \"--max-pixels <number>\", \"--max-source-pixels <number>\", \"--timeout-ms <number>\", \"--first\", \"--pretty\", \"--help\"],\n} as const;\n\nclass CliArgumentError extends Error {}\n\nfunction integer(value: string | undefined, option: string): number {\n if (value === undefined || !/^\\d+$/.test(value)) {\n throw new CliArgumentError(`${option} requires a non-negative integer.`);\n }\n return Number(value);\n}\n\nfunction requiredValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (value === undefined || value.startsWith(\"--\")) {\n throw new CliArgumentError(`${option} requires a value.`);\n }\n return value;\n}\n\nexport function parseCliArguments(args: string[]): ParsedCliArguments | typeof HELP {\n if (args.includes(\"--help\")) {\n return HELP;\n }\n\n const options: ExtractOptions = {};\n const sources: string[] = [];\n let pretty = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === undefined) {\n continue;\n }\n if (!argument.startsWith(\"--\")) {\n sources.push(argument);\n continue;\n }\n switch (argument) {\n case \"--performance\":\n options.performance = requiredValue(args, index, argument) as ExtractOptions[\"performance\"];\n index += 1;\n break;\n case \"--passes\":\n options.passes = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--ocr\":\n options.ocr = requiredValue(args, index, argument) as ExtractOptions[\"ocr\"];\n index += 1;\n break;\n case \"--max-pages\":\n options.maxPages = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--max-file-size\":\n options.maxFileSizeBytes = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--max-pixels\":\n options.maxPixelsPerPage = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--max-source-pixels\":\n options.maxSourceImagePixels = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--timeout-ms\":\n options.timeoutMs = integer(requiredValue(args, index, argument), argument);\n index += 1;\n break;\n case \"--first\":\n options.stopAfterFirst = true;\n break;\n case \"--pretty\":\n pretty = true;\n break;\n default:\n throw new CliArgumentError(`Unknown option: ${argument}.`);\n }\n }\n if (sources.length !== 1) {\n throw new CliArgumentError(\"Exactly one PDF path or HTTP(S) URL is required.\");\n }\n return { source: sources[0]!, options, pretty };\n}\n\nfunction cliError(message: string): ExtractionResult {\n return {\n status: \"error\",\n success: false,\n precisionScore: 0,\n bestMatch: null,\n results: [],\n metadata: {\n performance: \"balanced\",\n ocrMode: \"fallback\",\n passesRequested: 2,\n passesUsed: 0,\n pagesTotal: 0,\n pagesProcessed: 0,\n pagesRendered: 0,\n ocrPages: 0,\n fileSizeBytes: 0,\n maxPixelsPerPage: 12_000_000,\n maxSourceImagePixels: 60_000_000,\n durationMs: 0,\n complete: false,\n confidenceVersion: \"1.0.0\",\n },\n warnings: [],\n error: { code: \"INVALID_INPUT\", message },\n };\n}\n\nexport async function runCli(args: string[], io: CliIo = { stdout: process.stdout }): Promise<number> {\n try {\n const parsed = parseCliArguments(args);\n if (\"name\" in parsed) {\n io.stdout.write(`${JSON.stringify(HELP, null, 2)}\\n`);\n return 0;\n }\n const result = await extractNFeAccessKeys(parsed.source, parsed.options);\n io.stdout.write(`${JSON.stringify(result, null, parsed.pretty ? 2 : undefined)}\\n`);\n if (result.success) {\n return 0;\n }\n return result.status === \"not_found\" ? 2 : 1;\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Invalid CLI arguments.\";\n io.stdout.write(`${JSON.stringify(cliError(message))}\\n`);\n return 1;\n }\n}\n","#!/usr/bin/env node\n\nimport { runCli } from \"./cli/run\";\n\nvoid runCli(process.argv.slice(2)).then((exitCode) => {\n process.exitCode = exitCode;\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAYO,SAAS,mBAAmB,OAAwB;AACzD,SAAO,iBAAiB,QAAQ,MAAM,UAAU;AAClD;AAdA,IAEa;AAFb;AAAA;AAAA;AAEO,IAAM,oBAAN,cAAgC,MAAM;AAAA,MAC3B;AAAA,MAET,YAAY,MAA2B,SAAiB,SAAwB;AACrF,cAAM,SAAS,OAAO;AACtB,aAAK,OAAO;AACZ,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA;AAAA;;;ACVA;AAAA;AAAA;AAAA;AAeA,eAAsB,WAAW,MAAmB,QAAsB,WAA0C;AAClH,QAAM,EAAE,aAAa,IAAI,MAAM,OAAO,iBAAiB;AACvD,QAAM,aAAc,KAAK,SAAS,OAAO,YAAY,MAAO,OAAO;AACnE,MAAI,QAAQ,OAAO;AACnB,MAAI,WAAW,KAAK,YAAY,EAAE,OAAO,SAAS,CAAC;AACnD,MAAI,QAAQ;AACZ,MAAI,SAAS;AAEb,WAAS,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;AAC/C,QAAI,CAAC,OAAO,SAAS,SAAS,KAAK,KAAK,CAAC,OAAO,SAAS,SAAS,MAAM,KAAK,SAAS,SAAS,KAAK,SAAS,UAAU,GAAG;AACxH,YAAM,IAAI,kBAAkB,eAAe,oCAAoC;AAAA,IACjF;AAEA,YAAQ,KAAK,IAAI,GAAG,KAAK,KAAK,SAAS,KAAK,CAAC;AAC7C,aAAS,KAAK,IAAI,GAAG,KAAK,KAAK,SAAS,MAAM,CAAC;AAC/C,UAAM,kBAAkB,QAAQ;AAChC,QAAI,SAAS,wBAAwB,UAAU,wBAAwB,mBAAmB,WAAW;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