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:
1 parent
700567fc4f
commit
70b7f20f6f
5 files changed
+432
-170
No files matched your search
+150
-163
@@ -1,61 +1,113 @@
|
||||
# Adding a New Species
|
||||
|
||||
This guide walks through every step required to add a new species (e.g. dog,
|
||||
cat, bovine) to Osteo Report. The reference implementation is `equine` —
|
||||
mirror its structure when adding a new species.
|
||||
Osteo Report ships with one species (`equine`). Adding a new one is
|
||||
mostly authoring work — anatomy SVGs and a findings JSON — backed by a
|
||||
small amount of boilerplate that the project can scaffold for you.
|
||||
|
||||
Throughout this document, replace `<id>` with the new species' kebab-case id
|
||||
(e.g. `canine`, `feline`, `bovine`).
|
||||
> Throughout this document, replace `<id>` with the new species'
|
||||
> kebab-case id (e.g. `canine`, `feline`, `bovine`).
|
||||
|
||||
---
|
||||
|
||||
## 1. Author the anatomy SVGs
|
||||
## Quick start — `pnpm scaffold:species`
|
||||
|
||||
All SVG assets must conform to the conventions in
|
||||
[`docs/ANATOMY-SVG-CONVENTION.md`](./ANATOMY-SVG-CONVENTION.md). The parser
|
||||
in `src/anatomy/svgConvention.ts` reads the same attributes, so any drift
|
||||
breaks the editor canvas.
|
||||
|
||||
Every clickable zone element must carry these data attributes:
|
||||
|
||||
| Attribute | Required | Notes |
|
||||
|----------------------|----------|-----------------------------------------------------------------|
|
||||
| `data-anno-id` | yes | Stable kebab-case id, unique within the SVG. |
|
||||
| `data-anno-name-fr` | yes | French anatomical label (used in tooltips and PDF text). |
|
||||
| `data-anno-name-en` | yes | English anatomical label (used as fallback and a11y hint). |
|
||||
| `data-anno-category` | yes | One of: `articulation`, `charniere`, `spine-zone`, `os`, `os-overlay`, `head`, `cadran-crane`. |
|
||||
| `data-anno-opens-detail` | no | Id of a detail popup SVG to open when the zone is clicked. The id must match a key in the species manifest's `details` map. |
|
||||
|
||||
Reuse the equine SVG patterns:
|
||||
|
||||
- **Hitbox + visible twin** — used for `articulation`, `charniere`, `os-overlay`, `head`.
|
||||
- **Single visible element** — used for `spine-zone`, `os`, `cadran-crane`.
|
||||
|
||||
See `public/species/equine/Horse.svg` and `public/species/equine/Horse_head.svg`
|
||||
for fully worked examples.
|
||||
|
||||
## 2. Drop the SVGs into `public/`
|
||||
|
||||
Put the assets at:
|
||||
|
||||
```
|
||||
public/species/<id>/<Main>.svg # main side-view body schema
|
||||
public/species/<id>/<Main>_<detail>.svg # one detail SVG per opens-detail key
|
||||
```bash
|
||||
pnpm scaffold:species
|
||||
```
|
||||
|
||||
For example, for a dog with a single head detail popup:
|
||||
The interactive prompt asks for:
|
||||
|
||||
- species id (kebab-case, e.g. `canine`),
|
||||
- French and English display labels,
|
||||
- the asset folder under `public/species/` (defaults to the id),
|
||||
- the main SVG filename,
|
||||
- zero or more detail-popup SVG paths (mapped by `data-anno-opens-detail` key),
|
||||
- the vertebral formula (C / T / L / S / Cd).
|
||||
|
||||
It then writes:
|
||||
|
||||
```
|
||||
public/species/canine/Dog.svg
|
||||
public/species/canine/Dog_head.svg
|
||||
src/domain/species/<id>/
|
||||
index.ts ← SpeciesManifest with `export default`
|
||||
vertebrae.ts ← VertebralFormula constant
|
||||
pathologies.ts ← parses pathologies.json via SpeciesFindingsSchema
|
||||
pathologies.json ← minimal valid catalog skeleton
|
||||
public/species/<assetFolder>/ (directory created, empty)
|
||||
```
|
||||
|
||||
The `public/` prefix is implicit at runtime — the manifest references files
|
||||
by absolute path starting with `/species/...`.
|
||||
The script refuses to clobber existing files, so it is safe to rerun.
|
||||
|
||||
## 3. Create the species manifest
|
||||
After scaffolding, drop the anatomy SVGs into the `public/species/...`
|
||||
folder, fill in `pathologies.json`, and the species shows up
|
||||
automatically in the species picker — see "How auto-discovery works"
|
||||
below.
|
||||
|
||||
Create `src/domain/species/<id>/index.ts` exporting a `SpeciesManifest`:
|
||||
---
|
||||
|
||||
## How auto-discovery works
|
||||
|
||||
`src/domain/species/registry.ts` no longer hard-codes species. It uses
|
||||
Vite's `import.meta.glob`:
|
||||
|
||||
```ts
|
||||
const modules = import.meta.glob<{ default: SpeciesManifest }>(
|
||||
'./*/index.ts',
|
||||
{ eager: true },
|
||||
)
|
||||
```
|
||||
|
||||
Every `src/domain/species/<id>/index.ts` that **default-exports** a
|
||||
`SpeciesManifest` is picked up at build time and registered by its
|
||||
`manifest.id`. Duplicates are warned about and the first one wins.
|
||||
|
||||
What this means in practice:
|
||||
|
||||
- **No registry edit needed.** Drop a properly-structured species
|
||||
folder and it appears in `AnimalForm`, `getSpecies(id)`, the editor,
|
||||
and the PDF exporter.
|
||||
- **The `id` must be unique.** Two folders default-exporting manifests
|
||||
with the same `id` triggers a console warning and the later module
|
||||
is ignored.
|
||||
- **A missing default export is silent.** If you forget
|
||||
`export default`, the species is invisible. The scaffold script
|
||||
emits the default export for you.
|
||||
|
||||
---
|
||||
|
||||
## Manual setup (without the script)
|
||||
|
||||
The scaffold script just writes the files below. If you'd rather do it
|
||||
by hand, the same workflow applies — make sure your `index.ts`
|
||||
default-exports the manifest so auto-discovery sees it.
|
||||
|
||||
### 1. Author the anatomy SVGs
|
||||
|
||||
All SVG assets must conform to
|
||||
[`docs/ANATOMY-SVG-CONVENTION.md`](./ANATOMY-SVG-CONVENTION.md). Every
|
||||
clickable element must carry:
|
||||
|
||||
| Attribute | Required | Notes |
|
||||
| -------------------------- | -------- | -------------------------------------------------------------------------------------- |
|
||||
| `data-anno-id` | yes | Stable identifier, unique within the SVG. The renderer treats it as opaque. |
|
||||
| `data-anno-name-fr` | yes | French anatomical label. |
|
||||
| `data-anno-name-en` | yes | English anatomical label. |
|
||||
| `data-anno-category` | yes | Free-form string used for grouping (e.g. `articulations`, `cadrans-du-cr-ne`). |
|
||||
| `data-anno-opens-detail` | no | Key of a detail popup SVG. Must match a key in the manifest's `details` map. |
|
||||
| `data-anno-special` | no | Behavior hint. `vertebral-precision` opens the VertebraPicker on click. |
|
||||
|
||||
Drop the SVGs into:
|
||||
|
||||
```
|
||||
public/species/<assetFolder>/<Main>.svg
|
||||
public/species/<assetFolder>/<Main>_<detail>.svg
|
||||
```
|
||||
|
||||
The `public/` prefix is implicit at runtime — the manifest references
|
||||
files by absolute path starting with `/species/...`.
|
||||
|
||||
### 2. Create the species manifest
|
||||
|
||||
`src/domain/species/<id>/index.ts`:
|
||||
|
||||
```ts
|
||||
import type { SpeciesManifest } from '@/domain/species/types'
|
||||
@@ -69,50 +121,23 @@ export const canine: SpeciesManifest = {
|
||||
head: '/species/canine/Dog_head.svg',
|
||||
},
|
||||
vertebralFormula: CANINE_VERTEBRAL_FORMULA,
|
||||
pathologies: () => import('./pathologies'),
|
||||
findings: () => import('./pathologies'),
|
||||
}
|
||||
|
||||
export default canine // <- required for auto-discovery
|
||||
```
|
||||
|
||||
Required fields (see `src/domain/species/types.ts`):
|
||||
`details` keys must match every distinct `data-anno-opens-detail`
|
||||
attribute used in the main SVG. There is no filename convention — the
|
||||
mapping is explicit through this object.
|
||||
|
||||
- `id` — must match the folder name and the registry key.
|
||||
- `labelFr` — French display name shown in the species picker.
|
||||
- `mainSvg` — absolute path to the main anatomy SVG.
|
||||
- `details` — map of detail id → SVG path. Keys must match every distinct
|
||||
`data-anno-opens-detail` attribute used in the main SVG.
|
||||
- `vertebralFormula` — segment counts for the VertebraPicker (see step 5).
|
||||
- `pathologies` — lazy import returning `{ default: Pathology[] }` (step 6).
|
||||
### 3. Provide the vertebral formula
|
||||
|
||||
## 4. Register the manifest
|
||||
|
||||
Edit `src/domain/species/registry.ts` to add the new manifest:
|
||||
|
||||
```ts
|
||||
import type { SpeciesManifest } from './types'
|
||||
import { equine } from './equine'
|
||||
import { canine } from './canine'
|
||||
|
||||
const SPECIES_REGISTRY: Record<string, SpeciesManifest> = {
|
||||
[equine.id]: equine,
|
||||
[canine.id]: canine,
|
||||
}
|
||||
```
|
||||
|
||||
The species will now appear in the species `<Select>` of `AnimalForm`,
|
||||
and `getSpecies(id)` will resolve it everywhere it is consumed (editor,
|
||||
PDF export, anatomy canvas).
|
||||
|
||||
## 5. Provide a vertebral formula
|
||||
|
||||
Create `src/domain/species/<id>/vertebrae.ts`:
|
||||
`src/domain/species/<id>/vertebrae.ts`:
|
||||
|
||||
```ts
|
||||
import type { VertebralFormula } from '@/domain/species/types'
|
||||
|
||||
/**
|
||||
* Vertebral formula for the dog (Canis lupus familiaris).
|
||||
* Cd count capped at 20 for the picker — actual count varies 6–23.
|
||||
*/
|
||||
export const CANINE_VERTEBRAL_FORMULA: VertebralFormula = {
|
||||
C: 7,
|
||||
T: 13,
|
||||
@@ -122,114 +147,76 @@ export const CANINE_VERTEBRAL_FORMULA: VertebralFormula = {
|
||||
}
|
||||
```
|
||||
|
||||
The keys map to the cervical, thoracic, lumbar, sacral, and caudal counts
|
||||
the `VertebraPicker` will offer when the practitioner clicks a `spine-zone`
|
||||
on the main SVG. Cap `Cd` at a reasonable maximum for picker usability
|
||||
when the real count varies between individuals.
|
||||
Cap `Cd` at a sensible maximum (caudal counts vary heavily across
|
||||
individuals).
|
||||
|
||||
Look up the reference counts in a veterinary anatomy textbook (König &
|
||||
Liebich for dogs/cats, Dyce/Sack/Wensing for general comparative anatomy).
|
||||
### 4. Provide the findings catalog
|
||||
|
||||
## 6. Provide a pathologies seed file
|
||||
Two files:
|
||||
|
||||
Create `src/domain/species/<id>/pathologies.ts`:
|
||||
`src/domain/species/<id>/pathologies.json` — authored tree of zones,
|
||||
categories, sub-categories and leaves. The shape is defined by
|
||||
`src/domain/schema/findings.ts`. The scaffold script ships a minimal
|
||||
skeleton; populate the `zones` map by mirroring the equine reference at
|
||||
`src/domain/species/equine/pathologies.json`.
|
||||
|
||||
`src/domain/species/<id>/pathologies.ts` — loader:
|
||||
|
||||
```ts
|
||||
import type { Pathology } from '@/domain/schema/pathology'
|
||||
import {
|
||||
SpeciesFindingsSchema,
|
||||
type SpeciesFindings,
|
||||
} from '@/domain/schema/findings'
|
||||
import data from './pathologies.json'
|
||||
|
||||
/**
|
||||
* Canine pathology database.
|
||||
* Per v1 contract, an empty array is acceptable — the practitioner can
|
||||
* fall back to free-text pathology input until this is populated.
|
||||
*/
|
||||
const CANINE_PATHOLOGIES: Pathology[] = []
|
||||
const FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data)
|
||||
|
||||
export default CANINE_PATHOLOGIES
|
||||
export default FINDINGS
|
||||
```
|
||||
|
||||
Each entry, when populated, must pass `PathologySchema.parse()` and have
|
||||
at least one `sources` entry citing a peer-reviewed reference. See
|
||||
`src/domain/schema/pathology.ts` for the full schema.
|
||||
The Zod parse runs on first import and **fails fast** if the JSON
|
||||
violates the schema (missing labels, malformed children, empty
|
||||
disclaimer, etc.). That is your validation gate — there is no separate
|
||||
lint step to run.
|
||||
|
||||
Empty arrays are allowed for v1 — the editor will simply show the
|
||||
free-text pathology input only, exactly like equine ships today.
|
||||
---
|
||||
|
||||
## 7. Add the two tests
|
||||
## Updating the findings JSON
|
||||
|
||||
Mirror the equine reference tests:
|
||||
The JSON is bundled into the app at build time, so updates flow
|
||||
through normal dev/deploy paths:
|
||||
|
||||
### 7a. Registry test
|
||||
- **In dev (`pnpm dev`)**: edit the JSON, Vite HMR reloads the module,
|
||||
the editor picks up the new tree on the next interaction. A bad
|
||||
edit fails loudly because the Zod parse runs at module load.
|
||||
- **In prod**: rebuild and redeploy. The findings tree is statically
|
||||
imported and there is no backend serving JSON at runtime.
|
||||
|
||||
Add to `tests/unit/species.registry.test.ts` (or create
|
||||
`tests/unit/species.<id>Registry.test.ts` if you prefer one file per
|
||||
species). Pattern:
|
||||
Snapshots in already-exported PDFs are unaffected — observations carry
|
||||
`labelFrSnapshot` / `labelEnSnapshot` copied at selection time, so
|
||||
catalog edits cannot retroactively rewrite past reports.
|
||||
|
||||
```ts
|
||||
it('returns the canine manifest', () => {
|
||||
const c = getSpecies('canine')
|
||||
expect(c).toBeDefined()
|
||||
expect(c?.labelFr).toBe('Chien')
|
||||
expect(c?.mainSvg).toBe('/species/canine/Dog.svg')
|
||||
expect(c?.details.head).toBe('/species/canine/Dog_head.svg')
|
||||
expect(c?.vertebralFormula).toEqual({ C: 7, T: 13, L: 7, S: 3, Cd: 20 })
|
||||
})
|
||||
```
|
||||
---
|
||||
|
||||
### 7b. Real-SVG parse test
|
||||
## How findings link back to clicked SVG zones
|
||||
|
||||
Mirror `tests/unit/anatomy.horse.test.ts`. Create
|
||||
`tests/unit/anatomy.<id>.test.ts` that loads the real SVG from
|
||||
`public/species/<id>/` and asserts:
|
||||
The catalog keys observations by stable JSON zone ids (e.g.
|
||||
`sphenoid`). SVG hitboxes carry opaque generator ids
|
||||
(e.g. `point-mpbymcln`). The bridge is the **FR/EN label** parsed from
|
||||
`data-anno-name-fr` / `data-anno-name-en`, matched against the JSON's
|
||||
`zone.name_fr` / `zone.name_en` via the fuzzy matcher in
|
||||
`src/lib/zoneMatch.ts`.
|
||||
|
||||
- `parseSvgBones` does not throw and returns a non-empty map.
|
||||
- Every required `data-anno-category` you used is present at least once
|
||||
(especially the `spine-zone` count, the `head` zone with `opensDetail`,
|
||||
and any `charniere` hinges).
|
||||
- Detail SVGs (one test per detail id) parse cleanly and contain the
|
||||
expected `cadran-crane` zones.
|
||||
|
||||
Pattern:
|
||||
|
||||
```ts
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const DOG_PATH = resolve(HERE, '../../public/species/canine/Dog.svg')
|
||||
|
||||
function loadSvg(path: string): SVGSVGElement {
|
||||
const raw = readFileSync(path, 'utf8')
|
||||
return new DOMParser()
|
||||
.parseFromString(raw, 'image/svg+xml')
|
||||
.documentElement as unknown as SVGSVGElement
|
||||
}
|
||||
|
||||
describe('real Dog.svg', () => {
|
||||
const map = parseSvgBones(loadSvg(DOG_PATH))
|
||||
|
||||
it('parses without throwing', () => {
|
||||
expect(map.size).toBeGreaterThan(10)
|
||||
})
|
||||
|
||||
it('contains all 5 spine-zone bones', () => {
|
||||
const spine = [...map.values()].filter((b) => b.category === 'spine-zone')
|
||||
expect(spine.length).toBe(5)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Also add a `tests/unit/species.<id>Pathologies.test.ts` that mirrors
|
||||
`tests/unit/species.equinePathologies.test.ts` — even if the array is empty,
|
||||
the schema parse loop and the `speciesIds.includes('<id>')` assertion become
|
||||
guardrails for future contributors.
|
||||
In practice you do not need to make the SVG ids meaningful; you just
|
||||
need each zone's label to match its catalog entry under normalization
|
||||
(lowercase + strip accents + drop non-alphanumerics) or be close
|
||||
enough that Levenshtein finds it.
|
||||
|
||||
---
|
||||
|
||||
## CI gate before merging
|
||||
|
||||
```
|
||||
```bash
|
||||
pnpm lint
|
||||
pnpm typecheck
|
||||
pnpm test:run
|
||||
|
||||
+2
-1
@@ -16,7 +16,8 @@
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"lint": "eslint . --max-warnings 0",
|
||||
"format": "prettier --write ."
|
||||
"format": "prettier --write .",
|
||||
"scaffold:species": "node scripts/scaffold-species.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.0",
|
||||
|
||||
Executable
+235
@@ -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()
|
||||
})
|
||||
@@ -11,3 +11,8 @@ export const equine: SpeciesManifest = {
|
||||
vertebralFormula: EQUINE_VERTEBRAL_FORMULA,
|
||||
findings: () => import('./pathologies'),
|
||||
}
|
||||
|
||||
// Default export is the convention picked up by the registry's
|
||||
// import.meta.glob() auto-discovery. Keep the named export for any
|
||||
// code that still imports the manifest by name.
|
||||
export default equine
|
||||
@@ -1,17 +1,51 @@
|
||||
import type { SpeciesManifest } from './types'
|
||||
import { equine } from './equine'
|
||||
|
||||
/** Map of speciesId → manifest. Add new species here. */
|
||||
const SPECIES_REGISTRY: Record<string, SpeciesManifest> = {
|
||||
[equine.id]: equine,
|
||||
/**
|
||||
* Auto-discovers every species manifest in `src/domain/species/*\/index.ts`
|
||||
* via Vite's `import.meta.glob`. Each manifest module must default-export
|
||||
* its `SpeciesManifest`. Drop a new folder with a conforming `index.ts`
|
||||
* (and its `vertebrae.ts` + `pathologies.ts` siblings) and the species
|
||||
* shows up everywhere — the AnimalForm dropdown, the editor canvas,
|
||||
* the PDF export — without any registry edit.
|
||||
*
|
||||
* `eager: true` resolves modules synchronously at build time so the
|
||||
* registry is a plain object literal in the bundled output (no async
|
||||
* loading required to enumerate species).
|
||||
*/
|
||||
const modules = import.meta.glob<{ default: SpeciesManifest }>(
|
||||
'./*/index.ts',
|
||||
{ eager: true },
|
||||
)
|
||||
|
||||
function buildRegistry(): Record<string, SpeciesManifest> {
|
||||
const reg: Record<string, SpeciesManifest> = {}
|
||||
for (const [path, mod] of Object.entries(modules)) {
|
||||
const manifest = mod.default
|
||||
if (!manifest || typeof manifest.id !== 'string' || !manifest.id) {
|
||||
console.warn(`Species manifest at ${path} has no valid default export — skipping.`)
|
||||
continue
|
||||
}
|
||||
if (reg[manifest.id]) {
|
||||
console.warn(
|
||||
`Duplicate species id "${manifest.id}" — keeping the first one (from ${path} ignored).`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
reg[manifest.id] = manifest
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
const SPECIES_REGISTRY: Record<string, SpeciesManifest> = buildRegistry()
|
||||
|
||||
/** Returns a species manifest by id, or undefined if not registered. */
|
||||
export function getSpecies(id: string): SpeciesManifest | undefined {
|
||||
return SPECIES_REGISTRY[id]
|
||||
}
|
||||
|
||||
/** Returns all registered species manifests. */
|
||||
/** Returns all registered species manifests, sorted alphabetically by labelFr. */
|
||||
export function getAllSpecies(): SpeciesManifest[] {
|
||||
return Object.values(SPECIES_REGISTRY)
|
||||
return Object.values(SPECIES_REGISTRY).sort((a, b) =>
|
||||
a.labelFr.localeCompare(b.labelFr, 'fr'),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user