import * as pako from 'pako'; import { PDFDocument, PDFName, type PDFRawStream } from 'pdf-lib'; import { ReportSchema } from '../schema/report'; import type { Report } from '../schema/report'; import { PDF_ATTACHMENT_NAME } from './version'; export type ImportFailure = | { ok: false; reason: 'NO_ATTACHMENT' } | { ok: false; reason: 'INVALID_JSON'; details?: string } | { ok: false; reason: 'SCHEMA_MISMATCH'; details?: string } | { ok: false; reason: 'UNREADABLE_PDF'; details?: string }; export type ImportResult = { ok: true; report: Report } | ImportFailure; export async function importReport(file: File | Blob | ArrayBuffer | Uint8Array): Promise { let pdf: PDFDocument; try { const buf = await toBytes(file); pdf = await PDFDocument.load(buf, { ignoreEncryption: true }); } catch (e) { return { ok: false, reason: 'UNREADABLE_PDF', details: (e as Error).message }; } const json = extractAttachment(pdf, PDF_ATTACHMENT_NAME); if (!json) return { ok: false, reason: 'NO_ATTACHMENT' }; let parsed: unknown; try { const decoded = new TextDecoder().decode(json); parsed = JSON.parse(decoded); } catch (e) { return { ok: false, reason: 'INVALID_JSON', details: `${(e as Error).message} | first 80 bytes: ${Array.from(json.slice(0, 80)) .map((b) => b.toString(16).padStart(2, '0')) .join(' ')}`, }; } const result = ReportSchema.safeParse(parsed); if (!result.success) { return { ok: false, reason: 'SCHEMA_MISMATCH', details: result.error.message }; } return { ok: true, report: result.data }; } async function toBytes(input: File | Blob | ArrayBuffer | Uint8Array): Promise { if (input instanceof Uint8Array) return input; if (input instanceof ArrayBuffer) return new Uint8Array(input); return new Uint8Array(await input.arrayBuffer()); } function extractAttachment(pdf: PDFDocument, name: string): Uint8Array | null { // Walk catalog → Names → EmbeddedFiles → Names array → filespec → EF → F // pdf-lib has no public attachment-extract API, so we navigate the tree. const catalog = pdf.catalog; const names = catalog.lookup(PDFName.of('Names')) as | { lookup?: (n: PDFName) => unknown } | undefined; if (!names?.lookup) return null; const embeddedFiles = names.lookup(PDFName.of('EmbeddedFiles')) as | { lookup?: (n: PDFName) => unknown } | undefined; if (!embeddedFiles?.lookup) return null; const namesArr = embeddedFiles.lookup(PDFName.of('Names')) as | { size?: () => number; lookup?: (i: number) => unknown } | undefined; if (!namesArr?.lookup || typeof namesArr.size !== 'function') return null; const size = namesArr.size(); for (let i = 0; i < size; i += 2) { const k = namesArr.lookup(i) as { decodeText?: () => string } | undefined; const fname = k?.decodeText?.(); if (fname !== name) continue; const fileSpec = namesArr.lookup(i + 1) as | { lookup?: (n: PDFName) => unknown } | undefined; if (!fileSpec?.lookup) continue; const ef = fileSpec.lookup(PDFName.of('EF')) as | { lookup?: (n: PDFName) => unknown } | undefined; if (!ef?.lookup) continue; const stream = (ef.lookup(PDFName.of('F')) ?? ef.lookup(PDFName.of('UF'))) as | { dict?: unknown; contents?: Uint8Array } | undefined; if (!stream) continue; // Duck-type instead of `instanceof PDFRawStream` (instanceof fails when // multiple pdf-lib realms coexist, e.g. during tests). if (stream.dict !== undefined && stream.contents !== undefined) { const s = stream as PDFRawStream; const filter = (s.dict as { lookup?: (n: PDFName) => unknown }).lookup?.( PDFName.of('Filter'), ); const filterName = (filter as { encodedName?: string } | undefined)?.encodedName; // We bypass pdf-lib's `decodePDFRawStream` because its reference-equality // check on `PDFName.of('FlateDecode')` is unreliable across module realms // (e.g. when vitest dual-loads pdf-lib). Use pako directly on raw bytes. if (filterName === '/FlateDecode') { return pako.inflate(s.contents); } if (filterName === undefined || filter === null) { return s.contents; } // Other filters (ASCII85, LZW, etc.) not expected for embedded files we wrote. return null; } } return null; }