Phase A — Domain & schemas (15 tests): - Zod schemas: ReportSchema, FindingSchema, PractitionerSchema, SeveritySchema - Types derived via z.infer (single source of truth) - newId() helper with optional prefix Phase B — Equine anatomy + pathology DB (7 tests): - 26 macro zones, axial subzones C1-7/T1-18/L1-6/S1-5 - 31 pathologies, each citing Merck Vet Manual, PubMed, IMAIOS or LCAO - Placeholder SVGs (lateral L/R + dorsal) with data-zone convention - Species registry: equine registered, 8 others remain stubs Phase C — Zustand store (8 tests): - Single source of truth with persist middleware (localStorage key osteo-report-draft) - Actions: hydrate, reset, toggleZone, addFinding, updateFinding, removeFinding, setConclusion/Recommendations/NextAppointment Phase H/I — PDF export + import roundtrip (2 tests): - A4 portrait, pdf-lib StandardFonts - Header (practitioner + animal), anatomy pages (per used view), findings table, conclusion/recommendations/RDV page, page footer with date+page# - Attachment: base64 data URI workaround (pdf-lib treats raw string as base64 input, and rejects cross-realm Uint8Array in jsdom tests) - Import: walks Catalog→Names→EmbeddedFiles→Names array→F stream; inflates via pako directly (bypasses pdf-lib's reference-equality FlateDecode check which fails across module realms in vitest); validates with ReportSchema Tooling: - Add pako 2.x + @types/pako (already transitive of pdf-lib) - Switch vitest 2 → 3 (already done in prior commit) - Add 8 test files (34 tests total green)
112 lines
4.3 KiB
TypeScript
112 lines
4.3 KiB
TypeScript
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<ImportResult> {
|
|
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<Uint8Array> {
|
|
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;
|
|
}
|