test(tests): R2 freeze — archive envelopes of the three golden reports and the frozen N-1 reader

Envelopes exported by the TypeScript domain before the Rust switch (FR, no
logos, fixed export time) are the semantic oracle of the switch (D-R11:
key order may change, values may not). The shipped Zod schemas are copied
verbatim under packages/core-wasm/tests/n-1 (develop 1a7ee7d) so a rollback
reader stays testable after packages/domain is deleted at R5.
This commit is contained in:
bchanot committed 2026-10-13 23:53:12 +02:00
1 parent 1a7ee7d9ac
commit 3114d67959
29 files changed
+8581 -46

No files matched your search

@@ -0,0 +1,44 @@
import {
AnatomicalSheetDocumentSchema,
SHEET_DOCUMENT_SCHEMA_VERSION,
type AnatomicalSheetDocument,
type LocalizedText,
} from './schema'
export interface NewSheetDocumentParams {
species_id: string
name: LocalizedText
}
export const MAIN_VIEW_ID = 'view-main'
/**
* Starting point of a new sheet: shape-valid so it can be saved as a draft
* at once, but not publishable until the main view gets its SVG asset.
*/
export function createEmptySheetDocument(
params: NewSheetDocumentParams,
): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse({
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
species_id: params.species_id,
name: params.name,
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: { regions: [] },
references: [],
categories: [],
views: [
{
id: MAIN_VIEW_ID,
kind: 'main',
name: { fr: 'Vue principale', en: 'Main view' },
svg_asset_id: null,
view_box: null,
},
],
annotations: [],
finding_zones: [],
})
}
@@ -0,0 +1,4 @@
export * from './schema'
export * from './validate'
export * from './create'
export * from './sheet-index'
@@ -0,0 +1,327 @@
import { z } from 'zod'
/**
* Canonical anatomical sheet document, schema_version 2.
*
* Shape contract of docs/development/ANATOMICAL_SHEET_MODEL.md §2. Every
* object is strict: a canonical document must not silently carry fields no
* version of the schema defines. Cross-references (view ids, zone ids,
* reference ids…) are checked by validateSheetDocument, not here, so a
* draft with dangling references can still be saved.
*
* Version 2 (Step 4c): shared bibliographic `references` registry cited by
* `reference_ids`, `review_status` on findings and annotations, optional
* `count_range` on vertebral regions. No version 1 document was ever
* published, so version 1 is not read any more.
*/
export const SHEET_DOCUMENT_SCHEMA_VERSION = 2
/** Ids are never derived from labels, so translations never move them. */
export const STABLE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
export const StableIdSchema = z.string().regex(STABLE_ID_PATTERN)
/** Region codes are free (C, T, L, S, Cd for the horse), case included. */
export const RegionCodeSchema = z
.string()
.regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/)
export const LocalizedTextSchema = z
.object({ fr: z.string().min(1), en: z.string().min(1) })
.strict()
export const LocalizedOptionalTextSchema = z
.object({ fr: z.string().optional(), en: z.string().optional() })
.strict()
/**
* How far the sheet content was checked against references. `inherited` =
* taken over from a previous source without review; `reviewed` = checked
* and cited; `to_confirm` = changed or added on documented grounds, still
* awaiting a professional's confirmation.
*/
export const ReviewStatusSchema = z.enum(['inherited', 'reviewed', 'to_confirm'])
const CountRangeSchema = z
.object({ min: z.number().int().min(1), max: z.number().int().min(1) })
.strict()
/**
* `count` is the usual number of vertebrae (what the picker shows by
* default); `count_range` states the documented individual variation so a
* report may record a vertebra beyond the usual count. Null = no variation.
*/
export const VertebralRegionSchema = z
.object({
code: RegionCodeSchema,
name: LocalizedTextSchema,
count: z.number().int().min(1),
count_range: CountRangeSchema.nullable().default(null),
})
.strict()
const HexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/)
export const AnnotationCategorySchema = z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
color: HexColorSchema.nullable(),
})
.strict()
const CoordinateSchema = z.number().finite()
export const ViewBoxSchema = z
.object({
min_x: CoordinateSchema,
min_y: CoordinateSchema,
width: CoordinateSchema.positive(),
height: CoordinateSchema.positive(),
})
.strict()
/** Null asset on a detail view means "parent asset cropped by view_box". */
const viewCommon = {
id: StableIdSchema,
name: LocalizedTextSchema,
svg_asset_id: z.string().uuid().nullable(),
view_box: ViewBoxSchema.nullable(),
}
const MainViewSchema = z
.object({ ...viewCommon, kind: z.literal('main') })
.strict()
const DetailViewSchema = z
.object({
...viewCommon,
kind: z.literal('detail'),
parent_view_id: StableIdSchema,
})
.strict()
/** Views form a tree: a detail names its parent, any depth. */
export const SheetViewSchema = z.discriminatedUnion('kind', [
MainViewSchema,
DetailViewSchema,
])
const CircleSchema = z
.object({
type: z.literal('circle'),
cx: CoordinateSchema,
cy: CoordinateSchema,
r: CoordinateSchema.positive(),
})
.strict()
const PolygonSchema = z
.object({
type: z.literal('polygon'),
points: z.array(z.tuple([CoordinateSchema, CoordinateSchema])).min(3),
})
.strict()
const PathSchema = z
.object({ type: z.literal('path'), d: z.string().min(1) })
.strict()
export const GeometrySchema = z.discriminatedUnion('type', [
CircleSchema,
PolygonSchema,
PathSchema,
])
/** Explicit on every annotation: absence no longer carries meaning. */
export const LateralitySchema = z.enum([
'unpaired',
'bilateral',
'left',
'right',
])
const annotationCommon = {
id: StableIdSchema,
view_id: StableIdSchema,
category_id: StableIdSchema,
laterality: LateralitySchema,
geometry: GeometrySchema.nullable(),
review_status: ReviewStatusSchema.default('inherited'),
/** Marker colour of this annotation; null = the category colour. */
color: HexColorSchema.nullable().default(null),
}
/** Observable annotations link to findings through one explicit field. */
const observableFields = {
...annotationCommon,
name: LocalizedTextSchema,
finding_zone_id: StableIdSchema.nullable(),
vertebral_region_code: RegionCodeSchema.nullable(),
}
const PointAnnotationSchema = z
.object({ ...observableFields, kind: z.literal('point') })
.strict()
const ZoneAnnotationSchema = z
.object({ ...observableFields, kind: z.literal('zone') })
.strict()
/** Navigation only: a trigger never carries findings. */
const DetailTriggerAnnotationSchema = z
.object({
...annotationCommon,
kind: z.literal('detail_trigger'),
name: LocalizedTextSchema.nullable(),
opens_view_id: StableIdSchema,
})
.strict()
export const AnnotationSchema = z.discriminatedUnion('kind', [
PointAnnotationSchema,
ZoneAnnotationSchema,
DetailTriggerAnnotationSchema,
])
/** Documents are shared across users: only web links, never javascript: URLs. */
const HttpUrlSchema = z
.string()
.url()
.refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected')
/**
* One bibliographic reference, declared once in the document and cited by
* id from any number of findings (an anatomy atlas backs hundreds of
* entries). `citation` is the human-readable form (author, title, edition,
* year, publisher or journal, location in the work when known).
*/
export const ReferenceSchema = z
.object({
id: StableIdSchema,
type: z.enum(['book', 'journal', 'standard', 'legal', 'web', 'manual']),
citation: z.string().min(1),
url: HttpUrlSchema.nullable().default(null),
doi: z.string().min(1).nullable().default(null),
})
.strict()
export type Reference = z.infer<typeof ReferenceSchema>
export type ReviewStatus = z.infer<typeof ReviewStatusSchema>
export type LocalizedText = z.infer<typeof LocalizedTextSchema>
export type LocalizedOptionalText = z.infer<typeof LocalizedOptionalTextSchema>
/** Parsed node: every optional key of the authoring form is filled in. */
export interface FindingNode {
id: string
name: LocalizedText
description: LocalizedOptionalText
requires_vet_referral: boolean
reference_ids: string[]
review_status: ReviewStatus
children: FindingNode[]
}
/** Authoring form: leaves stay lean, hundreds of them carry no empty keys. */
export interface FindingNodeInput {
id: string
name: LocalizedText
description?: LocalizedOptionalText
requires_vet_referral?: boolean
reference_ids?: string[]
review_status?: ReviewStatus
children?: FindingNodeInput[]
}
export const FindingNodeSchema: z.ZodType<
FindingNode,
z.ZodTypeDef,
FindingNodeInput
> = z.lazy(() =>
z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema.default({}),
requires_vet_referral: z.boolean().default(false),
reference_ids: z.array(StableIdSchema).default([]),
review_status: ReviewStatusSchema.default('inherited'),
children: z.array(FindingNodeSchema).default([]),
})
.strict(),
)
/** Typed business buckets; creators may add their own as 'custom'. */
export const FindingCategoryKindSchema = z.enum([
'dysfunction',
'consultation_reason',
'anamnesis',
'custom',
])
export const FindingCategorySchema = z
.object({
id: StableIdSchema,
kind: FindingCategoryKindSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema.default({}),
reference_ids: z.array(StableIdSchema).default([]),
review_status: ReviewStatusSchema.default('inherited'),
children: z.array(FindingNodeSchema),
})
.strict()
export const FindingZoneSchema = z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
categories: z.array(FindingCategorySchema),
})
.strict()
const AttributionSchema = z
.object({
authors: z.array(z.string().min(1)),
license: z.string().min(1).nullable(),
notes: z.string().min(1).nullable(),
})
.strict()
const VertebralConfigSchema = z
.object({ regions: z.array(VertebralRegionSchema) })
.strict()
export const AnatomicalSheetDocumentSchema = z
.object({
schema_version: z.literal(SHEET_DOCUMENT_SCHEMA_VERSION),
species_id: StableIdSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema,
scope_disclaimer: LocalizedOptionalTextSchema,
attribution: AttributionSchema,
vertebral_config: VertebralConfigSchema,
references: z.array(ReferenceSchema),
categories: z.array(AnnotationCategorySchema),
views: z.array(SheetViewSchema),
annotations: z.array(AnnotationSchema),
finding_zones: z.array(FindingZoneSchema),
})
.strict()
export type AnatomicalSheetDocument = z.output<
typeof AnatomicalSheetDocumentSchema
>
export type AnatomicalSheetDocumentInput = z.input<
typeof AnatomicalSheetDocumentSchema
>
export type VertebralRegion = z.infer<typeof VertebralRegionSchema>
export type AnnotationCategory = z.infer<typeof AnnotationCategorySchema>
export type ViewBox = z.infer<typeof ViewBoxSchema>
export type SheetView = z.infer<typeof SheetViewSchema>
export type Geometry = z.infer<typeof GeometrySchema>
export type Laterality = z.infer<typeof LateralitySchema>
export type Annotation = z.infer<typeof AnnotationSchema>
export type FindingCategoryKind = z.infer<typeof FindingCategoryKindSchema>
export type FindingCategory = z.output<typeof FindingCategorySchema>
export type FindingZone = z.output<typeof FindingZoneSchema>
@@ -0,0 +1,127 @@
import type {
AnatomicalSheetDocument,
Annotation,
FindingCategory,
FindingNode,
FindingZone,
LocalizedText,
SheetView,
VertebralRegion,
} from './schema'
/**
* Read-only lookups over a sheet document. Everything the editor and the
* PDF engine derive from the sheet (zone names, finding paths, spine
* regions, trigger targets) comes from the document here, by stable id:
* no label drives logic. The index keeps the source it was built from so a
* caller gets back exactly what it passed (a loaded sheet with its migration
* map, or an archived snapshot).
*/
/** The minimum a sheet source carries: provenance, document, SVG text by asset id. */
export interface SheetIndexSource {
ref: { documentSha256: string }
document: AnatomicalSheetDocument
assets: Readonly<Record<string, string>>
}
export type ObservableAnnotation = Extract<
Annotation,
{ kind: 'point' | 'zone' }
>
export interface SheetIndex<S extends SheetIndexSource = SheetIndexSource> {
sheet: S
mainView: SheetView
view(id: string): SheetView | undefined
annotation(id: string): Annotation | undefined
annotationsOfView(viewId: string): Annotation[]
findingZone(id: string): FindingZone | undefined
/** The category or node at a path, undefined when absent from the sheet. */
nodeAt(
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined
regions(): VertebralRegion[]
region(code: string): VertebralRegion | undefined
/** The annotation that opens the vertebra picker for a region on a view. */
spineAnnotation(
regionCode: string,
viewId: string,
): ObservableAnnotation | undefined
/** Whether an annotation opens the vertebra picker. */
isSpine(annotationId: string): boolean
name(annotation: Annotation): LocalizedText
}
/** The label in a locale, the other locale as fallback, '' when none. */
export function pickLabel(
text: LocalizedText | null | undefined,
locale: 'fr' | 'en',
): string {
if (!text) return ''
return locale === 'en' ? text.en || text.fr : text.fr || text.en
}
export function isObservable(
a: Annotation | undefined,
): a is ObservableAnnotation {
return a !== undefined && a.kind !== 'detail_trigger'
}
function nodeAtPath(
zone: FindingZone | undefined,
path: readonly string[],
): FindingCategory | FindingNode | undefined {
if (!zone || path.length === 0) return undefined
let node: FindingCategory | FindingNode | undefined = zone.categories.find(
(c) => c.id === path[0],
)
for (const segment of path.slice(1)) {
if (!node) return undefined
node = node.children.find((n) => n.id === segment)
}
return node
}
export function buildSheetIndex<S extends SheetIndexSource>(
sheet: S,
): SheetIndex<S> {
const { document } = sheet
const views = new Map(document.views.map((v) => [v.id, v]))
const annotations = new Map(document.annotations.map((a) => [a.id, a]))
const zones = new Map(document.finding_zones.map((z) => [z.id, z]))
const regions = new Map(
document.vertebral_config.regions.map((r) => [r.code, r]),
)
const mainView = document.views.find((v) => v.kind === 'main')
if (!mainView) throw new Error('sheet has no main view')
return {
sheet,
mainView,
view: (id) => views.get(id),
annotation: (id) => annotations.get(id),
annotationsOfView: (viewId) =>
document.annotations.filter((a) => a.view_id === viewId),
findingZone: (id) => zones.get(id),
nodeAt: (zoneId, path) => nodeAtPath(zones.get(zoneId), path),
regions: () => document.vertebral_config.regions,
region: (code) => regions.get(code),
spineAnnotation: (code, viewId) =>
document.annotations.find(
(a): a is ObservableAnnotation =>
isObservable(a) &&
a.view_id === viewId &&
a.vertebral_region_code === code,
),
isSpine: (id) => {
const a = annotations.get(id)
return isObservable(a) && a.vertebral_region_code !== null
},
name: (a) =>
a.kind === 'detail_trigger'
? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' })
: a.name,
}
}
@@ -0,0 +1,494 @@
import type {
AnatomicalSheetDocument,
Annotation,
FindingNode,
SheetView,
VertebralRegion,
} from './schema'
/**
* Integrity tier of the sheet model (ANATOMICAL_SHEET_MODEL.md §2.1).
*
* The shape tier (Zod) accepts dangling references so drafts can be saved
* mid-edit; this tier lists every inconsistency for the editor and gates
* publication. Each rule is one function; codes are part of the contract
* shared with the SQL re-check (private.sheet_document_issues).
*/
export type SheetIssueSeverity = 'error' | 'warning'
export interface SheetIssue {
code: string
severity: SheetIssueSeverity
path: string
message: string
}
type Rule = (doc: AnatomicalSheetDocument) => SheetIssue[]
type ObservableAnnotation = Exclude<Annotation, { kind: 'detail_trigger' }>
type TriggerAnnotation = Extract<Annotation, { kind: 'detail_trigger' }>
type DetailView = Extract<SheetView, { kind: 'detail' }>
/** A sibling level of the finding tree: categories or node children. */
interface FindingLevelItem {
id: string
reference_ids: readonly string[]
children: readonly FindingNode[]
}
function error(code: string, path: string, message: string): SheetIssue {
return { code, severity: 'error', path, message }
}
function warning(code: string, path: string, message: string): SheetIssue {
return { code, severity: 'warning', path, message }
}
/** Indexes of entries whose value already appeared earlier in the list. */
function repeatedIndexes(values: readonly string[]): number[] {
const seen = new Set<string>()
const repeated: number[] = []
values.forEach((value, index) => {
if (seen.has(value)) repeated.push(index)
seen.add(value)
})
return repeated
}
function duplicateIssues(
values: readonly string[],
code: string,
pathOf: (index: number) => string,
): SheetIssue[] {
return repeatedIndexes(values).map((index) =>
error(code, pathOf(index), `Duplicate id "${values[index]}"`),
)
}
function isObservable(
annotation: Annotation,
): annotation is ObservableAnnotation {
return annotation.kind !== 'detail_trigger'
}
function isTrigger(annotation: Annotation): annotation is TriggerAnnotation {
return annotation.kind === 'detail_trigger'
}
function viewsById(doc: AnatomicalSheetDocument): Map<string, SheetView> {
const byId = new Map<string, SheetView>()
for (const view of doc.views) if (!byId.has(view.id)) byId.set(view.id, view)
return byId
}
/** Rendering starts from a single root drawing. */
const checkMainViewCount: Rule = (doc) => {
const count = doc.views.filter((view) => view.kind === 'main').length
if (count === 1) return []
return [
error('view.main.count', 'views', `Expected 1 main view, found ${count}`),
]
}
const checkViewIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.views.map((view) => view.id),
'view.id.duplicate',
(index) => `views[${index}].id`,
)
const checkViewParentsExist: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' && !byId.has(view.parent_view_id)
? [
error(
'view.parent.missing',
`views[${index}].parent_view_id`,
`Parent view "${view.parent_view_id}" does not exist`,
),
]
: [],
)
}
/**
* True when the parent chain loops before reaching the main view. A
* missing parent ends the walk: that case is view.parent.missing.
*/
function loopsBeforeMain(view: DetailView, byId: Map<string, SheetView>) {
const visited = new Set<string>([view.id])
let current: SheetView = view
while (current.kind === 'detail') {
const parent = byId.get(current.parent_view_id)
if (!parent) return false
if (visited.has(parent.id)) return true
visited.add(parent.id)
current = parent
}
return false
}
const checkViewParentCycles: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' && loopsBeforeMain(view, byId)
? [
error(
'view.parent.cycle',
`views[${index}].parent_view_id`,
`Parent chain of "${view.id}" never reaches the main view`,
),
]
: [],
)
}
function isOpenedFromParent(
view: DetailView,
doc: AnatomicalSheetDocument,
): boolean {
return doc.annotations.some(
(annotation) =>
isTrigger(annotation) &&
annotation.opens_view_id === view.id &&
annotation.view_id === view.parent_view_id,
)
}
/** A detail view nobody can open is dead content for the practitioner. */
const checkViewsReachable: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' &&
byId.has(view.parent_view_id) &&
!isOpenedFromParent(view, doc)
? [
error(
'view.unreachable',
`views[${index}]`,
`No detail_trigger in "${view.parent_view_id}" opens "${view.id}"`,
),
]
: [],
)
}
/** Every view must have something to draw: its own asset or a crop. */
function viewAssetIssue(view: SheetView, index: number): SheetIssue[] {
if (view.svg_asset_id !== null) return []
if (view.kind === 'main') {
return [
error(
'view.asset.missing',
`views[${index}].svg_asset_id`,
`Main view "${view.id}" has no SVG asset`,
),
]
}
if (view.view_box !== null) return []
return [
error(
'view.asset.missing',
`views[${index}].view_box`,
`Detail view "${view.id}" has neither an asset nor a view_box`,
),
]
}
const checkViewAssets: Rule = (doc) => doc.views.flatMap(viewAssetIssue)
/** Report points are keyed by annotation id across every view. */
const checkAnnotationIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.annotations.map((annotation) => annotation.id),
'annotation.id.duplicate',
(index) => `annotations[${index}].id`,
)
const checkAnnotationViews: Rule = (doc) => {
const byId = viewsById(doc)
return doc.annotations.flatMap((annotation, index) =>
byId.has(annotation.view_id)
? []
: [
error(
'annotation.view.missing',
`annotations[${index}].view_id`,
`View "${annotation.view_id}" does not exist`,
),
],
)
}
const checkAnnotationCategories: Rule = (doc) => {
const ids = new Set(doc.categories.map((category) => category.id))
return doc.annotations.flatMap((annotation, index) =>
ids.has(annotation.category_id)
? []
: [
error(
'annotation.category.missing',
`annotations[${index}].category_id`,
`Category "${annotation.category_id}" does not exist`,
),
],
)
}
/** A trigger opens a direct child of the view it is drawn in. */
function opensChildOfOwnView(
trigger: TriggerAnnotation,
byId: Map<string, SheetView>,
): boolean {
const target = byId.get(trigger.opens_view_id)
return target?.kind === 'detail' && target.parent_view_id === trigger.view_id
}
const checkTriggerTargets: Rule = (doc) => {
const byId = viewsById(doc)
return doc.annotations.flatMap((annotation, index) =>
isTrigger(annotation) && !opensChildOfOwnView(annotation, byId)
? [
error(
'annotation.opens_view.invalid',
`annotations[${index}].opens_view_id`,
`"${annotation.opens_view_id}" is not a detail child of ` +
`"${annotation.view_id}"`,
),
]
: [],
)
}
const checkAnnotationFindingZones: Rule = (doc) => {
const ids = new Set(doc.finding_zones.map((zone) => zone.id))
return doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) &&
annotation.finding_zone_id !== null &&
!ids.has(annotation.finding_zone_id)
? [
error(
'annotation.finding_zone.missing',
`annotations[${index}].finding_zone_id`,
`Finding zone "${annotation.finding_zone_id}" does not exist`,
),
]
: [],
)
}
const checkAnnotationRegions: Rule = (doc) => {
const codes = new Set(doc.vertebral_config.regions.map((r) => r.code))
return doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) &&
annotation.vertebral_region_code !== null &&
!codes.has(annotation.vertebral_region_code)
? [
error(
'annotation.region.missing',
`annotations[${index}].vertebral_region_code`,
`Vertebral region "${annotation.vertebral_region_code}" ` +
'is not configured',
),
]
: [],
)
}
/** Allowed in a draft, but a click on it would offer nothing to record. */
const checkAnnotationsHaveFindings: Rule = (doc) =>
doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) && annotation.finding_zone_id === null
? [
warning(
'annotation.no_findings',
`annotations[${index}].finding_zone_id`,
`Annotation "${annotation.id}" is linked to no finding zone`,
),
]
: [],
)
const checkRegionCodesUnique: Rule = (doc) =>
duplicateIssues(
doc.vertebral_config.regions.map((region) => region.code),
'region.code.duplicate',
(index) => `vertebral_config.regions[${index}].code`,
)
const checkCategoryIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.categories.map((category) => category.id),
'category.id.duplicate',
(index) => `categories[${index}].id`,
)
const checkFindingZoneIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.finding_zones.map((zone) => zone.id),
'finding_zone.id.duplicate',
(index) => `finding_zones[${index}].id`,
)
/**
* Findings are addressed by (zone, path[]) as Finding.path does today, so
* ids only need to be unique among siblings, at every depth.
*/
function siblingIssues(
nodes: readonly FindingLevelItem[],
path: string,
): SheetIssue[] {
const own = duplicateIssues(
nodes.map((node) => node.id),
'finding.id.duplicate',
(index) => `${path}[${index}].id`,
)
const nested = nodes.flatMap((node, index) =>
siblingIssues(node.children, `${path}[${index}].children`),
)
return [...own, ...nested]
}
const checkFindingSiblings: Rule = (doc) =>
doc.finding_zones.flatMap((zone, index) =>
siblingIssues(zone.categories, `finding_zones[${index}].categories`),
)
/** Allowed in a draft, but nothing on the drawing can reach this zone. */
const checkFindingZonesReferenced: Rule = (doc) => {
const referenced = new Set(
doc.annotations.filter(isObservable).map((a) => a.finding_zone_id),
)
return doc.finding_zones.flatMap((zone, index) =>
referenced.has(zone.id)
? []
: [
warning(
'finding_zone.unreferenced',
`finding_zones[${index}]`,
`No annotation points to finding zone "${zone.id}"`,
),
],
)
}
const checkReferenceIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.references.map((reference) => reference.id),
'reference.id.duplicate',
(index) => `references[${index}].id`,
)
/** A citation must point at a declared reference, at every depth. */
function citationIssues(
nodes: readonly FindingLevelItem[],
path: string,
known: ReadonlySet<string>,
): SheetIssue[] {
return nodes.flatMap((node, index) => {
const own = node.reference_ids.flatMap((id, refIndex) =>
known.has(id)
? []
: [
error(
'finding.reference.missing',
`${path}[${index}].reference_ids[${refIndex}]`,
`Reference "${id}" is not declared in references`,
),
],
)
const nested = citationIssues(
node.children,
`${path}[${index}].children`,
known,
)
return [...own, ...nested]
})
}
const checkFindingReferences: Rule = (doc) => {
const known = new Set(doc.references.map((reference) => reference.id))
return doc.finding_zones.flatMap((zone, index) =>
citationIssues(
zone.categories,
`finding_zones[${index}].categories`,
known,
),
)
}
/** The usual count must sit inside the documented variation. */
function countRangeIssue(region: VertebralRegion, index: number): SheetIssue[] {
const range = region.count_range
if (range === null) return []
if (range.min <= region.count && region.count <= range.max) return []
return [
error(
'region.count_range.invalid',
`vertebral_config.regions[${index}].count_range`,
`Region "${region.code}": count ${region.count} outside ` +
`${range.min}–${range.max}`,
),
]
}
const checkRegionCountRanges: Rule = (doc) =>
doc.vertebral_config.regions.flatMap(countRangeIssue)
const RULES: readonly Rule[] = [
checkMainViewCount,
checkViewIdsUnique,
checkViewParentsExist,
checkViewParentCycles,
checkViewsReachable,
checkViewAssets,
checkAnnotationIdsUnique,
checkAnnotationViews,
checkAnnotationCategories,
checkTriggerTargets,
checkAnnotationFindingZones,
checkAnnotationRegions,
checkAnnotationsHaveFindings,
checkRegionCodesUnique,
checkCategoryIdsUnique,
checkFindingZoneIdsUnique,
checkFindingSiblings,
checkFindingZonesReferenced,
checkReferenceIdsUnique,
checkFindingReferences,
checkRegionCountRanges,
]
/** Lists every integrity issue of a shape-valid document. */
export function validateSheetDocument(
doc: AnatomicalSheetDocument,
): SheetIssue[] {
return RULES.flatMap((rule) => rule(doc))
}
/** Warnings never block publication; errors always do. */
export function isPublishable(issues: readonly SheetIssue[]): boolean {
return !issues.some((issue) => issue.severity === 'error')
}
export class SheetValidationError extends Error {
readonly issues: SheetIssue[]
constructor(issues: SheetIssue[]) {
const errors = issues.filter((issue) => issue.severity === 'error')
super(
`Sheet document is not publishable: ${errors.length} error(s), ` +
`first: ${errors[0]?.code ?? 'none'}`,
)
this.name = 'SheetValidationError'
this.issues = issues
}
}
/** TypeScript-side publication gate, mirrored by SQL at publish time. */
export function assertPublishable(doc: AnatomicalSheetDocument): void {
const issues = validateSheetDocument(doc)
if (!isPublishable(issues)) throw new SheetValidationError(issues)
}