test(tests): R4.1b writer oracles: O1 draw logs, O2 R3-build PDFs (real raster, store path), O3 pre-R2 envelope PDFs

This commit is contained in:
bchanot committed 2026-10-18 05:25:57 +02:00
1 parent 7a4297933d
commit 87b88739f8
35 files changed
+39810

No files matched your search

@@ -0,0 +1,351 @@
/**
* R4.1 freeze, writer oracles O1 to O3 (plan 2026-10-17 §B.5.1), recorded on
* the application export path with the Step 6 golden inputs (three reports,
* fr / en, nologos / logos, fixed 1×1 / 2×1 rasters) at FIXED_EXPORTED_AT:
* - O1, the complete draw log of every run, which the Step 6 text, images
* and links goldens must equal once rounded;
* - O2, the PDFs of those runs, one real-raster PDF (resvg, v2full's first
* observation) with every PNG it embedded, one PDF exported through the
* store path (D-R11 case);
* - O3, the frozen pre-R2 envelopes attached byte for byte by pdf-lib.
* `MAKE_R4_ORACLES=1` writes them; never again without an owner decision.
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib'
import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types'
import {
readAttachedDocument,
readAttachmentBytes,
type Rasterizer,
} from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { useReportStore } from '@/state/reportStore'
import { resvgRasterizer } from '../../../../packages/pdf/tests/helpers/resvg'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReportName,
} from '../helpers/goldenReports'
import {
brandingOf,
FIXTURES_DIR,
ONE_PX_PNG,
readGolden,
TWO_BY_ONE_PNG,
viewIdsOf,
type LogoMode,
} from '../helpers/goldens'
import {
checkBytesOracle,
checkJsonOracle,
drawLogOf,
FIXED_EXPORTED_AT,
R3_PDF_DIR,
R4_GOLDEN_DIR,
readPdfFacts,
recordFullDrawing,
sha256,
step6Images,
step6Links,
step6Texts,
STEP6_PDF_DIR,
type DrawLog,
} from '../helpers/r4-draw'
const raster = vi.hoisted(() => ({ rasterize: null as Rasterizer | null }))
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn<Rasterizer>((svg, size) =>
raster.rasterize!(svg, size),
),
}))
const logoMode = vi.hoisted(() => ({ current: 'nologos' as LogoMode }))
vi.mock('@/pdf/branding', async () => {
const { brandingOf } = await import('../helpers/goldens')
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
})
const MODES: readonly LogoMode[] = ['nologos', 'logos']
const LOCALES: readonly Locale[] = ['fr', 'en']
const REAL_DIR = resolve(R3_PDF_DIR, 'real')
const R2_DIR = resolve(FIXTURES_DIR, 'goldens/r2')
const R2_ENVELOPES = ['demo', 'v2full', 'v2unresolved'].map(
(name) => `${name}.fr.nologos`,
)
const REAL_RASTER_TIMEOUT = 120_000
let sheet: SheetIndex
let reports: Record<GoldenReportName, Report>
beforeAll(async () => {
sheet = await loadTestSheet()
reports = buildGoldenReports(sheet).reports
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(FIXED_EXPORTED_AT)
})
afterAll(() => {
useReportStore.getState().reset()
sessionStorage.clear()
vi.useRealTimers()
vi.restoreAllMocks()
})
interface Run {
report: Report
mode: LogoMode
locale: Locale
rasterize: Rasterizer
}
interface Exported {
pdf: Uint8Array
log: DrawLog
}
const fixedRaster =
(mode: LogoMode): Rasterizer =>
async () =>
mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
/** One export through `@/pdf/export`, drawn under the full recorder. */
async function exportRun(run: Run): Promise<Exported> {
raster.rasterize = run.rasterize
logoMode.current = run.mode
const recorder = recordFullDrawing()
try {
const { pdf, warnings } = await exportReportToPdf(run.report, sheet, {
locale: run.locale,
})
expect(warnings).toEqual([])
expect(recorder.unexpectedCalls()).toEqual([])
expect(recorder.state.documents.size).toBe(1)
return { pdf, log: drawLogOf(recorder, await readPdfFacts(pdf)) }
} finally {
recorder.stop()
}
}
describe.each(GOLDEN_REPORTS)('writer oracles of %s', (name) => {
describe.each(MODES)('%s', (mode) => {
it.each(LOCALES)(
'%s: O1 draw log, O2 PDF, rounded = step6',
async (locale) => {
const run = { report: reports[name], mode, locale }
const out = await exportRun({ ...run, rasterize: fixedRaster(mode) })
const id = `${name}.${locale}.${mode}`
checkJsonOracle(resolve(R4_GOLDEN_DIR, `draw.${id}.json`), out.log)
checkBytesOracle(resolve(R3_PDF_DIR, `${id}.pdf`), out.pdf)
expect(step6Texts(out.log)).toEqual(readGolden(`text.${id}.json`))
expect(step6Images(out.log)).toEqual(readGolden(`images.${id}.json`))
expect(step6Links(out.log)).toEqual(readGolden(`links.${id}.json`))
},
)
})
})
type RasterSubject =
| { kind: 'logo'; slot: string }
| { kind: 'view'; observationId: string; viewId: string }
interface RasterCall {
index: number
svgSha256: string
widthPx: number
heightPx: number
png: Uint8Array | null
}
const LOGO_SLOTS = ['headerLogo', 'footerLogo', 'poweredBy', 'partner'] as const
function logoOf(branding: Branding, slot: (typeof LOGO_SLOTS)[number]) {
const value = branding[slot]
return value && 'kind' in value ? value : (value?.logo ?? null)
}
/**
* The engine's rasteriser calls in order: the SVG logos while embedding the
* branding (header, footer, powered-by, partner), then each observation's
* views, main first (packages/pdf export and observationPage).
*/
function rasterSubjects(branding: Branding, report: Report): RasterSubject[] {
const logos = LOGO_SLOTS.filter(
(slot) => logoOf(branding, slot)?.kind === 'svg',
).map((slot): RasterSubject => ({ kind: 'logo', slot }))
const snapshot = sheetSnapshot(sheet, report)
const views = report.observations.flatMap((o) =>
viewIdsOf(snapshot, o).map(
(viewId): RasterSubject => ({
kind: 'view',
observationId: o.id,
viewId,
}),
),
)
return [...logos, ...views]
}
/** resvg wrapped: each call is numbered when it is made, its PNG kept. */
function capturingResvg(calls: RasterCall[]): Rasterizer {
const resvg = resvgRasterizer()
return async (svg, size) => {
const call: RasterCall = {
index: calls.length,
svgSha256: sha256(svg),
widthPx: size.widthPx,
heightPx: size.heightPx,
png: null,
}
calls.push(call)
call.png = await resvg(svg, size)
return call.png
}
}
const REAL_NOTE =
'v2full reduced to its first observation (obs-1, main view), every other ' +
'field unchanged: the full report weighed 3 MB in real rasters.'
/** v2full with its first observation only: one view keeps the set small. */
function firstObservationOf(report: Report): Report {
return { ...report, observations: report.observations.slice(0, 1) }
}
describe('O2 real raster: v2full first observation, fr, logos, resvg', () => {
it(
'freezes the PDF, every PNG returned and the call manifest',
async () => {
const calls: RasterCall[] = []
const report = firstObservationOf(reports.v2full)
const { pdf } = await exportRun({
report,
mode: 'logos',
locale: 'fr',
rasterize: capturingResvg(calls),
})
const subjects = rasterSubjects(await brandingOf('logos'), report)
expect(subjects).toEqual([
{ kind: 'logo', slot: 'partner' },
{ kind: 'view', observationId: 'obs-1', viewId: 'main' },
])
expect(calls).toHaveLength(subjects.length)
checkBytesOracle(resolve(REAL_DIR, 'v2full-obs1.fr.logos.pdf'), pdf)
const manifest = calls.map(({ png, ...call }) => {
const file = `raster-${call.index}.png`
checkBytesOracle(resolve(REAL_DIR, file), png!)
const pngSha256 = sha256(png!)
return { ...call, png: file, pngSha256, subject: subjects[call.index] }
})
const manifestFile = resolve(REAL_DIR, 'manifest.json')
checkJsonOracle(manifestFile, { note: REAL_NOTE, calls: manifest })
},
REAL_RASTER_TIMEOUT,
)
})
type KeyOrder = { path: string; keys: string[] }
function keyOrders(value: unknown, path = 'report'): KeyOrder[] {
if (!value || typeof value !== 'object') return []
const entries = Object.entries(value)
const own = Array.isArray(value)
? []
: [{ path, keys: entries.map(([k]) => k) }]
return [...own, ...entries.flatMap(([k, v]) => keyOrders(v, `${path}.${k}`))]
}
/** Objects whose key sequence differs between two equal values. */
function keyOrderDifferences(a: unknown, b: unknown) {
const other = new Map(keyOrders(b).map((o) => [o.path, o.keys]))
return keyOrders(a)
.map((o) => ({ path: o.path, attachment: o.keys, core: other.get(o.path) }))
.filter((d) => JSON.stringify(d.attachment) !== JSON.stringify(d.core))
}
/** A partial practitioner, keys out of the contract order (name, cabinet, contact, siret). */
const EDITED_PRACTITIONER: Practitioner = {
contact: 'secretariat@example.test',
name: 'Dr. Claire Dupont-Martin',
}
describe('O2 store path: demo, next appointment set, practitioner edited', () => {
it('freezes the PDF and the store report; attachment order is D-R11', async () => {
sessionStorage.clear()
const store = useReportStore.getState()
expect(
store.hydrateImport({ report: reports.demo, archive: null }, sheet),
).toEqual({ ok: true })
store.setNextAppointment({ kind: 'date', date: '2026-11-20' })
store.setPractitioner(EDITED_PRACTITIONER)
const report = useReportStore.getState().report!
const { pdf } = await exportRun({
report,
mode: 'nologos',
locale: 'fr',
rasterize: fixedRaster('nologos'),
})
checkBytesOracle(resolve(R3_PDF_DIR, 'store-path.fr.nologos.pdf'), pdf)
checkJsonOracle(resolve(R3_PDF_DIR, 'store-path.report.json'), report)
const attached = (await readAttachedDocument(pdf)) as { report: unknown }
expect(keyOrders(attached.report)).toEqual(keyOrders(report))
const reread = importAttachment(attached, sheet).read.report
expect(reread).toEqual(attached.report)
const differences = keyOrderDifferences(attached.report, reread)
console.info('D-R11 key order, attachment vs core:', differences)
expect(differences.length).toBeGreaterThan(0)
})
})
interface EnvelopeMeta {
locale: 'fr' | 'en'
labels: Record<string, Record<string, string>>
report: { animal: { name: string }; practitioner: { name: string } }
}
/** The engine's file structure around a given attachment (export.ts, attachment/write.ts). */
async function envelopePdf(attachment: Uint8Array): Promise<Uint8Array> {
const envelope = JSON.parse(
new TextDecoder().decode(attachment),
) as EnvelopeMeta
const labels = envelope.labels[envelope.locale]
const title = `${labels['pdf.title.suffix.bilan']}${envelope.report.animal.name}`
const doc = await PDFDocument.create()
doc.setTitle(title)
doc.setAuthor(envelope.report.practitioner.name)
doc.setSubject(labels['pdf.subject'])
doc.setKeywords(['faunosteo-archive/1'])
doc.setCreationDate(FIXED_EXPORTED_AT)
doc.setModificationDate(FIXED_EXPORTED_AT)
const font = await doc.embedFont(StandardFonts.Helvetica)
doc.addPage(PageSizes.A4).drawText(title, { x: 40, y: 790, size: 12, font })
await doc.attach(attachment, 'osteo-report.json', {
mimeType: 'application/json',
description: 'Faunosteo report archive v1',
creationDate: FIXED_EXPORTED_AT,
modificationDate: FIXED_EXPORTED_AT,
afRelationship: AFRelationship.Data,
})
return doc.save({ useObjectStreams: false })
}
describe.each(R2_ENVELOPES)('O3 pre-R2 envelope PDF %s', (name) => {
// The R2 freeze wrote the decoded attachment text as is, and UTF-8
// round-trips JSON.stringify output: the file bytes are the attachment.
it('carries the frozen bytes, read back as is', async () => {
const golden = new Uint8Array(
readFileSync(resolve(R2_DIR, `envelope.${name}.json`)),
)
const pdf = await envelopePdf(golden)
checkBytesOracle(resolve(STEP6_PDF_DIR, `envelope.${name}.pdf`), pdf)
const read = await readAttachmentBytes(pdf)
expect(Buffer.from(read).equals(Buffer.from(golden))).toBe(true)
expect(await readAttachedDocument(pdf)).toEqual(
JSON.parse(new TextDecoder().decode(golden)),
)
})
})