/** * The N-1 reader test (RUST_ARCHITECTURE_REVIEW III.3 rule 7, VI.3 R2 row): * every draft and archive the application writes through the Rust core must * stay readable by the build before R2, whose Zod schemas and readers are * frozen in `@faunosteo/core-wasm/n-1`. A rollback to that build then finds * every session the R2 build left behind (key order may differ: D-R11). */ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, } from 'vitest' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { readArchiveDocument, readReportDocument, ReportArchiveEnvelopeSchema, ReportSchema, } from '@faunosteo/core-wasm/n-1' import { readAttachmentBytes } from '@faunosteo/pdf' import { exportReportToPdf } from '@/pdf/export' import { importAttachment } from '@/pdf/import' import { useReportStore } from '@/state/reportStore' import { ARCHIVE_KEY, DRAFT_KEY } from '@/state/persistence' import type { SheetIndex } from '@/services/sheetIndex' import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens' import { archiveEnvelope, bundledMigrationMap, loadTestSheet, minimalReport, } from '../helpers/sheet' vi.mock('@/pdf/browserRasterizer', () => ({ browserRasterizer: vi.fn(async () => ONE_PX_PNG), })) vi.mock('@/pdf/branding', async () => { const { brandingOf } = await import('../helpers/goldens') return { loadBranding: vi.fn(() => brandingOf('nologos')) } }) let sheet: SheetIndex beforeAll(async () => { sheet = await loadTestSheet() vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) afterAll(() => vi.restoreAllMocks()) beforeEach(() => { sessionStorage.clear() useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0, }) }) const fixture = (name: string): unknown => JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8')) /** The draft mirror as the previous build reads it on a rollback. */ async function expectN1ReadsTheDraft(): Promise { const text = sessionStorage.getItem(DRAFT_KEY) expect(text).not.toBeNull() const data: unknown = JSON.parse(text!) expect(ReportSchema.safeParse(data).success).toBe(true) const read = readReportDocument(data, await bundledMigrationMap()) expect(read.report).toEqual(useReportStore.getState().report) } describe('drafts written through the core', () => { it('a new report', async () => { useReportStore.getState().initReport( { date: '2026-10-14', practitioner: { name: 'Dr. Dupont', cabinet: 'Équi' }, animal: { speciesId: 'equine', name: 'Mistral' }, owner: { name: 'Jean Martin' }, observations: [], conclusion: '', recommendations: '', nextAppointment: { kind: 'period', text: 'dans 3 semaines' }, }, sheet.sheet.ref, sheet, ) await expectN1ReadsTheDraft() }) it('after the editor reducers (zones, sides, vertebrae, findings)', async () => { useReportStore.getState().initReport( { date: '2026-10-14', practitioner: { name: 'Dr. Dupont' }, animal: { speciesId: 'equine', name: 'Mistral' }, owner: { name: 'Jean Martin' }, observations: [], conclusion: '', recommendations: '', }, sheet.sheet.ref, sheet, ) const apply = (obs: ReturnType) => useReportStore.getState().updateObservation(0, obs) const current = () => useReportStore.getState().report!.observations[0]! const click = sheet.ops.zoneClick(current(), 'c7-t1') if (!click.ok || !click.value.observation) throw new Error('zone click') apply(click.value.observation) const sides = sheet.ops.addSides(current(), 'hip', ['left', 'right']) if (!sides.ok) throw new Error('add sides') apply(sides.value) const spine = sheet.ops.zoneClick(current(), 'cervical') if (!spine.ok || !spine.value.observation) throw new Error('spine click') apply(spine.value.observation) const synced = sheet.ops.syncVertebrae( current(), [ { region: 'C', index: 3 }, { region: 'L', index: 2 }, ], 'main', ) if (!synced.ok) throw new Error('vertebrae') apply(synced.value) const articular = sheet .findingZone('hip')! .categories.find((c) => c.id === 'hip-dysfunctions')! .children.find((n) => n.id === 'articular')! const finding = sheet.ops.toggleFinding({ observation: current(), findingZoneId: 'hip', path: ['hip-dysfunctions', 'articular', 'hypermobility'], leafPosition: articular.children.findIndex( (n) => n.id === 'hypermobility', ), side: 'left', }) if (!finding.ok) throw new Error(finding.kind) apply(finding.value) expect(current().zones.length).toBeGreaterThanOrEqual(4) expect(current().findings).toHaveLength(1) await expectN1ReadsTheDraft() }) it('after the restore of a v2 draft left by the previous version', async () => { sessionStorage.setItem( DRAFT_KEY, JSON.stringify(fixture('report-v2.full.json')), ) expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({ kind: 'restored', }) await expectN1ReadsTheDraft() }) it('after the import of an archive (draft and archive mirror)', async () => { const report = minimalReport(sheet, { conclusion: 'imported' }) const { read, rebase } = importAttachment( archiveEnvelope(sheet, report), sheet, ) useReportStore .getState() .hydrateImport({ report: rebase.report, archive: read.archive }, sheet) await expectN1ReadsTheDraft() const archive: unknown = JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!) expect(ReportArchiveEnvelopeSchema.safeParse(archive).success).toBe(true) }) }) describe('archives exported from core-built reports', () => { it.each([['report-v3.demo.json'], ['report-v2.full.json']])( 'the attachment of %s reads back through the N-1 reader', async (name) => { const { report } = importAttachment(fixture(name), sheet).read const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' }) const data: unknown = JSON.parse( new TextDecoder().decode(await readAttachmentBytes(pdf)), ) expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true) const outcome = readArchiveDocument(data, await bundledMigrationMap()) expect(outcome.origin).toBe('envelope_v1') expect(outcome.archive).not.toBeNull() expect(outcome.snapshotRejected).toBeUndefined() expect(outcome.report).toEqual(report) }, 30_000, ) })