From fb9a8fc3bd98864ae27721723af75559dcd6878f Mon Sep 17 00:00:00 2001 From: Bastien Chanot Date: Mon, 18 May 2026 21:53:26 +0200 Subject: [PATCH] feat(pdf): attach + extract report JSON via pdf-lib (with fallback traversal) --- src/pdf/attachment.ts | 99 +++++++++++++++++++++++++------ tests/unit/pdf.attachment.test.ts | 40 +++++++++++++ 2 files changed, 120 insertions(+), 19 deletions(-) create mode 100644 tests/unit/pdf.attachment.test.ts diff --git a/src/pdf/attachment.ts b/src/pdf/attachment.ts index 47795522..f2d43f77 100644 --- a/src/pdf/attachment.ts +++ b/src/pdf/attachment.ts @@ -1,23 +1,84 @@ -import type { PDFDocument } from 'pdf-lib' -import type { Report } from '@/domain/schema/report' +import { AFRelationship, type PDFDocument } from 'pdf-lib' +import { ReportSchema, type Report } from '@/domain/schema/report' -/** - * Attaches the serialized Report JSON to the PDF document as a native - * embedded file with afRelationship 'Data'. - * Filename: 'osteo-report.json', mimeType: 'application/json'. - */ -export async function attachReportJson( - _pdfDoc: PDFDocument, - _report: Report, -): Promise { - throw new Error('not implemented') +const FILENAME = 'osteo-report.json' + +export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise { + const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2)) + await pdfDoc.attach(bytes, FILENAME, { + mimeType: 'application/json', + description: 'Osteo Report state v1', + creationDate: new Date(), + modificationDate: new Date(), + afRelationship: AFRelationship.Data, + }) } -/** - * Extracts and parses the first embedded file named 'osteo-report*' - * with mime 'application/json' from the PDF document. - * Throws ImportError if not found or invalid. - */ -export async function extractReportJson(_pdfDoc: PDFDocument): Promise { - throw new Error('not implemented') +export async function extractReportJson(pdfDoc: PDFDocument): Promise { + const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> } + if (typeof maybeApi.getAttachments === 'function') { + const list = maybeApi.getAttachments() + if (list && list.length) { + const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0] + return parseAttachment(hit.data) + } + } + const fallback = await traverseForJsonAttachment(pdfDoc) + if (!fallback) throw new Error('No osteo-report attachment found') + return parseAttachment(fallback) +} + +function parseAttachment(bytes: Uint8Array): Report { + const text = new TextDecoder().decode(bytes) + const data = JSON.parse(text) + return ReportSchema.parse(data) +} + +interface RawObj { + contents?: Uint8Array + dict?: { entries?: () => Array<[unknown, unknown]> } +} + +async function inflateFlate(bytes: Uint8Array): Promise { + if (typeof DecompressionStream === 'undefined') return null + try { + const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate')) + return new Uint8Array(await new Response(stream).arrayBuffer()) + } catch { + return null + } +} + +function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean { + for (const [k, v] of entries) { + if (String(k).includes('Filter') && String(v).includes('FlateDecode')) return true + } + return false +} + +async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise { + const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context + for (const [, obj] of ctx.enumerateIndirectObjects()) { + if (!obj || typeof obj !== 'object') continue + if (!(obj.contents instanceof Uint8Array)) continue + const entries = obj.dict?.entries?.() ?? [] + let isEmbeddedFile = false + let isJsonSubtype = false + for (const [k, v] of entries) { + const ks = String(k) + const vs = String(v) + if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true + // PDF name syntax escapes '/' as '#2F': /application#2Fjson + if (ks.includes('Subtype') && (vs.includes('application/json') || vs.includes('application#2Fjson'))) { + isJsonSubtype = true + } + } + if (!isEmbeddedFile && !isJsonSubtype) continue + if (dictHasFlateFilter(entries)) { + const inflated = await inflateFlate(obj.contents) + if (inflated) return inflated + } + return obj.contents + } + return null } diff --git a/tests/unit/pdf.attachment.test.ts b/tests/unit/pdf.attachment.test.ts new file mode 100644 index 00000000..7a024f29 --- /dev/null +++ b/tests/unit/pdf.attachment.test.ts @@ -0,0 +1,40 @@ +import { describe, it, expect } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { attachReportJson, extractReportJson } from '@/pdf/attachment' +import type { Report } from '@/domain/schema/report' + +const report: Report = { + version: 1, + id: 'r1', + createdAt: '2026-05-18T10:00:00Z', + date: '2026-05-18', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: 'tout va bien', + recommendations: 'continuer', +} + +describe('PDF attachment roundtrip', () => { + it('attaches and extracts the report JSON', async () => { + const doc = await PDFDocument.create() + doc.addPage() + await attachReportJson(doc, report) + const bytes = await doc.save() + + const reopened = await PDFDocument.load(bytes) + const out = await extractReportJson(reopened) + expect(out.conclusion).toBe('tout va bien') + expect(out.animal.name).toBe('Mistral') + expect(out.version).toBe(1) + }) + + it('throws on PDFs without the attachment', async () => { + const doc = await PDFDocument.create() + doc.addPage() + const bytes = await doc.save() + const reopened = await PDFDocument.load(bytes) + await expect(extractReportJson(reopened)).rejects.toThrow() + }) +})