/** * R2 freeze, part b (R2 plan §5 "Oracles"): the behaviour of the TypeScript report and * archive functions on the inputs no suite pins (JavaScript truthiness, numeric literals, * prototype keys, lone surrogates, the envelope decision table, rebase labels, snapshot * caps and depth), and the accept / refuse verdict of the Zod schemas on hostile inputs. * `MAKE_R2_ORACLES=1` writes `crates/core/tests/oracles/{characterisation,verdicts}.json` * from these functions; otherwise the committed files are asserted against them, so the Rust * port is checked against what the TypeScript really did. */ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import type { z } from 'zod' import { BrandingSchema, ENVELOPE_FORMAT, ENVELOPE_VERSION, PdfLabelSetSchema, ReferenceSchema, ReportArchiveEnvelopeSchema, ReportMigrationMapSchema, ReportSchema, ReportV2Schema, SheetSnapshotSchema, SnapshotError, UnsupportedReportVersionError, assertSnapshot, buildSheetIndex, buildSheetSnapshot, createEmptySheetDocument, readArchiveDocument, readReportDocument, rebaseReportOnSheet, validateSheetDocument, type AnatomicalSheetDocument, type Report, type SheetRef, type SnapshotSource, } from '../src' import { sampleBranding, sampleLabels } from './archive.branding-labels.test' import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' import full from './fixtures/report-v2.full.json' import minimal from './fixtures/report-v2.minimal.json' const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..') const OUT = resolve(ROOT, 'crates/core/tests/oracles') const MAKE = process.env.MAKE_R2_ORACLES === '1' /** A backslash, so no escape sequence is typed literally in this file. */ const BS = String.fromCharCode(92) const LONE = `${BS}ud800` const SHA = 'a'.repeat(64) const SHA_B = 'b'.repeat(64) const REF_A: SheetRef = { sheetId: 'sheet-1', versionId: null, documentSha256: SHA, } const REF_B: SheetRef = { sheetId: 'sheet-1', versionId: 'v2', documentSha256: SHA_B, } const SVG = '' type Json = unknown const text = (value: Json) => JSON.stringify(value) const clone = (value: T): T => JSON.parse(JSON.stringify(value)) as T // --------------------------------------------------------------------------- // Inputs shared with the Rust side (as texts, so both sides parse the same bytes) const TEST_MAP = { schema_version: 1, sheet: REF_A, main_view_id: 'main', views: { head: 'head' }, annotations: { 'point-mpbwyyc9': { id: 'c7-t1', name: { fr: 'Charnière C7-T1 (cervico-thoracique)', en: 'C7-T1 (Cervicothoracic)', }, }, 'point-mpbwtst0': { id: 'hip', name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, }, 'zone-mpbx5hx2': { id: 'cervical', name: { fr: 'Vertèbres cervicales', en: '' }, }, 'point-mpbyo7zq': { id: 'atm', name: { fr: 'ATM', en: 'TMJ' } }, }, finding_paths: { 'c7-t1/c7-t1-dysfunctions/segmental/fixation': 'c7-t1/c7-t1-dysfunctions/segmental/fixation', 'hip/hip-dysfunctions/articular/restriction-flexion': 'hip/hip-dysfunctions/articular/restriction-flexion', 'cervical/cervical-observations/stumbling-proprioceptive': 'cervical/cervical-consultation-reasons/stumbling-proprioceptive', 'atm/atm-observations/headshaking': null, 'odd/no-slash': 'zone-only', 'odd/empty': '', 'odd/double': 'zone//leaf', }, } const PROTO_MAP_TEXT = text(TEST_MAP) .replace('"views":{', '"views":{"__proto__":"polluted-view",') .replace( '"annotations":{', '"annotations":{"__proto__":{"id":"polluted","name":{"fr":"x","en":"x"}},', ) const MAPS: Record = { test: text(TEST_MAP), proto: PROTO_MAP_TEXT, } function sliceB(): AnatomicalSheetDocument { const doc = horseSlice() doc.annotations = doc.annotations.filter( (a) => a.id !== 'atm' && a.id !== 'head-trigger', ) const hip = doc.finding_zones.find((z) => z.id === 'hip')! hip.categories[0]!.children = hip.categories[0]!.children.filter( (n) => n.id !== 'articular', ) return doc } const DOCUMENTS = { slice: horseSlice(), sliceB: sliceB() } type SheetName = keyof typeof DOCUMENTS const SHEET_REFS: Record = { slice: REF_A, sliceB: REF_B } /** A sheet as the Rust side loads it (the bundled payload shape) and as TS indexes it. */ function bundle( name: SheetName, assets: Record, hashes: Record, ) { const ref = SHEET_REFS[name] return { status: 'draft', ref: { sheet_id: ref.sheetId, version_id: ref.versionId, document_sha256: ref.documentSha256, schema_version: 2, species_id: 'equine', }, document: DOCUMENTS[name], migrationMap: TEST_MAP, assets, assetHashes: hashes, } } const SHEETS = { slice: bundle( 'slice', { [HORSE_MAIN_ASSET_ID]: SVG }, { [HORSE_MAIN_ASSET_ID]: 'c'.repeat(64) }, ), sliceB: bundle('sliceB', { [HORSE_MAIN_ASSET_ID]: SVG }, {}), sliceNoHash: bundle('slice', { [HORSE_MAIN_ASSET_ID]: SVG }, {}), sliceNoSvg: bundle('slice', {}, {}), } type LoadedName = keyof typeof SHEETS function source(name: LoadedName): SnapshotSource { const b = SHEETS[name] return { status: 'draft', ref: { sheetId: b.ref.sheet_id, versionId: b.ref.version_id, documentSha256: b.ref.document_sha256, }, speciesId: b.ref.species_id, schemaVersion: b.ref.schema_version, document: b.document, assets: b.assets, assetHashes: b.assetHashes, } } function reportOn( ref: SheetRef, observations: Report['observations'] = [], ): Report { return ReportSchema.parse({ version: 3, id: 'r1', createdAt: '2026-10-10T10:00:00Z', date: '2026-10-10', practitioner: { name: 'Dr. Dupont' }, animal: { speciesId: 'equine', name: 'Mistral' }, owner: { name: 'Jean Martin' }, sheet: ref, observations, conclusion: 'c', recommendations: 'r', }) } /** The rebase suite's report on revision A, plus label cases for `??=`. */ function rebaseReport(ref: SheetRef): Report { return reportOn(ref, [ { id: 'obs-1', zones: [ { annotationId: 'hip', viewId: 'view-main', side: 'left', labelFrSnapshot: 'Hanche', labelEnSnapshot: 'Hip', }, { annotationId: 'atm', viewId: 'view-head' }, { annotationId: 'head-trigger', viewId: 'view-main' }, { annotationId: 'hip', viewId: 'ghost-view', labelFrSnapshot: 'Gardé' }, { annotationId: 'atm', viewId: 'view-head', labelFrSnapshot: '', side: 'right', }, { annotationId: 'gone', viewId: 'view-main', labelFrSnapshot: 'Ancien', unresolved: true, }, { annotationId: 'nowhere', viewId: 'view-main' }, ], findings: [ { findingZoneId: 'hip', path: ['hip-dysfunctions', 'articular', 'restriction-flexion'], labelFrSnapshot: 'Restriction en flexion', labelEnSnapshot: 'Flexion restriction', }, { findingZoneId: 'cervical', path: ['cervical-observations', 'stumbling-proprioceptive'], labelFrSnapshot: 'Trébuchements', labelEnSnapshot: 'Stumbling', requiresVetReferral: true, }, { findingZoneId: 'atm', path: ['atm-observations', 'headshaking'], labelFrSnapshot: 'Headshaking', labelEnSnapshot: 'Headshaking', unresolved: true, }, ], freeTextFindings: ['note'], severity: 'moderate', comment: '', }, ]) } /** A report on the slice whose findings exercise the snapshot pruning. */ function snapshotReport(): Report { return reportOn(REF_A, [ { id: 'obs-1', zones: [{ annotationId: 'hip', viewId: 'view-main' }], findings: [ { findingZoneId: 'hip', path: ['hip-dysfunctions', 'articular', 'restriction-flexion'], labelFrSnapshot: 'R', labelEnSnapshot: 'R', }, { findingZoneId: 'hip', path: ['hip-dysfunctions', 'articular', 'ghost-leaf'], labelFrSnapshot: 'G', labelEnSnapshot: 'G', unresolved: true, }, { findingZoneId: 'hip', path: ['hip-dysfunctions'], labelFrSnapshot: 'C', labelEnSnapshot: 'C', }, { findingZoneId: 'nowhere', path: ['x'], labelFrSnapshot: 'X', labelEnSnapshot: 'X', }, ], freeTextFindings: [], comment: '', }, ]) } // --------------------------------------------------------------------------- // Characterisation cases interface Case { name: string fn: | 'readReport' | 'readArchive' | 'rebase' | 'assertSnapshot' | 'buildSnapshot' input: string map?: string sheet?: LoadedName archived?: string | null output?: Json error?: { kind: string; found?: number | null } /** The TS result keeps a lone surrogate; Rust refuses the text (`lone_surrogate`, L1). */ l1?: true /** The outcome depends on the sheet integrity rules (fork A's validate.rs). */ needsRules?: true } function errorOf(error: unknown): Case['error'] { if (error instanceof UnsupportedReportVersionError) { return { kind: 'unsupported_version', found: error.foundVersion } } if (error instanceof SnapshotError) return { kind: error.reason } return { kind: 'invalid' } } function run(c: Case): Case { c = { ...c, name: `${c.fn}: ${c.name}` } try { const output = clone(compute(c)) return { ...c, output } } catch (error) { return { ...c, error: errorOf(error) } } } function compute(c: Case): Json { const map = ReportMigrationMapSchema.parse(JSON.parse(MAPS[c.map ?? 'test']!)) const input: unknown = JSON.parse(c.input) switch (c.fn) { case 'readReport': return readReportDocument(input, map) case 'readArchive': return readArchiveDocument(input, map) case 'rebase': { const archived = c.archived ? assertSnapshot(JSON.parse(c.archived)) : null const index = buildSheetIndex(source(c.sheet!)) return rebaseReportOnSheet(ReportSchema.parse(input), index, archived) } case 'assertSnapshot': return assertSnapshot(input) case 'buildSnapshot': return buildSheetSnapshot(source(c.sheet!), ReportSchema.parse(input)) } } /** Whether a snapshot inside the input fails the integrity rules (Rust stub until merge). */ function needsRules(c: Case): boolean { const input = JSON.parse(c.input) as Record | null const candidate = c.fn === 'readArchive' ? input?.sheetSnapshot : input const parsed = SheetSnapshotSchema.safeParse(candidate) return ( parsed.success && validateSheetDocument(parsed.data.document).some( (i) => i.severity === 'error', ) ) } const v2Minimal = () => ReportV2Schema.parse(minimal) const v2With = (observations: unknown[]) => ({ ...clone(minimal), observations, }) const v2Obs = ( zones: unknown[], findings: unknown[] = [], extra: object = {}, ) => ({ id: 'o', zones, findings, freeTextFindings: [], comment: '', ...extra, }) const v2Finding = (zoneId: string, path: string[], extra: object = {}) => ({ zoneId, path, labelFrSnapshot: 'F', labelEnSnapshot: 'F', ...extra, }) const v3 = () => reportOn(REF_A) const withVersion = (value: unknown, literal: string) => text(value).replace(/"version":\d+/, `"version":${literal}`) function readReportCases(): Case[] { const rr = (name: string, input: string, map?: string): Case => ({ name, fn: 'readReport', input, map, }) const zone = (z: object) => text(v2With([v2Obs([z])])) return [ rr('v2 full', text(full)), rr('v2 minimal', text(minimal)), rr( 'detailSourceId empty string → main view', zone({ boneId: 'point-mpbwtst0', detailSourceId: '' }), ), rr( 'detailSourceId mapped', zone({ boneId: 'point-mpbyo7zq', detailSourceId: 'head' }), ), rr( 'detailSourceId unknown key kept as view id', zone({ boneId: 'point-mpbyo7zq', detailSourceId: 'neck' }), ), rr( 'prototype keys as legacy ids', zone({ boneId: 'constructor', detailSourceId: '__proto__' }), ), rr( '__proto__ entries of the map are dropped', zone({ boneId: '__proto__', detailSourceId: '__proto__' }), 'proto', ), rr( 'empty legacy name kept as an empty snapshot', zone({ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C', index: 3 }] }), ), rr('vertebrae [] kept', zone({ boneId: 'zone-mpbx5hx2', vertebrae: [] })), rr('side copied', zone({ boneId: 'point-mpbwtst0', side: 'left' })), rr('unknown legacy zone flagged', zone({ boneId: 'point-unknown' })), rr( 'requiresVetReferral false dropped, true kept, side kept', text( v2With([ v2Obs( [], [ v2Finding( 'hip', ['hip-dysfunctions', 'articular', 'restriction-flexion'], { requiresVetReferral: false }, ), v2Finding( 'c7-t1', ['c7-t1-dysfunctions', 'segmental', 'fixation'], { requiresVetReferral: true, side: 'right' }, ), v2Finding('atm', ['atm-observations', 'headshaking']), v2Finding('nowhere', ['x']), v2Finding('constructor', ['__proto__']), ], ), ]), ), ), rr( 'mapped path without a slash fails the read', text(v2With([v2Obs([], [v2Finding('odd', ['no-slash'])])])), ), rr( 'mapped empty path fails the read', text(v2With([v2Obs([], [v2Finding('odd', ['empty'])])])), ), rr( 'mapped path with an empty segment fails the read', text(v2With([v2Obs([], [v2Finding('odd', ['double'])])])), ), ...(['légère', 'modérée', 'sévère'] as const).map((severity) => rr(`severity ${severity}`, text(v2With([v2Obs([], [], { severity })]))), ), rr( 'next appointment date', text({ ...clone(minimal), nextAppointment: { kind: 'date', date: '2026-11-01', extra: 1 }, }), ), rr( 'next appointment period', text({ ...clone(minimal), nextAppointment: { kind: 'period', text: '3 sem.' }, }), ), rr('v2 version written 2.0', withVersion(v2Minimal(), '2.0')), rr('v3 version written 3.0', withVersion(v3(), '3.0')), rr('v3 version written 3e0', withVersion(v3(), '3e0')), rr('v3 version 3.5', withVersion(v3(), '3.5')), rr('version as a string', text({ ...v3(), version: '3' })), rr('version 4', text({ ...v3(), version: 4 })), rr('version 1', text({ ...clone(minimal), version: 1 })), rr('no version', text({ hello: 'world' })), rr('an array', text([v3()])), rr('null', 'null'), rr('a number', '42'), rr( 'v3 unknown keys stripped', text({ ...v3(), extra: 1, practitioner: { name: 'P', x: 2 } }), ), rr( 'v3 optional field null refused', text({ ...v3(), nextAppointment: null }), ), rr( 'v3 vertebra index 2.0 and 1e20', text( reportOn(REF_A, [ { id: 'o', zones: [ { annotationId: 'a', viewId: 'v', vertebrae: [ { region: 'C', index: 2 }, { region: 'T', index: 1e20 }, ], }, ], findings: [], freeTextFindings: [], comment: '', }, ]), ).replace('"index":2', '"index":2.0'), ), rr( 'v3 unresolved false refused', text( reportOn(REF_A, [ { id: 'o', zones: [{ annotationId: 'a', viewId: 'v', unresolved: true }], findings: [], freeTextFindings: [], comment: '', }, ]), ).replace('"unresolved":true', '"unresolved":false'), ), rr( 'v3 localAnnotations entry refused', text({ ...v3(), localAnnotations: [{ x: 1 }] }), ), { ...rr( 'lone surrogate in a v3 conclusion', text({ ...v3(), conclusion: 'a' }).replace( '"conclusion":"a"', `"conclusion":"a${LONE}b"`, ), ), l1: true, }, { ...rr( 'lone surrogate in a v2 comment', text(v2With([v2Obs([], [], { comment: 'x' })])).replace( '"comment":"x"', `"comment":"${LONE}"`, ), ), l1: true, }, ] } function envelopeOn( report: unknown, patch: Record = {}, ): Record { return { format: ENVELOPE_FORMAT, envelopeVersion: ENVELOPE_VERSION, exportedAt: '2026-10-11T10:00:00.000Z', locale: 'fr', report, sheetSnapshot: clone(buildSheetSnapshot(source('slice'), snapshotReport())), branding: sampleBranding(), labels: { fr: sampleLabels(), en: sampleLabels() }, ...patch, } } function readArchiveCases(): Case[] { const ra = (name: string, input: string): Case => ({ name, fn: 'readArchive', input, }) const report = snapshotReport() const env = (patch: Record = {}) => envelopeOn(report, patch) const snap = () => clone(buildSheetSnapshot(source('slice'), report)) const brokenRule = snap() brokenRule.document.finding_zones = brokenRule.document.finding_zones.filter( (z) => z.id !== 'atm', ) const label513 = snap() label513.document.name.fr = 'x'.repeat(513) return [ ra('bare v3', text(report)), ra('bare v2', text(full)), ra('envelope v1 accepted', text(env())), ra( 'envelopeVersion written 1.0', text(env()).replace('"envelopeVersion":1', '"envelopeVersion":1.0'), ), ra( 'unknown envelope version keeps the report origin', text(env({ envelopeVersion: 2 })), ), ra( 'envelopeVersion as a string is no envelope', text(env({ envelopeVersion: '1' })), ), ra( 'wrapper: javascript site URL', text( env({ branding: { ...sampleBranding(), siteUrl: 'javascript:alert(1)' }, }), ), ), ra( 'wrapper: labels without en', text(env({ labels: { fr: sampleLabels() } })), ), ra('wrapper: locale de', text(env({ locale: 'de' }))), ra('wrapper: other format', text(env({ format: 'other' }))), ra( 'wrapper: unknown metadata key ignored', text(env({ futureField: { anything: true } })), ), ra( 'wrapper: __proto__ metadata key ignored', text(env()).replace('"format"', '"__proto__":{"polluted":true},"format"'), ), ra( 'snapshot: unknown key', text(env({ sheetSnapshot: { ...snap(), extra: 1 } })), ), ra('snapshot: missing', text(env({ sheetSnapshot: undefined }))), ra('snapshot: label over the cap', text(env({ sheetSnapshot: label513 }))), ra( 'snapshot: no asset (integrity)', text(env({ sheetSnapshot: { ...snap(), assets: [] } })), ), ra( 'snapshot: a sheet rule fails (integrity)', text(env({ sheetSnapshot: brokenRule })), ), ra( 'snapshot: another document hash', text( env({ sheetSnapshot: { ...snap(), ref: { ...snap().ref, documentSha256: 'f'.repeat(64) }, }, }), ), ), ra( 'snapshot: another sheet id', text( env({ sheetSnapshot: { ...snap(), ref: { ...snap().ref, sheetId: 'other' }, }, }), ), ), ra('v2 report inside an envelope', text(envelopeOn(full))), ra( 'unknown wrapped report version', text(envelopeOn({ ...report, version: 4 })), ), ra('envelope without report', text(envelopeOn(undefined))), ra('null', 'null'), ra('a string', '"report"'), ra('an array', text([report])), ] } function rebaseCases(): Case[] { const archivedA = text( buildSheetSnapshot(source('slice'), rebaseReport(REF_A)), ) const rb = ( name: string, report: Report, archived: string | null, sheet: LoadedName = 'sliceB', ): Case => ({ name, fn: 'rebase', input: text(report), sheet, archived, }) return [ rb('same sheet: untouched', rebaseReport(REF_B), archivedA), rb('other sheet with archived labels', rebaseReport(REF_A), archivedA), rb('other sheet without archive', rebaseReport(REF_A), null), rb( 'other sheet onto the slice itself', rebaseReport({ ...REF_A, documentSha256: 'e'.repeat(64) }), archivedA, 'slice', ), ] } function snapshotDepth(depth: number) { const snap = clone(buildSheetSnapshot(source('slice'), snapshotReport())) let node: Record = { id: 'leaf', name: { fr: 'l', en: 'l' }, description: {}, requires_vet_referral: false, reference_ids: [], review_status: 'inherited', children: [], } for (let level = depth - 2; level >= 1; level -= 1) { node = { ...node, id: `n${level}`, children: [node] } } snap.document.finding_zones[0]!.categories[0]!.children = [node as never] return snap } function snapshotCases(): Case[] { const as = (name: string, input: string): Case => ({ name, fn: 'assertSnapshot', input, }) const bs = (name: string, sheet: LoadedName, report: Report): Case => ({ name, fn: 'buildSnapshot', input: text(report), sheet, }) const snap = () => clone(buildSheetSnapshot(source('slice'), snapshotReport())) const astral = snap() astral.document.name.fr = '😀'.repeat(256) const astralOver = snap() astralOver.document.name.en = `x${'😀'.repeat(256)}` const otherAsset = snap() otherAsset.assets[0]!.svgAssetId = '00000000-0000-4000-8000-000000000009' return [ bs('pruned trees, unresolved and unknown paths', 'slice', snapshotReport()), bs('no asset hash', 'sliceNoHash', snapshotReport()), bs('no asset text', 'sliceNoSvg', snapshotReport()), bs('no finding', 'slice', reportOn(REF_A)), as('the slice snapshot', text(snap())), as('depth 8 accepted', text(snapshotDepth(8))), as('depth 9 refused before the shape', text(snapshotDepth(9))), as( 'garbage under a deep tree is caps first', text({ garbage: true, document: { finding_zones: [ { categories: [ snapshotDepth(9).document.finding_zones[0]!.categories[0], ], }, ], }, }), ), as( 'a shallow garbage tree is schema', text({ document: { finding_zones: [{ categories: [{ id: 'c' }] }] } }), ), as( 'finding_zones not an array', text({ document: { finding_zones: 'x' } }), ), as('unknown key', text({ ...snap(), extra: 1 })), as( '__proto__ key', text(snap()).replace('"status"', '"__proto__":{"polluted":1},"status"'), ), as('null', 'null'), as('labels of 256 astral characters (512 units)', text(astral)), as('a label of 513 units', text(astralOver)), as('no asset', text({ ...snap(), assets: [] })), as('a view reaching another asset', text(otherAsset)), as( 'schemaVersion written 2.0', text(snap()).replace('"schemaVersion":2', '"schemaVersion":2.0'), ), ] } function characterisation(): Case[] { return [ ...readReportCases(), ...readArchiveCases(), ...rebaseCases(), ...snapshotCases(), ].map((c) => { const done = run(c) return needsRules(c) ? { ...done, needsRules: true } : done }) } // --------------------------------------------------------------------------- // Verdicts of the Zod schemas interface Verdict { schema: string name: string input: string accepted: boolean } const SCHEMAS: Record = { Report: ReportSchema, ReportV2: ReportV2Schema, MigrationMap: ReportMigrationMapSchema, Branding: BrandingSchema, PdfLabelSet: PdfLabelSetSchema, SheetSnapshot: SheetSnapshotSchema, Envelope: ReportArchiveEnvelopeSchema, Reference: ReferenceSchema, } type Path = Array /** Every path to a value of `base`, skipping the subtrees `skip` names. */ function paths( value: unknown, skip: (path: Path) => boolean, prefix: Path = [], ): Path[] { if (skip(prefix)) return [] const own = prefix.length > 0 ? [prefix] : [] if (Array.isArray(value)) { return [ ...own, ...value.flatMap((item, i) => paths(item, skip, [...prefix, i])), ] } if (value !== null && typeof value === 'object') { return [ ...own, ...Object.entries(value).flatMap(([key, item]) => paths(item, skip, [...prefix, key]), ), ] } return own } function mutate( base: unknown, path: Path, change: ( parent: Record, key: string | number, ) => void, ) { const copy = clone(base) as Record let parent = copy for (const key of path.slice(0, -1)) parent = parent[key] as Record change(parent, path.at(-1)!) return copy } function wrongType(value: unknown): unknown { if (typeof value === 'string') return 1 if (typeof value === 'number') return '1' if (typeof value === 'boolean') return 'true' if (Array.isArray(value)) return {} return [] } /** Generic mutations at every path: delete, null, wrong type, empty string, numeric edges, extra key. */ function generic( schema: string, base: unknown, skip: (path: Path) => boolean, ): Array> { const out: Array> = [] const add = (name: string, value: unknown) => out.push({ schema, name, input: text(value) }) add('base', base) add('extra key at the root', { ...(base as object), zz: 1 }) for (const path of paths(base, skip)) { const at = path.join('.') const value = path.reduce( (v, k) => (v as Record)[k], base, ) if (typeof path.at(-1) === 'string') add( `${at}: deleted`, mutate(base, path, (p, k) => delete p[k]), ) add( `${at}: null`, mutate(base, path, (p, k) => (p[k] = null)), ) add( `${at}: wrong type`, mutate(base, path, (p, k) => (p[k] = wrongType(value))), ) if (typeof value === 'string') add( `${at}: empty`, mutate(base, path, (p, k) => (p[k] = '')), ) if (typeof value === 'number') { for (const n of [2.5, -1, 0, 1e20]) add( `${at}: ${n}`, mutate(base, path, (p, k) => (p[k] = n)), ) } if (value !== null && typeof value === 'object' && !Array.isArray(value)) { add( `${at}: extra key`, mutate(base, path, (p, k) => (p[k] = { ...(value as object), zz: 1 })), ) } } return out } function verdictBases() { const report = reportOn(REF_A, [ { id: 'o', zones: [ { annotationId: 'a', viewId: 'v', side: 'left', vertebrae: [{ region: 'C', index: 2 }], labelFrSnapshot: 'A', labelEnSnapshot: 'A', unresolved: true, }, ], findings: [ { findingZoneId: 'z', path: ['a', 'b'], labelFrSnapshot: 'F', labelEnSnapshot: 'F', requiresVetReferral: true, side: 'right', unresolved: true, }, ], freeTextFindings: ['t'], severity: 'mild', comment: 'c', }, ]) const withAppointment = { ...report, nextAppointment: { kind: 'date', date: '2026-11-01' }, } const v2 = { ...clone(minimal), observations: [ { id: 'o', zones: [ { boneId: 'b', detailSourceId: 'head', vertebrae: [{ region: 'Cd', index: 1 }], side: 'left', }, ], findings: [ v2Finding('z', ['a'], { requiresVetReferral: true, side: 'left' }), ], freeTextFindings: [], severity: 'modérée', comment: '', }, ], nextAppointment: { kind: 'period', text: 'x' }, } const document = createEmptySheetDocument({ species_id: 'equine', name: { fr: 'C', en: 'H' }, }) const snapshot = { status: 'published', ref: { ...REF_A, versionId: 'v1', schemaVersion: 2, speciesId: 'equine' }, document, assets: [ { svgAssetId: HORSE_MAIN_ASSET_ID, sha256: 'c'.repeat(64), svg: SVG }, ], } const envelope = { format: ENVELOPE_FORMAT, envelopeVersion: ENVELOPE_VERSION, exportedAt: '2026-10-11T10:00:00.000Z', locale: 'en', report: reportOn(REF_A), sheetSnapshot: snapshot, branding: sampleBranding(), labels: { fr: sampleLabels(), en: sampleLabels() }, } const reference = { id: 'atlas', type: 'book', citation: 'Atlas', url: 'https://example.org/a', doi: '10.1/x', } return { report: withAppointment, v2, snapshot, envelope, reference } } function verdictInputs(): Array> { const b = verdictBases() const none = () => false return [ ...generic('Report', b.report, none), ...generic('ReportV2', b.v2, none), ...generic('MigrationMap', TEST_MAP, none), ...generic('Branding', sampleBranding(), none), // Every key behaves the same: one label key per locale stands for the 25. ...generic( 'PdfLabelSet', { fr: sampleLabels(), en: sampleLabels() }, (path) => path.length === 2 && path[1] !== 'pdf.empty', ), // The document's own sites belong to the sheet contract (fork A's verdicts). ...generic( 'SheetSnapshot', b.snapshot, (path) => path[0] === 'document' && path.length > 1, ), ...generic('Envelope', b.envelope, (path) => path.length > 1), ...generic('Reference', b.reference, none), ...specific(b), ] } function specific( b: ReturnType, ): Array> { const out: Array> = [] const add = (schema: string, name: string, input: string) => out.push({ schema, name, input }) const report = text(b.report) add('Report', 'version 3.0', report.replace('"version":3', '"version":3.0')) add('Report', 'version 3e0', report.replace('"version":3', '"version":3e0')) add( 'Report', 'vertebra index 2.0', report.replace('"index":2', '"index":2.0'), ) add( 'Report', 'vertebra index 2e0', report.replace('"index":2', '"index":2e0'), ) add( 'Report', 'lone surrogate in a comment', report.replace('"comment":"c"', `"comment":"${LONE}"`), ) add( 'ReportV2', 'version 2.0', text(b.v2).replace('"version":2', '"version":2.0'), ) add( 'ReportV2', 'unknown legacy region', text(b.v2).replace('"region":"Cd"', '"region":"X"'), ) add( 'ReportV2', 'English severity', text(b.v2).replace('"modérée"', '"moderate"'), ) add( 'SheetSnapshot', 'schemaVersion 2.0', text(b.snapshot).replace('"schemaVersion":2', '"schemaVersion":2.0'), ) add( 'SheetSnapshot', 'upper-case uuid', text(b.snapshot).replace( HORSE_MAIN_ASSET_ID, HORSE_MAIN_ASSET_ID.toUpperCase(), ), ) add( 'SheetSnapshot', 'upper-case sha256', text(b.snapshot).replace('c'.repeat(64), 'C'.repeat(64)), ) add( 'SheetSnapshot', 'five assets', text({ ...b.snapshot, assets: Array(5).fill(b.snapshot.assets[0]) }), ) add( 'SheetSnapshot', 'status other', text({ ...b.snapshot, status: 'archived' }), ) add( 'Envelope', 'envelopeVersion 1.0', text(b.envelope).replace('"envelopeVersion":1', '"envelopeVersion":1.0'), ) add( 'Envelope', 'envelopeVersion 2', text({ ...b.envelope, envelopeVersion: 2 }), ) const labels = (value: string) => text({ fr: { ...sampleLabels(), 'pdf.subject': value }, en: sampleLabels(), }) add('PdfLabelSet', '256 characters', labels('x'.repeat(256))) add('PdfLabelSet', '257 characters', labels('x'.repeat(257))) add( 'PdfLabelSet', '128 astral characters (256 units)', labels('😀'.repeat(128)), ) add( 'PdfLabelSet', '128 astral characters and one more unit', labels(`x${'😀'.repeat(128)}`), ) add( 'PdfLabelSet', 'extra locale', text({ fr: sampleLabels(), en: sampleLabels(), de: sampleLabels() }), ) const credit = (fallbackText: string) => text({ ...sampleBranding(), poweredBy: { ...sampleBranding().poweredBy!, fallbackText }, }) add('Branding', 'fallback 128', credit('x'.repeat(128))) add('Branding', 'fallback 129', credit('x'.repeat(129))) add('Branding', 'fallback 64 astral', credit('😀'.repeat(64))) add('Branding', 'fallback 64 astral + 1', credit(`x${'😀'.repeat(64)}`)) add( 'Branding', 'base64 with three =', text({ ...sampleBranding(), headerLogo: { kind: 'png', base64: 'QUJD===' }, }), ) add( 'Branding', 'empty base64', text({ ...sampleBranding(), headerLogo: { kind: 'png', base64: '' } }), ) add( 'Branding', 'svg logo with extra key', text({ ...sampleBranding(), footerLogo: { kind: 'svg', svg: SVG, zz: 1 } }), ) add( 'Branding', 'image kind gif', text({ ...sampleBranding(), footerLogo: { kind: 'gif', svg: SVG } }), ) for (const url of [ 'https://münchen.de/', 'HTTP://a.example/', 'https://a.example:99999/', 'https://[::1]/', 'https://%zz/', 'http://a.example/%', 'https://a.example/a?b=c&d=e#f', 'https://', 'http://a b/', 'https://a.example/(x)', 'https://xn--mnchen-3ya.de/', 'https://user:pass@a.example/', 'https://a..example/', 'https://1.2.3.4/', 'https://999.2.3.4/', ]) { add( 'Branding', `site URL ${url}`, text({ ...sampleBranding(), siteUrl: url }), ) add('Reference', `url ${url}`, text({ ...b.reference, url })) } for (const url of [ 'https://例え.テスト/', 'Https://a.example/', 'ftp://a.example/', 'javascript:alert(1)', 'mailto:a@b.c', 'https:a.example', 'https:/a.example', ]) { add('Reference', `url ${url}`, text({ ...b.reference, url })) } add('Reference', 'doi empty', text({ ...b.reference, doi: '' })) add('Reference', 'type other', text({ ...b.reference, type: 'blog' })) add( 'Reference', 'url and doi absent (defaults)', text({ id: 'atlas', type: 'web', citation: 'C' }), ) add( 'MigrationMap', 'schema_version 1.0', text(TEST_MAP).replace('"schema_version":1', '"schema_version":1.0'), ) add( 'MigrationMap', 'empty view id', text({ ...TEST_MAP, views: { head: '' } }), ) add( 'MigrationMap', 'views as an array', text({ ...TEST_MAP, views: ['head'] }), ) add('MigrationMap', '__proto__ entries', PROTO_MAP_TEXT) return out } function verdicts(): Verdict[] { return verdictInputs().map((v) => { const parsed = SCHEMAS[v.schema]!.safeParse(JSON.parse(v.input)) return { ...v, accepted: parsed.success } }) } // --------------------------------------------------------------------------- /** One JSON line per entry: compact, still diffable case by case. */ function lines(list: readonly unknown[]): string { return `[\n${list.map((item) => JSON.stringify(item)).join(',\n')}\n]` } function freeze(name: string, content: string) { const file = resolve(OUT, name) if (MAKE) { mkdirSync(OUT, { recursive: true }) writeFileSync(file, content) } expect(readFileSync(file, 'utf8')).toBe(content) } describe('R2 characterisation oracles (frozen from the TypeScript domain)', () => { it('characterisation.json: report, archive, rebase and snapshot functions', () => { const cases = characterisation() expect(new Set(cases.map((c) => c.name)).size).toBe(cases.length) freeze( 'characterisation.json', `{"maps":${JSON.stringify(MAPS)},\n"sheets":${JSON.stringify(SHEETS)},\n"cases":${lines(cases)}}\n`, ) }) it('verdicts.json: accept / refuse of the Zod schemas on hostile inputs', () => { const list = verdicts() expect(list.some((v) => v.accepted)).toBe(true) expect(list.some((v) => !v.accepted)).toBe(true) freeze('verdicts.json', `${lines(list)}\n`) }) })