feat(species): auto-discover species manifests + scaffold script

Registry
--------
src/domain/species/registry.ts previously hard-coded the species list,
which meant adding a new animal forced an edit in two places. The
registry now uses Vite's `import.meta.glob('./*/index.ts', { eager: true })`
and registers every manifest that default-exports a SpeciesManifest.
Duplicate ids log a warn and the first wins. Existing named imports
keep working — equine/index.ts adds `export default equine` next to the
named export.

The species dropdown is also now sorted alphabetically by labelFr (FR
locale) instead of insertion order, so two species don't shuffle
position based on glob ordering.

Scaffold script
---------------
`pnpm scaffold:species` (scripts/scaffold-species.mjs) is an
interactive Node ESM prompt that asks for the id, FR/EN labels, asset
folder, main SVG filename, detail SVG mappings, and the vertebral
formula, then writes:

  src/domain/species/<id>/index.ts        (with `export default`)
  src/domain/species/<id>/vertebrae.ts
  src/domain/species/<id>/pathologies.ts  (Zod-parses the JSON)
  src/domain/species/<id>/pathologies.json (minimal valid skeleton)
  public/species/<assetFolder>/           (directory placeholder)

The script refuses to overwrite existing files, so it's safe to rerun
after typos. SVG assets are not generated — drop them in the public
folder yourself.

Findings JSON updates
---------------------
No runtime hot-reload mechanism is needed in dev: `pathologies.ts`
imports `pathologies.json` and runs `SpeciesFindingsSchema.parse(data)`
at module load, so a JSON edit triggers Vite HMR + an immediate Zod
validation pass. In prod, rebuild and redeploy.

Docs
----
docs/ADDING-A-SPECIES.md rewritten around the new flow: quick start via
the scaffold script first, manual instructions second, and removed the
stale references to the flat `Pathology[]` model and the no-longer-
required registry edit step.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude committed 2026-05-20 05:46:33 +02:00
1 parent 700567fc4f
commit 70b7f20f6f
5 files changed
+432 -170

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
#!/usr/bin/env node
/**
* Scaffolds a new species: prompts for the few required values then
* writes the boilerplate that the auto-discovery registry expects.
*
* Run via: pnpm scaffold:species
* or: node scripts/scaffold-species.mjs
*
* The script never touches existing files — it refuses to write if any
* of the targets already exist, so you can rerun it after fixing typos
* without losing work. SVG assets are NOT created; drop them in
* `public/species/<assetFolder>/` yourself after the script finishes.
*/
import { existsSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import readline from 'node:readline/promises'
import { stdin as input, stdout as output } from 'node:process'
const HERE = dirname(fileURLToPath(import.meta.url))
const PROJECT_ROOT = resolve(HERE, '..')
const rl = readline.createInterface({ input, output })
async function ask(question, fallback) {
const suffix = fallback === undefined ? '' : ` [${fallback}]`
const raw = (await rl.question(`${question}${suffix}: `)).trim()
return raw || (fallback ?? '')
}
async function askRequired(question, validate) {
while (true) {
const v = (await rl.question(`${question}: `)).trim()
if (!v) {
console.log(' (required)')
continue
}
if (validate) {
const err = validate(v)
if (err) {
console.log(` ${err}`)
continue
}
}
return v
}
}
async function askPositiveInt(question, fallback) {
while (true) {
const v = await ask(question, String(fallback))
const n = Number(v)
if (Number.isInteger(n) && n > 0) return n
console.log(' enter a positive integer')
}
}
function isKebab(s) {
return /^[a-z][a-z0-9-]*$/.test(s)
}
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1)
}
function indexTs({ id, labelFr, mainSvgPath, details, formulaConstName }) {
const detailLines = details
.map((d) => ` ${d.key}: '${d.path}',`)
.join('\n')
return `import type { SpeciesManifest } from '@/domain/species/types'
import { ${formulaConstName} } from './vertebrae'
export const ${id}: SpeciesManifest = {
id: '${id}',
labelFr: '${labelFr.replace(/'/g, "\\'")}',
mainSvg: '${mainSvgPath}',
details: {
${detailLines}
},
vertebralFormula: ${formulaConstName},
findings: () => import('./pathologies'),
}
export default ${id}
`
}
function vertebraeTs({ formulaConstName, labelFr, formula }) {
return `import type { VertebralFormula } from '@/domain/species/types'
/** Vertebral formula for ${labelFr}. Adjust to species-specific anatomy. */
export const ${formulaConstName}: VertebralFormula = {
C: ${formula.C},
T: ${formula.T},
L: ${formula.L},
S: ${formula.S},
Cd: ${formula.Cd},
}
`
}
function pathologiesTs() {
return `import {
SpeciesFindingsSchema,
type SpeciesFindings,
} from '@/domain/schema/findings'
import data from './pathologies.json'
const FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data)
export default FINDINGS
`
}
function pathologiesJsonTemplate({ id, labelFr, labelEn }) {
return JSON.stringify(
{
schema_version: '1.1',
scope_disclaimer:
"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.",
species: {
id,
name_fr: labelFr,
name_en: labelEn,
},
zones: {},
},
null,
2,
)
}
async function collectDetails() {
const details = []
console.log('\nDetail popup SVGs (optional — leave key blank to stop).')
console.log(' Each "key" must match a data-anno-opens-detail value on a hitbox in the main SVG.')
for (;;) {
const key = (await rl.question(' detail key (e.g. head, patte): ')).trim()
if (!key) return details
if (!isKebab(key)) {
console.log(' → key must be kebab-case (lowercase, hyphen-separated). Try again.')
continue
}
const path = await askRequired(
` detail SVG path for "${key}" (e.g. /species/canine/Dog_head.svg)`,
(v) => (v.startsWith('/species/') ? '' : ' path must start with /species/'),
)
details.push({ key, path })
}
}
async function main() {
console.log('\nOsteo Report — new species scaffold')
console.log('-----------------------------------\n')
const id = await askRequired(
'species id (kebab-case, e.g. canine, feline, bovine)',
(v) => (isKebab(v) ? '' : 'must be kebab-case (lowercase letters / digits / hyphens; start with a letter)'),
)
const labelFr = await askRequired('display label (FR), e.g. "Chien"')
const labelEn = await ask('display label (EN), e.g. "Dog"', capitalize(id))
const assetFolder = await ask(
'public asset folder under /species/',
id,
)
const mainSvgFile = await askRequired(
`main SVG filename in /public/species/${assetFolder}/ (e.g. Dog.svg)`,
)
const mainSvgPath = `/species/${assetFolder}/${mainSvgFile}`
const details = await collectDetails()
console.log('\nVertebral formula (counts per region):')
const formula = {
C: await askPositiveInt(' cervical (C)', 7),
T: await askPositiveInt(' thoracic (T)', 13),
L: await askPositiveInt(' lumbar (L)', 6),
S: await askPositiveInt(' sacral (S)', 5),
Cd: await askPositiveInt(' caudal (Cd)', 18),
}
const formulaConstName = `${id.replace(/-/g, '_').toUpperCase()}_VERTEBRAL_FORMULA`
const speciesDir = resolve(PROJECT_ROOT, 'src/domain/species', id)
const targets = {
'index.ts': indexTs({ id, labelFr, mainSvgPath, details, formulaConstName }),
'vertebrae.ts': vertebraeTs({ formulaConstName, labelFr, formula }),
'pathologies.ts': pathologiesTs(),
'pathologies.json': pathologiesJsonTemplate({ id, labelFr, labelEn }),
}
// Refuse to clobber.
for (const file of Object.keys(targets)) {
const p = resolve(speciesDir, file)
if (existsSync(p)) {
console.error(`\n✖ ${p} already exists. Aborting to protect existing work.`)
process.exit(1)
}
}
await mkdir(speciesDir, { recursive: true })
for (const [file, body] of Object.entries(targets)) {
await writeFile(resolve(speciesDir, file), body)
}
const publicDir = resolve(PROJECT_ROOT, 'public/species', assetFolder)
await mkdir(publicDir, { recursive: true })
console.log(`\n✓ Created src/domain/species/${id}/`)
for (const file of Object.keys(targets)) console.log(` - ${file}`)
console.log(`✓ Ensured public/species/${assetFolder}/ exists`)
console.log('\nNext steps:')
console.log(` 1. Drop your SVG assets into public/species/${assetFolder}/`)
console.log(` - main: ${mainSvgFile}`)
for (const d of details) {
const file = d.path.split('/').pop()
console.log(` - detail "${d.key}": ${file}`)
}
console.log(` 2. Author the findings tree in src/domain/species/${id}/pathologies.json`)
console.log(` (schema documented in src/domain/schema/findings.ts).`)
console.log(` 3. Adjust the vertebral counts in vertebrae.ts if needed.`)
console.log(` 4. Run: pnpm typecheck && pnpm test:run && pnpm dev`)
console.log(' The new species will appear automatically in the animal picker.\n')
}
main()
.catch((err) => {
console.error('Scaffold failed:', err)
process.exit(1)
})
.finally(() => {
rl.close()
})