refactor(pdf): R4.8 the TypeScript PDF engine leaves: packages/pdf, pdf-lib, the TS CLI and import path, the oracle generators deleted; test read-back on an own reader of the writer's files (pdfFile.ts), view goldens from the session's SVGs, import helper on the module's reader, N-1 scanner exported by core-wasm/n-1; app no longer depends on @faunosteo/domain; r4.census suite

This commit is contained in:
bchanot committed 2026-10-19 12:17:01 +02:00
1 parent 77e11a53e4
commit 0dc1ba27c7
96 files changed
+743 -15769

No files matched your search

+80 -69
View File
@@ -6,36 +6,45 @@
* archive PDFs, migrated without silent loss.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { AFRelationship, PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation, Report } from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { defaultPdfLabels } from '@/pdf/labels'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
import { importReportFromPdf, ImportError } from '../helpers/pdfImport'
import {
PdfFile,
buildPdfWithAttachment,
nameOf,
textOf,
} from '../helpers/pdfFile'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
// The fixed 1×1 PNG for every raster; the view SVGs the session asks for are kept.
const raster = vi.hoisted(() => ({ svgs: [] as string[] }))
vi.mock('@/pdf/browserRasterizer', async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
return {
browserRasterizer: vi.fn(async (svg: string) => {
raster.svgs.push(svg)
return ONE_PX_PNG
}),
}
})
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
/** The layered reading the application does on import (the core's read part). */
/** The layered reading the application does on import (the core's reader). */
async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes, sheet)).read
return (await importReportFromPdf(bytes)).read
}
const pageCount = (bytes: Uint8Array) => PdfFile.parse(bytes).pages().length
/** The static PDF strings belong to the app's label set. */
const { fr, en } = defaultPdfLabels
@@ -44,6 +53,7 @@ const { fr, en } = defaultPdfLabels
* texts of its content streams, in draw order.
*/
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
raster.svgs = []
const bytes = await bytesOf(
(await exportReportToPdf(report, sheet, { locale })).pdf,
)
@@ -118,8 +128,7 @@ describe('export on a full v3 report (FR)', () => {
conclusion: 'ok',
})
const bytes = await exportPdf(report, 'fr')
const doc = await PDFDocument.load(bytes)
expect(doc.getPageCount()).toBe(2)
expect(pageCount(bytes)).toBe(2)
const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!)
expect(drawn.slice(zonesIdx + 1, zonesIdx + 6)).toEqual([
'Charnière C7-T1 (cervico-thoracique)',
@@ -156,19 +165,21 @@ describe('export on a full v3 report (FR)', () => {
}
})
// The engine draws only the observation's markers (the browser pipeline
// The core composes only the observation's markers (the browser pipeline
// hid the others with display="none"); the view facts are frozen in
// pdf.goldens.test.ts "highlighted views".
it('highlights the observation zones of a view and omits the other markers', () => {
// pdf.goldens.test.ts "highlighted views". The SVGs are the ones the
// session asked the rasteriser for: the bundled partner logo (the one SVG
// logo) first, then the main view, then the head.
it('highlights the observation zones of a view and omits the other markers', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const snapshot = sheetSnapshot(sheet, report) as EngineView[0]
const svg = composeHighlightedViewSvg(snapshot, 'main', fullObservation())
await exportPdf(report, 'fr')
expect(raster.svgs).toHaveLength(3)
const [svg, head] = raster.svgs.slice(1)
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
expect(svg).toContain('url(#osteo-halo)')
expect(svg).not.toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
const head = composeHighlightedViewSvg(snapshot, 'head', fullObservation())
expect(head).toContain('viewBox="60 100 500 380"')
expect(head).not.toContain('osteo-halo')
})
@@ -242,7 +253,7 @@ describe('PDF content on a two-observation report', () => {
it('draws free findings, comments, the conclusion page and the header on every page', async () => {
const report = fullReport()
const bytes = await exportPdf(report, 'fr')
const pages = (await PDFDocument.load(bytes)).getPageCount()
const pages = pageCount(bytes)
expect(drawn).toContain(fr['pdf.section.free_findings'])
expect(joined()).toContain('Sensibilité au garrot')
expect(joined()).toContain('Raideur au garrot')
@@ -260,11 +271,11 @@ describe('PDF content on a two-observation report', () => {
it('sets the PDF metadata and the archive keyword', async () => {
const bytes = await exportPdf(fullReport(), 'fr')
const doc = await PDFDocument.load(bytes)
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(doc.getAuthor()).toBe('Dr. Dupont')
expect(doc.getSubject()).toBe(fr['pdf.subject'])
expect(doc.getKeywords()).toContain('faunosteo-archive/1')
const info = PdfFile.parse(bytes).info().dict
expect(textOf(info, 'Title')).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(textOf(info, 'Author')).toBe('Dr. Dupont')
expect(textOf(info, 'Subject')).toBe(fr['pdf.subject'])
expect(textOf(info, 'Keywords')).toContain('faunosteo-archive/1')
})
it('embeds the four bundled logos without any network request', async () => {
@@ -289,20 +300,17 @@ describe('PDF content on a two-observation report', () => {
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
const bytes = await exportPdf(fullReport(), 'fr')
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
String(o),
)
const filespec = objects.find((o) => o.includes('/Type /Filespec'))!
expect(filespec).toContain('osteo-report.json')
expect(filespec).toContain('/AFRelationship /Data')
const utf16 = (text: string) =>
[...text]
.map((c) => c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0'))
.join('')
expect(filespec).toContain(utf16('Faunosteo report archive v1'))
const embedded = objects.find((o) => o.includes('/Type /EmbeddedFile'))!
expect(embedded).toContain('/Filter /FlateDecode')
const objects = PdfFile.parse(bytes).all()
const filespec = objects.find((o) => nameOf(o.dict, 'Type') === 'Filespec')!
expect(textOf(filespec.dict, 'F')).toBe('osteo-report.json')
expect(textOf(filespec.dict, 'UF')).toBe('osteo-report.json')
expect(nameOf(filespec.dict, 'AFRelationship')).toBe('Data')
expect(textOf(filespec.dict, 'Desc')).toBe('Faunosteo report archive v1')
const embedded = objects.find(
(o) => nameOf(o.dict, 'Type') === 'EmbeddedFile',
)!
expect(nameOf(embedded.dict, 'Filter')).toBe('FlateDecode')
expect(embedded.stream).not.toBeNull()
})
})
@@ -324,7 +332,11 @@ describe('a raster the browser cannot draw', () => {
locale: 'fr',
})
expect(warnings).toEqual([
{ kind: 'view_raster_failed', observationId: 'obs-full', viewId: 'head' },
{
kind: 'view_raster_failed',
observationId: 'obs-full',
viewId: 'head',
},
])
const bytes = await bytesOf(pdf)
const { images, texts } = await readDrawing(bytes)
@@ -349,19 +361,15 @@ describe('a raster the browser cannot draw', () => {
})
describe('attachment rejection', () => {
async function pdfWith(name: string, payload: unknown): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
return doc.save()
}
const pdfWith = (name: string, payload: unknown): Uint8Array =>
buildPdfWithAttachment(
name,
new TextEncoder().encode(JSON.stringify(payload)),
)
it('reports no_attachment for a foreign JSON attachment (no version)', async () => {
const bytes = await pdfWith('other.json', { hello: 'world' })
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
const bytes = pdfWith('other.json', { hello: 'world' })
await expect(importReportFromPdf(bytes)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
@@ -369,11 +377,18 @@ describe('attachment rejection', () => {
it('reports no_attachment for a v3 report failing validation', async () => {
const broken: Record<string, unknown> = { ...minimalReport(sheet) }
delete broken.sheet
const bytes = await pdfWith('osteo-report.json', broken)
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
const bytes = pdfWith('osteo-report.json', broken)
await expect(importReportFromPdf(bytes)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
it('reads the same attachment through the core when the report is sound', async () => {
const report = minimalReport(sheet)
const out = await readBack(pdfWith('osteo-report.json', report))
expect(out.origin).toBe('bare_v3')
expect(out.report).toEqual(report)
})
})
describe('import of the frozen v2 archive PDFs', () => {
@@ -451,14 +466,12 @@ describe('import of the frozen v2 archive PDFs', () => {
},
],
}
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify(v2)),
'osteo-report.json',
{ mimeType: 'application/json' },
const out = await readBack(
buildPdfWithAttachment(
'osteo-report.json',
new TextEncoder().encode(JSON.stringify(v2)),
),
)
const out = await readBack(await doc.save())
const [obs] = out.report.observations
expect(obs!.zones).toEqual([
expect.objectContaining({
@@ -494,17 +507,15 @@ describe('import of the frozen v2 archive PDFs', () => {
})
it('refuses unknown versions and unrelated PDFs with typed errors', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify({ version: 7 })),
const v7 = buildPdfWithAttachment(
'osteo-report.json',
{ mimeType: 'application/json' },
new TextEncoder().encode(JSON.stringify({ version: 7 })),
)
await expect(
importReportFromPdf(await doc.save(), sheet),
).rejects.toMatchObject({ kind: 'incompatible_version', foundVersion: 7 })
await expect(importReportFromPdf(v7)).rejects.toMatchObject({
kind: 'incompatible_version',
foundVersion: 7,
})
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(importReportFromPdf(fake, sheet)).rejects.toThrow(ImportError)
await expect(importReportFromPdf(fake)).rejects.toThrow(ImportError)
})
})