From 36812f4625ad3041acbd40cd14197ac3cfb6ebc8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:42 +0200 Subject: [PATCH] feat(domain): canonical anatomical sheet document, integrity rules, tests --- packages/domain/eslint.config.js | 20 + packages/domain/package.json | 32 ++ .../domain/src/anatomical-sheet/create.ts | 43 ++ packages/domain/src/anatomical-sheet/index.ts | 3 + .../domain/src/anatomical-sheet/schema.ts | 280 +++++++++++ .../domain/src/anatomical-sheet/validate.ts | 426 +++++++++++++++++ packages/domain/src/index.ts | 1 + .../tests/anatomical-sheet.schema.test.ts | 117 +++++ .../tests/anatomical-sheet.validate.test.ts | 426 +++++++++++++++++ packages/domain/tests/fixtures/horse-slice.ts | 443 ++++++++++++++++++ packages/domain/tsconfig.json | 21 + packages/domain/vitest.config.ts | 9 + pnpm-lock.yaml | 28 ++ 13 files changed, 1849 insertions(+) create mode 100644 packages/domain/eslint.config.js create mode 100644 packages/domain/package.json create mode 100644 packages/domain/src/anatomical-sheet/create.ts create mode 100644 packages/domain/src/anatomical-sheet/index.ts create mode 100644 packages/domain/src/anatomical-sheet/schema.ts create mode 100644 packages/domain/src/anatomical-sheet/validate.ts create mode 100644 packages/domain/src/index.ts create mode 100644 packages/domain/tests/anatomical-sheet.schema.test.ts create mode 100644 packages/domain/tests/anatomical-sheet.validate.test.ts create mode 100644 packages/domain/tests/fixtures/horse-slice.ts create mode 100644 packages/domain/tsconfig.json create mode 100644 packages/domain/vitest.config.ts diff --git a/packages/domain/eslint.config.js b/packages/domain/eslint.config.js new file mode 100644 index 00000000..242d5a31 --- /dev/null +++ b/packages/domain/eslint.config.js @@ -0,0 +1,20 @@ +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { ignores: ['node_modules/**'] }, + { + files: ['**/*.ts'], + extends: [...tseslint.configs.recommended], + languageOptions: { + globals: { ...globals.node, ...globals.es2022 }, + }, + rules: { + '@typescript-eslint/no-explicit-any': 'warn', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + }, + }, +) diff --git a/packages/domain/package.json b/packages/domain/package.json new file mode 100644 index 00000000..9eee014e --- /dev/null +++ b/packages/domain/package.json @@ -0,0 +1,32 @@ +{ + "name": "@faunosteo/domain", + "version": "0.1.0", + "private": true, + "description": "Faunosteo pure domain model: canonical anatomical sheet document, Zod schemas and integrity rules", + "license": "MIT", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./anatomical-sheet": "./src/anatomical-sheet/index.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest", + "test:run": "vitest run", + "lint": "eslint . --max-warnings 0", + "build": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^20.19.41", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "typescript": "^5.7.2", + "typescript-eslint": "^8.19.0", + "vitest": "^3.2.7" + } +} diff --git a/packages/domain/src/anatomical-sheet/create.ts b/packages/domain/src/anatomical-sheet/create.ts new file mode 100644 index 00000000..cc61873d --- /dev/null +++ b/packages/domain/src/anatomical-sheet/create.ts @@ -0,0 +1,43 @@ +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: [] }, + 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: [], + }) +} diff --git a/packages/domain/src/anatomical-sheet/index.ts b/packages/domain/src/anatomical-sheet/index.ts new file mode 100644 index 00000000..0e850af9 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/index.ts @@ -0,0 +1,3 @@ +export * from './schema' +export * from './validate' +export * from './create' diff --git a/packages/domain/src/anatomical-sheet/schema.ts b/packages/domain/src/anatomical-sheet/schema.ts new file mode 100644 index 00000000..7bdaaf70 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/schema.ts @@ -0,0 +1,280 @@ +import { z } from 'zod' + +/** + * Canonical anatomical sheet document, schema_version 1. + * + * 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…) are + * checked by validateSheetDocument, not here, so a draft with dangling + * references can still be saved. + */ + +export const SHEET_DOCUMENT_SCHEMA_VERSION = 1 + +/** 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() + +export const VertebralRegionSchema = z + .object({ + code: RegionCodeSchema, + name: LocalizedTextSchema, + count: z.number().int().min(1), + }) + .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(), +} + +/** 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, +]) + +export const SourceRefSchema = z + .object({ + type: z.enum(['manual', 'journal', 'database', 'web']), + citation: z.string().min(1), + url: z.string().url().optional(), + }) + .strict() + +export type SourceRef = z.infer +export type LocalizedText = z.infer +export type LocalizedOptionalText = z.infer + +/** 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 + sources: SourceRef[] + 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 + sources?: SourceRef[] + 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), + sources: z.array(SourceRefSchema).default([]), + children: z.array(FindingNodeSchema).default([]), + }) + .strict(), +) + +/** Typed business buckets; creators may add their own as 'custom'. */ +export const FindingCategoryKindSchema = z.enum([ + 'dysfunction', + 'observation', + 'anamnesis', + 'custom', +]) + +export const FindingCategorySchema = z + .object({ + id: StableIdSchema, + kind: FindingCategoryKindSchema, + name: LocalizedTextSchema, + description: LocalizedOptionalTextSchema.default({}), + 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, + 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 +export type AnnotationCategory = z.infer +export type ViewBox = z.infer +export type SheetView = z.infer +export type Geometry = z.infer +export type Laterality = z.infer +export type Annotation = z.infer +export type FindingCategoryKind = z.infer +export type FindingCategory = z.output +export type FindingZone = z.output diff --git a/packages/domain/src/anatomical-sheet/validate.ts b/packages/domain/src/anatomical-sheet/validate.ts new file mode 100644 index 00000000..473de443 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/validate.ts @@ -0,0 +1,426 @@ +import type { + AnatomicalSheetDocument, + Annotation, + FindingNode, + SheetView, +} 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 +type TriggerAnnotation = Extract +type DetailView = Extract + +/** A sibling level of the finding tree: categories or node children. */ +interface FindingLevelItem { + id: 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() + 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 { + const byId = new Map() + 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) { + const visited = new Set([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, +): 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 RULES: readonly Rule[] = [ + checkMainViewCount, + checkViewIdsUnique, + checkViewParentsExist, + checkViewParentCycles, + checkViewsReachable, + checkViewAssets, + checkAnnotationIdsUnique, + checkAnnotationViews, + checkAnnotationCategories, + checkTriggerTargets, + checkAnnotationFindingZones, + checkAnnotationRegions, + checkAnnotationsHaveFindings, + checkRegionCodesUnique, + checkCategoryIdsUnique, + checkFindingZoneIdsUnique, + checkFindingSiblings, + checkFindingZonesReferenced, +] + +/** 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) +} diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts new file mode 100644 index 00000000..12ac5d72 --- /dev/null +++ b/packages/domain/src/index.ts @@ -0,0 +1 @@ +export * from './anatomical-sheet' diff --git a/packages/domain/tests/anatomical-sheet.schema.test.ts b/packages/domain/tests/anatomical-sheet.schema.test.ts new file mode 100644 index 00000000..3f7746ba --- /dev/null +++ b/packages/domain/tests/anatomical-sheet.schema.test.ts @@ -0,0 +1,117 @@ +import { + AnatomicalSheetDocumentSchema, + FindingNodeSchema, + StableIdSchema, + type AnatomicalSheetDocumentInput, +} from '../src' +import { horseSlice, horseSliceInput } from './fixtures/horse-slice' + +// Mutations deliberately break the typed shape, so the draft is untyped. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type LooseDoc = any +type Mutation = (doc: LooseDoc) => void + +/** Applies a mutation to the lean fixture and reports whether it parses. */ +function parsesAfter(mutate: Mutation): boolean { + const doc: LooseDoc = horseSliceInput() + mutate(doc) + return AnatomicalSheetDocumentSchema.safeParse(doc).success +} + +describe('AnatomicalSheetDocumentSchema', () => { + it('accepts the horse slice fixture', () => { + const result = AnatomicalSheetDocumentSchema.safeParse(horseSliceInput()) + expect(result.success).toBe(true) + }) + + it('accepts a parsed document again (output is valid input)', () => { + expect(AnatomicalSheetDocumentSchema.parse(horseSlice())).toEqual( + horseSlice(), + ) + }) + + const rejections: Array<[string, Mutation]> = [ + ['an unknown top-level key', (d) => (d.extra = true)], + ['an unknown nested key', (d) => (d.views[0].zoom = 2)], + ['a stable id with spaces', (d) => (d.annotations[0].id = 'Hip Joint')], + ['a stable id with an accent', (d) => (d.categories[0].id = 'É')], + ['an empty stable id', (d) => (d.finding_zones[0].id = '')], + ['schema_version 2', (d) => (d.schema_version = 2)], + ['a non-uuid svg_asset_id', (d) => (d.views[0].svg_asset_id = 'horse')], + [ + 'a polygon with 2 points', + (d) => + (d.annotations[1].geometry.points = [ + [0, 0], + [1, 1], + ]), + ], + ['a circle with r 0', (d) => (d.annotations[0].geometry.r = 0)], + ['a region count of 0', (d) => (d.vertebral_config.regions[0].count = 0)], + ['a missing en label', (d) => delete d.name.en], + [ + 'a detail view without parent_view_id', + (d) => delete d.views[1].parent_view_id, + ], + [ + 'a detail_trigger with finding_zone_id', + (d) => (d.annotations[3].finding_zone_id = 'hip'), + ], + [ + 'a finding category kind foo', + (d) => (d.finding_zones[0].categories[0].kind = 'foo'), + ], + ] + + it.each(rejections)('rejects %s', (_label, mutate) => { + expect(parsesAfter(mutate)).toBe(false) + }) +}) + +describe('StableIdSchema', () => { + it.each(['hip', 'c7-t1', 'view_main', '0'])('accepts %s', (id) => { + expect(StableIdSchema.safeParse(id).success).toBe(true) + }) + + it.each(['Hip Joint', 'É', '', '-hip', 'a'.repeat(65)])( + 'rejects %j', + (id) => { + expect(StableIdSchema.safeParse(id).success).toBe(false) + }, + ) +}) + +describe('FindingNodeSchema defaults', () => { + it('fills the optional keys of a lean node, recursively', () => { + const node = FindingNodeSchema.parse({ + id: 'articular', + name: { fr: 'Articulaire', en: 'Articular' }, + children: [{ id: 'flexion', name: { fr: 'Flexion', en: 'Flexion' } }], + }) + expect(node.description).toEqual({}) + expect(node.requires_vet_referral).toBe(false) + expect(node.sources).toEqual([]) + expect(node.children[0]).toEqual({ + id: 'flexion', + name: { fr: 'Flexion', en: 'Flexion' }, + description: {}, + requires_vet_referral: false, + sources: [], + children: [], + }) + }) + + it('keeps explicit values of the fixture', () => { + const doc = horseSlice() + const lameness = doc.finding_zones[0].categories[1].children[0] + expect(lameness.requires_vet_referral).toBe(true) + const trauma = doc.finding_zones[0].categories[2].children[0] + expect(trauma.sources).toHaveLength(1) + }) + + it('does not add default keys to the lean input', () => { + const input: AnatomicalSheetDocumentInput = horseSliceInput() + const leaf = input.finding_zones[2].categories[0].children[0] + expect(Object.keys(leaf)).toEqual(['id', 'name']) + }) +}) diff --git a/packages/domain/tests/anatomical-sheet.validate.test.ts b/packages/domain/tests/anatomical-sheet.validate.test.ts new file mode 100644 index 00000000..70c25436 --- /dev/null +++ b/packages/domain/tests/anatomical-sheet.validate.test.ts @@ -0,0 +1,426 @@ +import { + AnatomicalSheetDocumentSchema, + SheetValidationError, + assertPublishable, + createEmptySheetDocument, + isPublishable, + validateSheetDocument, + type AnatomicalSheetDocument, + type Annotation, + type SheetView, +} from '../src' +import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' + +/** [code, path] pairs: what each rule test pins down. */ +function issuesOf(doc: AnatomicalSheetDocument): Array<[string, string]> { + return validateSheetDocument(doc).map((issue) => [issue.code, issue.path]) +} + +function mutated( + mutate: (doc: AnatomicalSheetDocument) => void, +): AnatomicalSheetDocument { + const doc = horseSlice() + mutate(doc) + return doc +} + +function point(id: string, fields: Partial = {}): Annotation { + return { + id, + kind: 'point', + view_id: 'view-main', + category_id: 'articulations', + laterality: 'bilateral', + geometry: null, + name: { fr: id, en: id }, + finding_zone_id: 'hip', + vertebral_region_code: null, + ...fields, + } as Annotation +} + +function trigger(id: string, viewId: string, opensViewId: string) { + return { + id, + kind: 'detail_trigger', + view_id: viewId, + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: null, + name: null, + opens_view_id: opensViewId, + } satisfies Annotation +} + +function detailView(id: string, parentId: string) { + return { + id, + kind: 'detail', + name: { fr: id, en: id }, + parent_view_id: parentId, + svg_asset_id: HORSE_MAIN_ASSET_ID, + view_box: null, + } satisfies SheetView +} + +describe('validateSheetDocument on the horse slice', () => { + it('reports no error and no warning', () => { + expect(validateSheetDocument(horseSlice())).toEqual([]) + }) +}) + +describe('integrity rules (one mutation per code)', () => { + it('view.main.count', () => { + const doc = mutated((d) => { + d.views.push({ ...d.views[0], id: 'view-alt' }) + }) + expect(issuesOf(doc)).toEqual([['view.main.count', 'views']]) + }) + + it('view.main.count with no main view', () => { + const doc = mutated((d) => { + d.views = d.views.filter((view) => view.kind !== 'main') + }) + const codes = issuesOf(doc).map(([code]) => code) + expect(codes).toContain('view.main.count') + }) + + it('view.id.duplicate', () => { + const doc = mutated((d) => { + d.views.push(structuredClone(d.views[1])) + }) + expect(issuesOf(doc)).toEqual([['view.id.duplicate', 'views[2].id']]) + }) + + it('view.parent.missing', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-orphan', 'view-ghost')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.missing', 'views[2].parent_view_id'], + ]) + }) + + it('view.parent.cycle (terminates on a two-view loop)', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-a', 'view-b')) + d.views.push(detailView('view-b', 'view-a')) + d.annotations.push(trigger('open-a', 'view-b', 'view-a')) + d.annotations.push(trigger('open-b', 'view-a', 'view-b')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.cycle', 'views[2].parent_view_id'], + ['view.parent.cycle', 'views[3].parent_view_id'], + ]) + }) + + it('view.parent.cycle on a self-parent', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-self', 'view-self')) + d.annotations.push(trigger('open-self', 'view-self', 'view-self')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.cycle', 'views[2].parent_view_id'], + ]) + }) + + it('view.unreachable', () => { + const doc = mutated((d) => { + d.annotations = d.annotations.filter((a) => a.id !== 'head-trigger') + }) + expect(issuesOf(doc)).toEqual([['view.unreachable', 'views[1]']]) + }) + + it('view.asset.missing on the main view', () => { + const doc = mutated((d) => { + d.views[0].svg_asset_id = null + }) + expect(issuesOf(doc)).toEqual([ + ['view.asset.missing', 'views[0].svg_asset_id'], + ]) + }) + + it('view.asset.missing on a detail view without asset nor view_box', () => { + const doc = mutated((d) => { + d.views[1].view_box = null + }) + expect(issuesOf(doc)).toEqual([['view.asset.missing', 'views[1].view_box']]) + }) + + it('annotation.id.duplicate (across views)', () => { + const doc = mutated((d) => { + d.annotations.push({ ...structuredClone(d.annotations[4]) }) + d.annotations[6].view_id = 'view-main' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.id.duplicate', 'annotations[6].id'], + ]) + }) + + it('annotation.view.missing', () => { + const doc = mutated((d) => { + d.annotations.push(point('ghost', { view_id: 'view-ghost' })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.view.missing', 'annotations[6].view_id'], + ]) + }) + + it('annotation.category.missing', () => { + const doc = mutated((d) => { + d.annotations[0].category_id = 'os' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.category.missing', 'annotations[0].category_id'], + ]) + }) + + it('annotation.opens_view.invalid when the target is not a child', () => { + const doc = mutated((d) => { + d.annotations.push(trigger('loop', 'view-head', 'view-head')) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.opens_view.invalid', 'annotations[6].opens_view_id'], + ]) + }) + + it('annotation.opens_view.invalid when the target is main or absent', () => { + const doc = mutated((d) => { + d.annotations.push(trigger('to-main', 'view-main', 'view-main')) + d.annotations.push(trigger('to-ghost', 'view-main', 'view-ghost')) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.opens_view.invalid', 'annotations[6].opens_view_id'], + ['annotation.opens_view.invalid', 'annotations[7].opens_view_id'], + ]) + }) + + it('annotation.finding_zone.missing', () => { + const doc = mutated((d) => { + d.annotations.push(point('stifle', { finding_zone_id: 'stifle' })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.finding_zone.missing', 'annotations[6].finding_zone_id'], + ]) + }) + + it('annotation.region.missing', () => { + const doc = mutated((d) => { + const cervical = d.annotations[1] + if (cervical.kind === 'detail_trigger') throw new Error('fixture') + cervical.vertebral_region_code = 'Q' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.region.missing', 'annotations[1].vertebral_region_code'], + ]) + }) + + it('annotation.no_findings is a warning', () => { + const doc = mutated((d) => { + d.annotations.push(point('mandible', { finding_zone_id: null })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.no_findings', 'annotations[6].finding_zone_id'], + ]) + expect(validateSheetDocument(doc)[0].severity).toBe('warning') + }) + + it('region.code.duplicate', () => { + const doc = mutated((d) => { + const regions = d.vertebral_config.regions + regions.push(structuredClone(regions[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['region.code.duplicate', 'vertebral_config.regions[5].code'], + ]) + }) + + it('category.id.duplicate', () => { + const doc = mutated((d) => { + d.categories.push(structuredClone(d.categories[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['category.id.duplicate', 'categories[4].id'], + ]) + }) + + it('finding_zone.id.duplicate', () => { + const doc = mutated((d) => { + d.finding_zones.push(structuredClone(d.finding_zones[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['finding_zone.id.duplicate', 'finding_zones[5].id'], + ]) + }) + + it('finding.id.duplicate among finding categories', () => { + const doc = mutated((d) => { + const categories = d.finding_zones[0].categories + categories.push(structuredClone(categories[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['finding.id.duplicate', 'finding_zones[0].categories[3].id'], + ]) + }) + + it('finding.id.duplicate among nested children', () => { + const doc = mutated((d) => { + const articular = d.finding_zones[0].categories[0].children[0] + articular.children.push(structuredClone(articular.children[0])) + }) + expect(issuesOf(doc)).toEqual([ + [ + 'finding.id.duplicate', + 'finding_zones[0].categories[0].children[0].children[2].id', + ], + ]) + }) + + it('finding ids may repeat across different sibling arrays', () => { + const doc = mutated((d) => { + const hip = d.finding_zones[0].categories + hip[1].children.push(structuredClone(hip[0].children[0])) + }) + expect(issuesOf(doc)).toEqual([]) + }) + + it('finding_zone.unreferenced is a warning', () => { + const doc = mutated((d) => { + d.finding_zones.push({ + id: 'stifle', + name: { fr: 'Grasset', en: 'Stifle' }, + categories: [], + }) + }) + expect(issuesOf(doc)).toEqual([ + ['finding_zone.unreferenced', 'finding_zones[5]'], + ]) + expect(validateSheetDocument(doc)[0].severity).toBe('warning') + }) +}) + +describe('publication gate', () => { + it('accepts the fixture', () => { + expect(isPublishable(validateSheetDocument(horseSlice()))).toBe(true) + expect(() => assertPublishable(horseSlice())).not.toThrow() + }) + + it('accepts a document with warnings only', () => { + const doc = mutated((d) => { + d.annotations.push(point('mandible', { finding_zone_id: null })) + }) + expect(validateSheetDocument(doc)).toHaveLength(1) + expect(isPublishable(validateSheetDocument(doc))).toBe(true) + expect(() => assertPublishable(doc)).not.toThrow() + }) + + it('refuses a document with an error, exposing the issues', () => { + const doc = mutated((d) => { + d.views[0].svg_asset_id = null + }) + expect(isPublishable(validateSheetDocument(doc))).toBe(false) + let caught: unknown + try { + assertPublishable(doc) + } catch (thrown) { + caught = thrown + } + expect(caught).toBeInstanceOf(SheetValidationError) + const codes = (caught as SheetValidationError).issues.map((i) => i.code) + expect(codes).toEqual(['view.asset.missing']) + }) +}) + +describe('createEmptySheetDocument', () => { + const empty = () => + createEmptySheetDocument({ + species_id: 'equine', + name: { fr: 'Nouvelle fiche', en: 'New sheet' }, + }) + + it('is valid for the shape tier', () => { + expect(AnatomicalSheetDocumentSchema.safeParse(empty()).success).toBe(true) + expect(empty().views).toEqual([ + expect.objectContaining({ + id: 'view-main', + kind: 'main', + svg_asset_id: null, + view_box: null, + }), + ]) + }) + + it('is not publishable: the main view has no asset', () => { + const issues = validateSheetDocument(empty()) + expect(issues.map((issue) => issue.code)).toEqual(['view.asset.missing']) + expect(() => assertPublishable(empty())).toThrow(SheetValidationError) + }) +}) + +/** True for a { fr?, en? } label object, the only thing a translator edits. */ +function isLabel(value: unknown): value is Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const keys = Object.keys(value) + return keys.length > 0 && keys.every((key) => key === 'fr' || key === 'en') +} + +/** Rewrites every label with arbitrary strings, leaving all else intact. */ +function mapLabels( + value: unknown, + rewrite: (label: Record) => unknown, +): unknown { + if (isLabel(value)) return rewrite(value) + if (Array.isArray(value)) return value.map((v) => mapLabels(v, rewrite)) + if (value === null || typeof value !== 'object') return value + return Object.fromEntries( + Object.entries(value).map(([k, v]) => [k, mapLabels(v, rewrite)]), + ) +} + +/** Every id and reference: values of keys named id, *_id or code. */ +function collectIds(value: unknown, out: string[] = []): string[] { + if (Array.isArray(value)) value.forEach((v) => collectIds(v, out)) + else if (value !== null && typeof value === 'object') { + for (const [key, v] of Object.entries(value)) { + const isRef = key === 'id' || key.endsWith('_id') || key.endsWith('code') + if (isRef && typeof v === 'string') out.push(`${key}=${v}`) + else collectIds(v, out) + } + } + return out +} + +describe('ID stability under translation', () => { + it('keeps ids, references and validation output when labels change', () => { + const original = horseSlice() + let counter = 0 + const relabeled = AnatomicalSheetDocumentSchema.parse( + mapLabels(original, (label) => + Object.fromEntries( + Object.keys(label).map((locale) => [locale, `x${counter++}`]), + ), + ), + ) + expect(counter).toBeGreaterThan(50) + expect(JSON.stringify(relabeled)).not.toEqual(JSON.stringify(original)) + expect(collectIds(relabeled)).toEqual(collectIds(original)) + const strip = () => null + expect(mapLabels(relabeled, strip)).toEqual(mapLabels(original, strip)) + expect(validateSheetDocument(relabeled)).toEqual( + validateSheetDocument(original), + ) + }) + + it('keeps validation output identical on a broken document too', () => { + const broken = mutated((d) => { + d.annotations[0].category_id = 'os' + d.views[1].view_box = null + }) + const relabeled = mapLabels(broken, () => ({ fr: 'a', en: 'b' })) + expect(validateSheetDocument(relabeled as AnatomicalSheetDocument)).toEqual( + validateSheetDocument(broken), + ) + }) +}) diff --git a/packages/domain/tests/fixtures/horse-slice.ts b/packages/domain/tests/fixtures/horse-slice.ts new file mode 100644 index 00000000..4f05c2f1 --- /dev/null +++ b/packages/domain/tests/fixtures/horse-slice.ts @@ -0,0 +1,443 @@ +import { + AnatomicalSheetDocumentSchema, + type AnatomicalSheetDocument, + type AnatomicalSheetDocumentInput, + type FindingNodeInput, +} from '../../src' + +/** + * Reduced equine sheet built from the real assets: labels come from + * apps/app/public/species/equine/{Horse,Horse_head}.svg and from + * apps/app/src/domain/species/equine/pathologies.json. It exercises two + * views (one cropped detail), a trigger, a spine region, a bilateral joint, + * the three finding kinds, a two-level tree, a vet referral and a source. + * It references every finding zone, so it validates with zero issues. + */ + +export const HORSE_MAIN_ASSET_ID = '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8' + +function leaf(id: string, fr: string, en: string): FindingNodeInput { + return { id, name: { fr, en } } +} + +const ANAMNESIS = { + id: 'anamnesis', + kind: 'anamnesis', + name: { + fr: 'Anamnèse / facteurs rapportés', + en: 'Anamnesis / reported factors', + }, + description: { + fr: "Facteurs rapportés par le propriétaire lors de l'anamnèse", + }, +} as const + +const OBSERVATIONS_NAME = { + fr: 'Observations / motifs de consultation', + en: 'Observations / consultation reasons', +} + +const DYSFUNCTIONS_NAME = { + fr: 'Dysfonctions ostéopathiques', + en: 'Osteopathic dysfunctions', +} + +const TRAUMA = leaf( + 'trauma-direct', + 'Traumatisme rapporté (choc, chute)', + 'Reported trauma (blow, fall)', +) + +const STRESS = leaf( + 'stress-context', + 'Contexte de stress / changement', + 'Stress / change context', +) + +const HIP_ZONE = { + id: 'hip', + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + categories: [ + { + id: 'hip-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'articular', + name: { + fr: 'Restrictions de mobilité articulaire', + en: 'Articular mobility restrictions', + }, + children: [ + leaf( + 'restriction-flexion', + 'Restriction en flexion', + 'Flexion restriction', + ), + leaf( + 'restriction-extension', + 'Restriction en extension', + 'Extension restriction', + ), + ], + }, + ], + }, + { + id: 'hip-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + { + ...leaf( + 'limb-lameness', + 'Boiterie rapportée (membre concerné)', + 'Reported lameness (affected limb)', + ), + requires_vet_referral: true, + }, + ], + }, + { + ...ANAMNESIS, + children: [ + { + ...TRAUMA, + sources: [ + { + type: 'manual', + citation: 'Legacy equine catalog (pathologies.json)', + }, + ], + }, + ], + }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const CERVICAL_ZONE = { + id: 'cervical', + name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' }, + categories: [ + { + id: 'cervical-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'muscular', + name: { + fr: 'Tensions musculaires paravertébrales', + en: 'Paravertebral muscle tensions', + }, + children: [ + leaf('splenius-tension', 'Tension du splénius', 'Splenius tension'), + ], + }, + ], + }, + { + id: 'cervical-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + { + ...leaf( + 'stumbling-proprioceptive', + 'Trébuchements / déficit proprioceptif rapporté', + 'Reported stumbling / proprioceptive deficit', + ), + requires_vet_referral: true, + }, + ], + }, + { ...ANAMNESIS, children: [TRAUMA] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const C7_T1_ZONE = { + id: 'c7-t1', + name: { + fr: 'Charnière C7-T1 (cervico-thoracique)', + en: 'C7-T1 (Cervicothoracic)', + }, + categories: [ + { + id: 'c7-t1-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + leaf( + 'restriction-rotation', + 'Restriction en rotation', + 'Rotation restriction', + ), + ], + }, + { + id: 'c7-t1-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'base-neck-stiffness', + "Raideur de la base de l'encolure", + 'Base-of-neck stiffness', + ), + ], + }, + { ...ANAMNESIS, children: [STRESS] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const ATM_ZONE = { + id: 'atm', + name: { + fr: 'Articulation Temporo-Mandibulaire (ATM)', + en: 'Temporomandibular Joint (TMJ)', + }, + categories: [ + { + id: 'atm-dysfunctions', + kind: 'dysfunction', + name: { + fr: "Dysfonctions ostéopathiques de l'ATM", + en: 'Osteopathic TMJ dysfunctions', + }, + children: [ + leaf('masseter-tension', 'Tension du masséter', 'Masseter tension'), + ], + }, + { + id: 'atm-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'bit-defense', + 'Réactions de défense au mors', + 'Defense reactions to bit', + ), + ], + }, + { + ...ANAMNESIS, + children: [ + leaf( + 'dental-context', + 'Suite de soin dentaire récent', + 'Post recent dental care', + ), + ], + }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const SPHENOID_ZONE = { + id: 'sphenoid', + name: { fr: 'Sphénoïde', en: 'Sphenoid' }, + categories: [ + { + id: 'ssb-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'physiological', + name: { + fr: 'Lésions physiologiques (SSB)', + en: 'Physiological lesions (SBS)', + }, + children: [ + leaf('torsion-right', 'Torsion droite', 'Right torsion'), + leaf('torsion-left', 'Torsion gauche', 'Left torsion'), + ], + }, + ], + }, + { + id: 'sphenoid-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'post-trauma-head', + 'Suite de traumatisme crânien', + 'Post head trauma', + ), + ], + }, + { ...ANAMNESIS, children: [TRAUMA, STRESS] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const HORSE_SLICE_INPUT: AnatomicalSheetDocumentInput = { + schema_version: 1, + species_id: 'equine', + name: { fr: 'Cheval (extrait)', en: 'Horse (slice)' }, + description: { + fr: 'Extrait de la fiche équine pour les tests du modèle', + en: 'Equine sheet slice for model tests', + }, + scope_disclaimer: { + fr: + "Les éléments listés correspondent au périmètre légal de l'ostéopathie " + + 'animale : dysfonctions ostéopathiques palpées, observations cliniques ' + + "et motifs de consultation. Aucun diagnostic médical n'est posé. " + + 'Toute pathologie organique relève du vétérinaire.', + }, + attribution: { authors: ['Faunosteo'], license: 'MIT', notes: null }, + vertebral_config: { + regions: [ + { code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 }, + { code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 }, + { code: 'L', name: { fr: 'Lombaires', en: 'Lumbar' }, count: 6 }, + { code: 'S', name: { fr: 'Sacrées', en: 'Sacral' }, count: 5 }, + { code: 'Cd', name: { fr: 'Caudales', en: 'Caudal' }, count: 18 }, + ], + }, + categories: [ + { + id: 'articulations', + name: { fr: 'Articulations', en: 'Joints' }, + color: '#ff9500', + }, + { + id: 'zone-colonne', + name: { fr: 'Zone colonne', en: 'Spine zone' }, + color: '#e100ff', + }, + { + id: 'charnieres-vertebrales', + name: { fr: 'Charnières vertébrales', en: 'Vertebral junctions' }, + color: '#ff0000', + }, + { + id: 'cadrans-du-crane', + name: { fr: 'Cadrans du crâne', en: 'Skull quadrants' }, + color: '#1baa08', + }, + ], + views: [ + { + id: 'view-main', + kind: 'main', + name: { fr: 'Cheval entier', en: 'Whole horse' }, + svg_asset_id: HORSE_MAIN_ASSET_ID, + view_box: null, + }, + { + id: 'view-head', + kind: 'detail', + name: { fr: 'Tête', en: 'Head' }, + parent_view_id: 'view-main', + svg_asset_id: null, + view_box: { min_x: 60, min_y: 100, width: 500, height: 380 }, + }, + ], + annotations: [ + { + id: 'hip', + kind: 'point', + view_id: 'view-main', + category_id: 'articulations', + laterality: 'bilateral', + geometry: { type: 'circle', cx: 1516, cy: 695, r: 34 }, + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + finding_zone_id: 'hip', + vertebral_region_code: null, + }, + { + id: 'cervical-vertebrae', + kind: 'zone', + view_id: 'view-main', + category_id: 'zone-colonne', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [468, 276], + [489, 216], + [558, 248], + [586, 339], + [552, 461], + [524, 370], + ], + }, + name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' }, + finding_zone_id: 'cervical', + vertebral_region_code: 'C', + }, + { + id: 'hinge-c7-t1', + kind: 'point', + view_id: 'view-main', + category_id: 'charnieres-vertebrales', + laterality: 'unpaired', + geometry: { type: 'circle', cx: 840.17, cy: 399.08, r: 30 }, + name: { + fr: 'Charnière C7-T1 (cervico-thoracique)', + en: 'C7-T1 (Cervicothoracic)', + }, + finding_zone_id: 'c7-t1', + vertebral_region_code: null, + }, + { + id: 'head-trigger', + kind: 'detail_trigger', + view_id: 'view-main', + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [454, 332], + [429, 202], + [349, 154], + [234, 279], + [164, 384], + [234, 468], + ], + }, + name: null, + opens_view_id: 'view-head', + }, + { + id: 'atm', + kind: 'point', + view_id: 'view-head', + category_id: 'articulations', + laterality: 'bilateral', + geometry: { type: 'circle', cx: 384.94, cy: 314.02, r: 27 }, + name: { + fr: 'Articulation Temporo-Mandibulaire (ATM)', + en: 'Temporomandibular Joint (TMJ)', + }, + finding_zone_id: 'atm', + vertebral_region_code: null, + }, + { + id: 'sphenoid', + kind: 'point', + view_id: 'view-head', + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: { type: 'circle', cx: 299, cy: 298, r: 27 }, + name: { fr: 'Sphénoïde', en: 'Sphenoid' }, + finding_zone_id: 'sphenoid', + vertebral_region_code: null, + }, + ], + finding_zones: [HIP_ZONE, CERVICAL_ZONE, C7_T1_ZONE, ATM_ZONE, SPHENOID_ZONE], +} + +/** Lean authoring form, as a creator or the importer would write it. */ +export function horseSliceInput(): AnatomicalSheetDocumentInput { + return structuredClone(HORSE_SLICE_INPUT) +} + +/** Parsed (total) document; a fresh copy so tests can mutate it freely. */ +export function horseSlice(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse(horseSliceInput()) +} diff --git a/packages/domain/tsconfig.json b/packages/domain/tsconfig.json new file mode 100644 index 00000000..99d2ea87 --- /dev/null +++ b/packages/domain/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "types": ["node", "vitest/globals"], + "noEmit": true + }, + "include": ["src", "tests"], + "exclude": ["node_modules"] +} diff --git a/packages/domain/vitest.config.ts b/packages/domain/vitest.config.ts new file mode 100644 index 00000000..f6374039 --- /dev/null +++ b/packages/domain/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/**/*.test.ts'], + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15fff537..2477e57b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -97,8 +97,36 @@ importers: specifier: ^3.2.7 version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages/domain: + dependencies: + zod: + specifier: ^3.24.1 + version: 3.25.76 + devDependencies: + '@types/node': + specifier: ^20.19.41 + version: 20.19.41 + eslint: + specifier: ^9.17.0 + version: 9.39.4(jiti@2.7.0) + globals: + specifier: ^15.14.0 + version: 15.15.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + typescript-eslint: + specifier: ^8.19.0 + version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages/supabase: dependencies: + '@faunosteo/domain': + specifier: workspace:* + version: link:../domain '@supabase/supabase-js': specifier: ^2.100.0 version: 2.117.3