feat(pdf): attach + extract report JSON via pdf-lib (with fallback traversal)
This commit is contained in:
1 parent
1c0b507458
commit
fb9a8fc3bd
2 files changed
+120
-19
No files matched your search
+80
-19
@@ -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<void> {
|
||||
throw new Error('not implemented')
|
||||
const FILENAME = 'osteo-report.json'
|
||||
|
||||
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
|
||||
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<Report> {
|
||||
throw new Error('not implemented')
|
||||
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> {
|
||||
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<Uint8Array | null> {
|
||||
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<Uint8Array | null> {
|
||||
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
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user