Files
faunosteo/apps/app/tests/unit/char.pathologyEditor.test.ts
T
bchanot 8673475293 chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates
dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and
pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager,
root devDependency, engine-strict). Dockerfile builds @faunosteo/app on
node:24-alpine and copies apps/app/dist; nginx and runtime config
unchanged. CI workflow for Gitea Actions. packages/ reserved (README only).
Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan.
271/271 tests, typecheck, lint, build green from the root.
2026-10-08 21:51:13 +02:00

147 lines
6.1 KiB
TypeScript

/**
* Characterisation (Step 1): public/pathology-editor.html, the standalone
* findings editor. Its JavaScript is extracted by text and evaluated so that
* the inline matcher, id generator, translations and species config are
* pinned without touching the file (BDR-020/021, LRN-026).
*
* Limitation: the DOM-editing behaviour (tree add/edit/delete, dirty flag,
* download) is not executed here; it is described in
* docs/faunosteo-audit/05-findings-editor.md §3.5 and will be re-specified
* as tests of the merged editor (plan Step 17).
*/
import { describe, it, expect } from 'vitest'
import { existsSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { matchZoneFindings, normalizeLabel, scorePair } from '@/lib/zoneMatch'
import FINDINGS from '@/domain/species/equine/pathologies'
import { fr } from '@/i18n/fr'
const HERE = dirname(fileURLToPath(import.meta.url))
const ROOT = resolve(HERE, '../..')
const HTML = readFileSync(resolve(ROOT, 'public/pathology-editor.html'), 'utf8')
function slice(from: string, to: string): string {
const a = HTML.indexOf(from)
const b = HTML.indexOf(to, a)
if (a < 0 || b < 0) throw new Error(`markers not found: ${from} … ${to}`)
return HTML.slice(a, b)
}
type Zone = { id: string; name_fr: string; name_en: string }
interface InlineApi {
normalizeLabel: (s: string) => string
scorePair: (a: string, b: string) => number
matchZone: (fr: string, en: string, zones: Zone[]) => Zone | null
generateId: (en: string, fr: string, existing: string[]) => string
}
const matcherSrc = slice('function normalizeLabel(s)', '// ── Node stats ──')
const inline = new Function(
`${matcherSrc}; return { normalizeLabel, scorePair, matchZone, generateId };`,
)() as InlineApi
const translationsSrc = slice('var TRANSLATIONS = ', '\n };') + '\n };'
const TRANSLATIONS = new Function(`${translationsSrc} return TRANSLATIONS;`)() as {
fr: Record<string, string>
en: Record<string, string>
}
const configSrc = slice('var SPECIES_CONFIG = ', '\n ];') + '\n ];'
const SPECIES_CONFIG = new Function(`${configSrc} return SPECIES_CONFIG;`)() as Array<{
id: string
labelKey: string
jsonPath: string
views: Array<{ labelKey: string; svgPath: string }>
}>
function bones(file: string) {
const text = readFileSync(resolve(ROOT, 'public/species/equine', file), 'utf8')
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
return parseSvgBones(doc.documentElement as unknown as SVGSVGElement)
}
const zones = Object.values(FINDINGS.zones)
describe('inline matcher parity with src/lib/zoneMatch.ts', () => {
const labels: Array<{ fr: string; en: string }> = [
...[...bones('Horse.svg').values(), ...bones('Horse_head.svg').values()].map((b) => ({ fr: b.fr, en: b.en })),
{ fr: 'Hanche', en: 'Hip' },
{ fr: 'ATM', en: 'TMJ' },
{ fr: 'Sphenoide', en: 'Sphenoidd' },
{ fr: 'Vertèbres sacrales', en: '' },
{ fr: '', en: '' },
{ fr: 'Boulet ant. (métacarpo-phalangien)', en: 'Fore fetlok' },
]
it('returns the same zone for every real annotation and edge label', () => {
for (const l of labels) {
const app = matchZoneFindings(l, zones)?.id
const editor = inline.matchZone(l.fr, l.en, zones)?.id
expect(editor ?? undefined, `${l.fr} / ${l.en}`).toBe(app)
}
})
it('normalizes and scores identically', () => {
for (const s of ['Sphénoïde', 'Charnière C0-C1 (occipito-atloïdienne)', 'Temporomandibular Joint (TMJ)', '']) {
expect(inline.normalizeLabel(s)).toBe(normalizeLabel(s))
}
expect(inline.scorePair('Hip', 'Hip joint')).toBe(scorePair('Hip', 'Hip joint'))
expect(inline.scorePair('Sphenoidd', 'Sphenoid')).toBe(scorePair('Sphenoidd', 'Sphenoid'))
expect(inline.scorePair('', 'x')).toBe(scorePair('', 'x'))
})
})
describe('inline id generator', () => {
it('slugs name_en first, then name_fr, strips accents, suffixes -2 on sibling collision', () => {
expect(inline.generateId('Flexion restriction', 'Restriction en flexion', [])).toBe('flexion-restriction')
expect(inline.generateId('', 'Tension du splénius', [])).toBe('tension-du-splenius')
expect(inline.generateId('Hip', '', ['hip'])).toBe('hip-2')
expect(inline.generateId('Hip', '', ['hip', 'hip-2'])).toBe('hip-3')
expect(inline.generateId('', '', [])).toBe('node')
expect(inline.generateId(' -- ', '', [])).toBe('node')
})
})
describe('inline translations and config', () => {
it('fr and en share the same key set (76 keys), independent from the app dictionary', () => {
const frKeys = Object.keys(TRANSLATIONS.fr).sort()
const enKeys = Object.keys(TRANSLATIONS.en).sort()
expect(frKeys).toEqual(enKeys)
expect(frKeys).toHaveLength(76)
// No shared key space with src/i18n (different naming scheme)
expect(frKeys.filter((k) => k in fr)).toEqual([])
})
it('shares only the locale storage key with the app', () => {
expect(HTML).toContain("localStorage.getItem('osteo:locale')")
expect(HTML).toContain("localStorage.setItem('osteo:locale'")
})
it('hard-codes a single species (equine) with two views and the public JSON copy', () => {
expect(SPECIES_CONFIG).toHaveLength(1)
const [equine] = SPECIES_CONFIG
expect(equine.id).toBe('equine')
expect(equine.jsonPath).toBe('/species/equine/pathologies.json')
expect(equine.views.map((v) => v.svgPath)).toEqual([
'/species/equine/Horse.svg',
'/species/equine/Horse_head.svg',
])
for (const p of [equine.jsonPath, ...equine.views.map((v) => v.svgPath)]) {
expect(existsSync(resolve(ROOT, 'public', p.slice(1))), p).toBe(true)
}
})
it('imports nothing from src/ and declares noindex', () => {
expect(HTML).not.toMatch(/from\s+['"]\.\.?\/src/)
expect(HTML).not.toMatch(/<script[^>]+src=/)
expect(HTML).toMatch(/name="robots"\s+content="noindex,\s*nofollow"/)
})
it('validates only three top-level keys of the loaded JSON (no Zod)', () => {
expect(HTML).toMatch(/schema_version/)
expect(HTML).not.toMatch(/zod/i)
})
})