Files
faunosteo/packages/domain/src/anatomical-sheet/validate.ts
T

495 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}