chore(workspace): R5.7 delete packages/anatomy and packages/domain
The TS pipeline, domain, upload script and legacy scripts leave; xmldom out of the lockfile, Dockerfile copies trimmed. LEDGER.tsv (407 cases) and FILES.tsv (112 files) record each disposition; r4 and r5 census tests guard the tree, lockfile and production imports.
This commit is contained in:
1 parent
0da7d3ab9f
commit
1b359598ab
124 files changed
+910
-17475
No files matched your search
@@ -36,8 +36,6 @@ RUN corepack enable && corepack prepare pnpm@10.13.1 --activate
|
||||
# Workspace manifests first for layer caching (install depends only on these)
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
|
||||
COPY apps/app/package.json apps/app/
|
||||
COPY packages/domain/package.json packages/domain/
|
||||
COPY packages/anatomy/package.json packages/anatomy/
|
||||
COPY packages/supabase/package.json packages/supabase/
|
||||
COPY packages/core-wasm/package.json packages/core-wasm/
|
||||
|
||||
|
||||
@@ -55,8 +55,8 @@ export default tseslint.config(
|
||||
},
|
||||
{
|
||||
// R2: the application's rules run in the Rust core; its contracts come from
|
||||
// @faunosteo/core-wasm. The TypeScript domain is no longer a dependency of the
|
||||
// application (R4.8); it stays frozen for the pipeline until R5
|
||||
// @faunosteo/core-wasm. The TypeScript domain left the application at R4.8 and
|
||||
// the repository at R5.7 with the pipeline package and its xmldom
|
||||
// (RUST_ARCHITECTURE_REVIEW VI.4). The rule keeps the door closed.
|
||||
files: ['src/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
@@ -68,8 +68,16 @@ export default tseslint.config(
|
||||
name: '@faunosteo/domain',
|
||||
message: 'Use @faunosteo/core-wasm (types) and the core operations.',
|
||||
},
|
||||
{
|
||||
name: '@faunosteo/anatomy',
|
||||
message: 'The SVG layer and composition are the core operations.',
|
||||
},
|
||||
{
|
||||
name: '@xmldom/xmldom',
|
||||
message: 'Every SVG goes through the core reader (anatomy::svg).',
|
||||
},
|
||||
],
|
||||
patterns: ['@faunosteo/domain/*'],
|
||||
patterns: ['@faunosteo/domain/*', '@faunosteo/anatomy/*'],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* R4.8 census (plan §B.7 R4.8, RUST.md §10.10): the PDF path runs on the core and nothing of
|
||||
* the TypeScript engine is left where the application or its glue could reach it. Grep facts
|
||||
* over the repository, so that a reintroduced import, a dependency added back or a script
|
||||
* repointed fails here before anything else.
|
||||
* repointed fails here before anything else. Since R5.7 xmldom, the TypeScript domain and the
|
||||
* pipeline package are gone too (`r5.census.test.ts` holds the rest of that census).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
@@ -43,6 +44,7 @@ describe('the TypeScript PDF engine is gone', () => {
|
||||
'@faunosteo/pdf',
|
||||
'pdf-lib',
|
||||
'@faunosteo/domain',
|
||||
'@faunosteo/anatomy',
|
||||
'@xmldom/xmldom',
|
||||
]
|
||||
for (const file of [
|
||||
@@ -70,6 +72,8 @@ describe('the TypeScript PDF engine is gone', () => {
|
||||
'@faunosteo/pdf',
|
||||
'pdf-lib',
|
||||
'@faunosteo/domain',
|
||||
'@faunosteo/anatomy',
|
||||
'@xmldom/xmldom',
|
||||
'tsx',
|
||||
]) {
|
||||
expect(names, path).not.toContain(banned)
|
||||
@@ -77,16 +81,27 @@ describe('the TypeScript PDF engine is gone', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('the lockfile holds no pdf-lib, @pdf-lib or resvg; xmldom only under packages/anatomy', () => {
|
||||
it('the lockfile holds no pdf-lib, @pdf-lib, resvg or xmldom (R5.7: the pipeline left with its xmldom)', () => {
|
||||
const lock = read('pnpm-lock.yaml')
|
||||
for (const name of ['pdf-lib@', '@pdf-lib/', '@resvg/resvg-js']) {
|
||||
expect(lock, name).not.toContain(name)
|
||||
}
|
||||
const importers = lock.split(/^ (?=[a-z@][^\n]*:$)/m)
|
||||
const withXmldom = importers
|
||||
.filter((block) => block.includes("'@xmldom/xmldom':"))
|
||||
.map((block) => block.split(':')[0]!.trim())
|
||||
expect(withXmldom).toEqual(['packages/anatomy'])
|
||||
const section = lock.slice(
|
||||
lock.indexOf('\nimporters:\n'),
|
||||
lock.indexOf('\npackages:\n'),
|
||||
)
|
||||
const importers = section
|
||||
.split(/\n(?= [^ \n][^\n]*:\n)/)
|
||||
.slice(1)
|
||||
.map((block) => block.slice(2, block.indexOf(':\n')))
|
||||
// Non-vacuity: the split finds the importers a dependency would sit under.
|
||||
expect(importers).toEqual(
|
||||
expect.arrayContaining(['.', 'apps/app', 'packages/core-wasm']),
|
||||
)
|
||||
expect(importers).not.toContain('packages/anatomy')
|
||||
expect(importers).not.toContain('packages/domain')
|
||||
expect(lock).toContain("'@faunosteo/core-wasm':")
|
||||
expect(lock).not.toContain('@xmldom/xmldom')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
/**
|
||||
* R5.7 census (plan 2026-10-25, RUST.md §11.23): the anatomical pipeline and the
|
||||
* sheet, report and archive rules run in the Rust core only; `packages/anatomy`
|
||||
* and `packages/domain` are gone and nothing reaches them again. Grep facts over
|
||||
* the repository, and the two disposition matrices of the deletion checked
|
||||
* against the tree, so that a reintroduced package, dependency, import, script or
|
||||
* a ledger target that no longer exists fails here.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..')
|
||||
const read = (path: string) => readFileSync(join(ROOT, path), 'utf8')
|
||||
const exists = (path: string) => existsSync(join(ROOT, path))
|
||||
const sha256 = (path: string) =>
|
||||
createHash('sha256')
|
||||
.update(readFileSync(join(ROOT, path)))
|
||||
.digest('hex')
|
||||
|
||||
const DELETED_PACKAGES = ['packages/anatomy', 'packages/domain']
|
||||
const BANNED_SPECIFIERS = [
|
||||
'@faunosteo/anatomy',
|
||||
'@faunosteo/domain',
|
||||
'@xmldom/xmldom',
|
||||
]
|
||||
const BANNED_DEPENDENCIES = [...BANNED_SPECIFIERS, 'tsx']
|
||||
|
||||
/** Source files under `dir` (relative to the root), node_modules excluded. */
|
||||
function sources(dir: string, pattern = /\.(tsx?|mjs|js)$/): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (at: string) => {
|
||||
for (const entry of readdirSync(join(ROOT, at))) {
|
||||
if (entry === 'node_modules') continue
|
||||
const path = `${at}/${entry}`
|
||||
if (statSync(join(ROOT, path)).isDirectory()) walk(path)
|
||||
else if (pattern.test(entry)) out.push(path)
|
||||
}
|
||||
}
|
||||
walk(dir)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Static, dynamic and `require` module specifiers of a source text. */
|
||||
const specifiersOf = (text: string): string[] =>
|
||||
[
|
||||
...text.matchAll(/\bfrom\s+['"]([^'"]+)['"]/g),
|
||||
...text.matchAll(/\bimport\s*\(\s*['"]([^'"]+)['"]/g),
|
||||
...text.matchAll(/\brequire\s*\(\s*['"]([^'"]+)['"]/g),
|
||||
].map((m) => m[1]!)
|
||||
|
||||
const isBanned = (spec: string) =>
|
||||
BANNED_SPECIFIERS.some((b) => spec === b || spec.startsWith(`${b}/`)) ||
|
||||
DELETED_PACKAGES.some((p) => spec.includes(p)) ||
|
||||
/(^|\/)(anatomy|domain)\/src(\/|$)/.test(spec)
|
||||
|
||||
type Manifest = Record<string, Record<string, string> | undefined>
|
||||
|
||||
/** Every workspace manifest: the root, `apps/*`, `packages/*` (with a manifest). */
|
||||
function manifests(): string[] {
|
||||
const found = ['package.json']
|
||||
for (const group of ['apps', 'packages']) {
|
||||
for (const entry of readdirSync(join(ROOT, group))) {
|
||||
const path = `${group}/${entry}/package.json`
|
||||
if (exists(path)) found.push(path)
|
||||
}
|
||||
}
|
||||
return found.sort()
|
||||
}
|
||||
|
||||
/** `pnpm-lock.yaml` importers (name → block) and the `packages:` keys. */
|
||||
function lockfile(): { importers: Map<string, string>; packages: string[] } {
|
||||
const lock = read('pnpm-lock.yaml')
|
||||
const start = lock.indexOf('\nimporters:\n')
|
||||
const end = lock.indexOf('\npackages:\n')
|
||||
const section = lock.slice(start, end)
|
||||
const importers = new Map<string, string>()
|
||||
for (const block of section.split(/\n(?= [^ \n][^\n]*:\n)/).slice(1)) {
|
||||
importers.set(block.slice(2, block.indexOf(':\n')), block)
|
||||
}
|
||||
const after = lock.slice(end + '\npackages:\n'.length)
|
||||
const packages = [
|
||||
...after
|
||||
.slice(0, after.indexOf('\nsnapshots:\n'))
|
||||
.matchAll(/^ {2}'?([^\s'][^\n]*?)'?:$/gm),
|
||||
].map((m) => m[1]!)
|
||||
return { importers, packages }
|
||||
}
|
||||
|
||||
/** Data rows of a committed TSV, checked against its header. */
|
||||
function tsv(path: string, header: string[]): string[][] {
|
||||
const [head, ...rows] = read(path).trimEnd().split('\n')
|
||||
expect(head!.split('\t'), path).toEqual(header)
|
||||
return rows.map((row) => {
|
||||
const cells = row.split('\t')
|
||||
expect(cells.length, `${path}: ${row}`).toBe(header.length)
|
||||
return cells
|
||||
})
|
||||
}
|
||||
|
||||
/** The file a ledger target names: `cargo <binary>::<path>::<test>`. */
|
||||
function cargoTargetFile(binary: string): string[] {
|
||||
if (binary === 'faunosteo_core') return sources('crates/core/src', /\.rs$/)
|
||||
if (['import_equine', 'report_compare'].includes(binary)) {
|
||||
return [`crates/core/src/bin/${binary}.rs`]
|
||||
}
|
||||
if (binary === 'upload_sheet_assets') {
|
||||
return sources('crates/core/src/bin/upload_sheet_assets', /\.rs$/)
|
||||
}
|
||||
return [`crates/core/tests/${binary}.rs`]
|
||||
}
|
||||
|
||||
describe('the TypeScript pipeline and domain packages are gone', () => {
|
||||
it('packages/anatomy, packages/domain and the TS upload script no longer exist', () => {
|
||||
// A folder may linger with a git-ignored node_modules of a stale install.
|
||||
for (const dir of DELETED_PACKAGES) {
|
||||
for (const part of ['package.json', 'src', 'tests']) {
|
||||
expect(exists(`${dir}/${part}`), `${dir}/${part}`).toBe(false)
|
||||
}
|
||||
}
|
||||
expect(exists('packages/supabase/scripts/upload-sheet-assets.ts')).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('no workspace manifest depends on them, and the scripts run the Rust tools', () => {
|
||||
const found = manifests()
|
||||
for (const path of [
|
||||
'package.json',
|
||||
'apps/app/package.json',
|
||||
'packages/core-wasm/package.json',
|
||||
'packages/supabase/package.json',
|
||||
]) {
|
||||
expect(found).toContain(path)
|
||||
}
|
||||
for (const path of found) {
|
||||
const pkg = JSON.parse(read(path)) as Manifest
|
||||
const names = Object.keys({
|
||||
...pkg.dependencies,
|
||||
...pkg.devDependencies,
|
||||
...pkg.peerDependencies,
|
||||
...pkg.optionalDependencies,
|
||||
})
|
||||
for (const banned of BANNED_DEPENDENCIES) {
|
||||
expect(names, path).not.toContain(banned)
|
||||
}
|
||||
for (const [name, script] of Object.entries(pkg.scripts ?? {})) {
|
||||
expect(name, path).not.toMatch(/:legacy$/)
|
||||
expect(script, `${path} ${name}`).not.toMatch(
|
||||
/@faunosteo\/(anatomy|domain)|packages\/(anatomy|domain)|\btsx\b/,
|
||||
)
|
||||
}
|
||||
}
|
||||
const root = JSON.parse(read('package.json')) as Manifest
|
||||
expect(root.scripts?.['import:equine']).toBe(
|
||||
'bash scripts/import-equine.sh',
|
||||
)
|
||||
expect(root.scripts?.['r5:import-equine']).toBe(
|
||||
'bash scripts/import-equine.sh',
|
||||
)
|
||||
expect(root.scripts?.['assets:upload']).toBe(
|
||||
'bash scripts/upload-sheet-assets.sh',
|
||||
)
|
||||
expect(read('scripts/import-equine.sh')).toContain(
|
||||
'--features curation --bin import-equine',
|
||||
)
|
||||
expect(read('scripts/upload-sheet-assets.sh')).toContain(
|
||||
'--bin upload-sheet-assets',
|
||||
)
|
||||
})
|
||||
|
||||
it('the lockfile has one importer per manifest and resolves none of them', () => {
|
||||
const { importers, packages } = lockfile()
|
||||
const dirs = manifests().map((path) =>
|
||||
path === 'package.json' ? '.' : path.slice(0, -'/package.json'.length),
|
||||
)
|
||||
// Non-vacuity: the parser sees exactly the workspace the manifests declare.
|
||||
expect([...importers.keys()].sort()).toEqual(dirs.sort())
|
||||
expect(packages.length).toBeGreaterThan(100)
|
||||
expect(packages.some((key) => key.startsWith('zod@'))).toBe(true)
|
||||
for (const [name, block] of importers) {
|
||||
for (const banned of BANNED_DEPENDENCIES) {
|
||||
expect(block, `${name}: ${banned}`).not.toMatch(
|
||||
new RegExp(`^ {6}'?${banned.replace('/', '\\/')}'?:$`, 'm'),
|
||||
)
|
||||
}
|
||||
}
|
||||
for (const banned of BANNED_SPECIFIERS) {
|
||||
expect(
|
||||
packages.filter((key) => key.startsWith(`${banned}@`)),
|
||||
banned,
|
||||
).toEqual([])
|
||||
}
|
||||
// `tsx` left with the pipeline's CLI; it stays resolved only as the optional peer of vite,
|
||||
// which pnpm marks `optional: true` (`pnpm dedupe --check` clean, RUST.md §11.23).
|
||||
const lock = read('pnpm-lock.yaml')
|
||||
const snapshots = lock.slice(lock.indexOf('\nsnapshots:\n'))
|
||||
const tsx = snapshots.split('\n\n').filter((b) => /^ {2}tsx@/.test(b))
|
||||
for (const block of tsx) expect(block).toMatch(/^ {4}optional: true$/m)
|
||||
})
|
||||
})
|
||||
|
||||
describe('no production path reaches a deleted engine', () => {
|
||||
it('the application, the glue, the Supabase package and their configs import none of them', () => {
|
||||
const files = [
|
||||
...sources('apps/app/src'),
|
||||
...sources('apps/app/vite'),
|
||||
'apps/app/vite.config.ts',
|
||||
'apps/app/vitest.config.ts',
|
||||
'apps/app/eslint.config.js',
|
||||
...sources('packages/core-wasm/src'),
|
||||
...sources('packages/supabase/src'),
|
||||
]
|
||||
// Non-vacuity: the specifier scan finds the imports these sources do have.
|
||||
expect(files.length).toBeGreaterThan(100)
|
||||
const specs = files.flatMap((file) => specifiersOf(read(file)))
|
||||
expect(specs).toContain('@faunosteo/core-wasm')
|
||||
for (const file of files) {
|
||||
expect(specifiersOf(read(file)).filter(isBanned), file).toEqual([])
|
||||
}
|
||||
const tsconfig = read('apps/app/tsconfig.json')
|
||||
expect(tsconfig).not.toMatch(/packages\/(anatomy|domain)/)
|
||||
})
|
||||
|
||||
it('the Dockerfile copies only manifests that exist', () => {
|
||||
const dockerfile = read('Dockerfile')
|
||||
expect(dockerfile).not.toMatch(/packages\/(anatomy|domain)/)
|
||||
const copied = [
|
||||
...dockerfile.matchAll(/^COPY (\S+\/package\.json) /gm),
|
||||
].map((m) => m[1]!)
|
||||
expect(copied).toContain('packages/core-wasm/package.json')
|
||||
expect(copied).toContain('packages/supabase/package.json')
|
||||
for (const path of copied) expect(exists(path), path).toBe(true)
|
||||
})
|
||||
|
||||
it('the application lint rule keeps the deleted packages out', () => {
|
||||
const config = read('apps/app/eslint.config.js')
|
||||
for (const name of BANNED_SPECIFIERS) {
|
||||
expect(config).toContain(`name: '${name}'`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the disposition of the deleted files and tests', () => {
|
||||
it('every deleted file is absent and its counterpart exists', () => {
|
||||
const rows = tsv('crates/core/tests/curation/FILES.tsv', [
|
||||
'ts_file',
|
||||
'disposition',
|
||||
'counterpart',
|
||||
'note',
|
||||
])
|
||||
expect(rows.length).toBeGreaterThan(80)
|
||||
for (const [file, disposition, counterpart] of rows) {
|
||||
expect(file, file).toMatch(/^packages\/(anatomy|domain|supabase)\//)
|
||||
expect(exists(file!), file).toBe(false)
|
||||
expect(['ported', 'replaced', 'deleted'], file).toContain(disposition)
|
||||
if (disposition === 'deleted') continue
|
||||
for (const path of counterpart!.split(', ')) {
|
||||
expect(exists(path), `${file} → ${path}`).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('every TS case of the two packages has a disposition and a live target', () => {
|
||||
const rows = tsv('crates/core/tests/curation/LEDGER.tsv', [
|
||||
'ts_file',
|
||||
'case_title',
|
||||
'contract',
|
||||
'disposition',
|
||||
'target',
|
||||
'oracle',
|
||||
'note',
|
||||
])
|
||||
const per = (dir: string) =>
|
||||
rows.filter(([file]) => file!.startsWith(dir)).length
|
||||
expect(rows.length).toBe(407)
|
||||
expect(per('packages/anatomy/tests/')).toBe(144)
|
||||
expect(per('packages/domain/tests/')).toBe(263)
|
||||
for (const [file, title, , disposition, target, oracle] of rows) {
|
||||
const id = `${file} > ${title}`
|
||||
expect(exists(file!), id).toBe(false)
|
||||
expect(['ported', 'replaced', 'kept', 'deleted'], id).toContain(
|
||||
disposition,
|
||||
)
|
||||
for (const path of oracle === '-' ? [] : oracle!.split(', ')) {
|
||||
expect(exists(path), `${id}: ${path}`).toBe(true)
|
||||
}
|
||||
if (disposition === 'deleted') continue
|
||||
expect(target, id).not.toBe('-')
|
||||
for (const part of target!.split(' ; ')) {
|
||||
const cargo =
|
||||
/^cargo ([a-z0-9_]+)::(?:[a-z0-9_]+::)*([a-z0-9_]+)$/.exec(part)
|
||||
if (cargo) {
|
||||
const [, binary, test] = cargo
|
||||
const files = cargoTargetFile(binary!)
|
||||
const defined = files.some(
|
||||
(path) => exists(path) && read(path).includes(`fn ${test}(`),
|
||||
)
|
||||
expect(defined, `${id}: ${part}`).toBe(true)
|
||||
continue
|
||||
}
|
||||
const vitest = /^vitest (\S+) > (.+)$/.exec(part)
|
||||
if (vitest) {
|
||||
expect(exists(vitest[1]!), `${id}: ${part}`).toBe(true)
|
||||
continue
|
||||
}
|
||||
expect(part, id).toBe('import-equine --check')
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the historical references stay byte for byte', () => {
|
||||
it('the moved report fixtures keep their sha256', () => {
|
||||
expect(sha256('crates/core/tests/fixtures/report-v2.full.json')).toBe(
|
||||
'e96b088282b5d20bd5ed925ea980c1faca86cf1f87eb500201834dda714b729c',
|
||||
)
|
||||
expect(sha256('crates/core/tests/fixtures/report-v2.minimal.json')).toBe(
|
||||
'ba79698c5691dd89f8c6a3ada5a9c6ceb6ea41a85e64596e3eec7399c33cfde7',
|
||||
)
|
||||
})
|
||||
|
||||
it('the oracles, the pre-switch seed files and the N-1 readers stay', () => {
|
||||
for (const path of [
|
||||
'crates/core/tests/oracles/sheet.draft.json',
|
||||
'crates/core/tests/oracles/migration-map.draft.json',
|
||||
'crates/core/tests/oracles/r3/highlight.json',
|
||||
'crates/core/tests/oracles/r5/pipeline.json',
|
||||
'crates/core/tests/oracles/r5/ids.json',
|
||||
'crates/core/tests/oracles/r5/fingerprints.json',
|
||||
'crates/core/tests/fixtures/r5-6/pre-switch/sheet-ref.json',
|
||||
'crates/core/tests/fixtures/r5-6/pre-switch/report-migration-map.json',
|
||||
'crates/core/tests/fixtures/horse-slice.json',
|
||||
'packages/core-wasm/tests/n-1/domain',
|
||||
]) {
|
||||
expect(exists(path), path).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,7 @@
|
||||
//! The anatomy core (R3): SVG reading and sanitising, the annotation layer drawn from the
|
||||
//! sheet document, and the composition of a view (canvas and highlight).
|
||||
//! sheet document, and the composition of a view (canvas and highlight). The TypeScript
|
||||
//! renderer it replaced (`packages/anatomy/src/render`) was deleted at R5.7; cited paths resolve
|
||||
//! at commit 756b7ef.
|
||||
|
||||
pub mod compose;
|
||||
pub mod layer;
|
||||
|
||||
@@ -30,6 +30,9 @@ fn sql_text(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
/// The second line still names the TypeScript generator: it is part of the frozen seed bytes
|
||||
/// (sha256 `c5a24312…ed1e`, the R5.1 ledger), so it stays as written; the generator is this
|
||||
/// module since R5.6 and `packages/anatomy` left at R5.7 (RUST.md §11.23).
|
||||
fn header() -> String {
|
||||
[
|
||||
"-- Official equine anatomical sheet: working revision, DRAFT.",
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
//! (changeset applier, migration map, stats, seed SQL) and the formatting of the generated seed
|
||||
//! files, ported from `packages/anatomy` with its outputs frozen as oracles
|
||||
//! (`crates/core/tests/oracles/r5`). Inputs are bytes and texts, outputs are texts; the
|
||||
//! `import-equine` binary owns the file system.
|
||||
//! `import-equine` binary owns the file system. The TypeScript package was deleted at R5.7:
|
||||
//! the `packages/anatomy/...` paths the module docs cite resolve at commit 756b7ef
|
||||
//! (`crates/core/tests/curation/FILES.tsv`, RUST.md §11.23).
|
||||
//!
|
||||
//! JavaScript behaviours the TypeScript pipeline depended on are reproduced here and pinned
|
||||
//! by `oracles/r5/js-semantics.json`: object key order, `Number()`, `toLowerCase` after NFD,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//! Data contracts and business rules of the core (R2: sheet, report, archive, editor rules).
|
||||
//! `packages/domain`, the TypeScript original, was deleted at R5.7; its sources stay as the
|
||||
//! frozen N-1 copy under `packages/core-wasm/tests/n-1/domain` (byte-identical).
|
||||
|
||||
pub mod archive;
|
||||
pub mod editor;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
ts_file disposition counterpart note
|
||||
packages/anatomy/eslint.config.js deleted - package tooling, deleted with the package
|
||||
packages/anatomy/package.json deleted - package tooling, deleted with the package
|
||||
packages/anatomy/src/cli/import-equine.ts replaced crates/core/src/bin/import_equine.rs, scripts/import-equine.sh pnpm import:equine --check | --out <empty dir>; the TS CLI rewrote the seed folders in place
|
||||
packages/anatomy/src/curation/app-review.ts ported crates/core/src/curation/draft/app_review.rs -
|
||||
packages/anatomy/src/curation/apply.ts ported crates/core/src/curation/draft/apply.rs -
|
||||
packages/anatomy/src/curation/assets.ts replaced crates/core/src/curation/draft/pipeline.rs xmldom cleaning not ported: the frozen draft/assets/horse.svg bytes are read and verified (BDR-068)
|
||||
packages/anatomy/src/curation/changelog.ts ported crates/core/src/curation/draft/changelog.rs -
|
||||
packages/anatomy/src/curation/fields.ts ported crates/core/src/curation/draft/fields.rs -
|
||||
packages/anatomy/src/curation/index.ts ported crates/core/src/curation/draft/mod.rs module index
|
||||
packages/anatomy/src/curation/labels.ts ported crates/core/src/curation/draft/labels.rs -
|
||||
packages/anatomy/src/curation/migration-map.ts ported crates/core/src/curation/draft/migration_map.rs cascade-record debt kept on both sides (RUST.md §11.12)
|
||||
packages/anatomy/src/curation/ops.ts ported crates/core/src/curation/draft/ops.rs -
|
||||
packages/anatomy/src/curation/overlay.ts ported crates/core/src/curation/draft/overlay.rs, crates/core/src/curation/draft/drawing.rs -
|
||||
packages/anatomy/src/curation/pipeline.ts ported crates/core/src/curation/draft/pipeline.rs -
|
||||
packages/anatomy/src/curation/rename.ts ported crates/core/src/curation/draft/rename.rs -
|
||||
packages/anatomy/src/curation/review-report.ts ported crates/core/src/curation/draft/review_report.rs, crates/core/src/curation/report_guard.rs -
|
||||
packages/anatomy/src/curation/schema.ts ported crates/core/src/curation/draft/schema.rs, crates/core/src/curation/draft/shape.rs -
|
||||
packages/anatomy/src/curation/seed.ts ported crates/core/src/curation/draft/seed.rs -
|
||||
packages/anatomy/src/curation/sources.ts replaced crates/core/src/bin/import_equine.rs file reads moved to the binary; the core takes bytes
|
||||
packages/anatomy/src/curation/stats.ts ported crates/core/src/curation/draft/stats.rs -
|
||||
packages/anatomy/src/curation/targets.ts ported crates/core/src/curation/draft/targets.rs -
|
||||
packages/anatomy/src/curation/types.ts ported crates/core/src/curation/draft/records.rs -
|
||||
packages/anatomy/src/format.ts replaced crates/core/src/curation/prettier_json.rs, crates/core/src/curation/markdown.rs Prettier 3.8.3 layout reproduced, pinned by oracles/r5/prettier-json.json and markdown-tables.json
|
||||
packages/anatomy/src/index.ts ported crates/core/src/curation/mod.rs package index
|
||||
packages/anatomy/src/legacy/annotations.ts ported crates/core/src/curation/legacy/annotations.rs -
|
||||
packages/anatomy/src/legacy/artifacts.ts ported crates/core/src/curation/legacy/mod.rs render_artifacts
|
||||
packages/anatomy/src/legacy/authored-labels.ts ported crates/core/src/curation/legacy/authored_labels.rs -
|
||||
packages/anatomy/src/legacy/catalog-checks.ts ported crates/core/src/curation/legacy/catalog_checks.rs -
|
||||
packages/anatomy/src/legacy/catalog.ts ported crates/core/src/curation/legacy/catalog.rs -
|
||||
packages/anatomy/src/legacy/categories.ts ported crates/core/src/curation/legacy/categories.rs -
|
||||
packages/anatomy/src/legacy/ids.ts ported crates/core/src/curation/ids.rs, crates/core/src/curation/text.rs deterministicUuid, sha256Hex, slugify (oracles/r5/ids.json)
|
||||
packages/anatomy/src/legacy/importer.ts ported crates/core/src/curation/legacy/importer.rs -
|
||||
packages/anatomy/src/legacy/index.ts ported crates/core/src/curation/legacy/mod.rs module index
|
||||
packages/anatomy/src/legacy/regions.ts ported crates/core/src/curation/legacy/regions.rs -
|
||||
packages/anatomy/src/legacy/report.ts ported crates/core/src/curation/legacy/report.rs -
|
||||
packages/anatomy/src/legacy/sources.ts replaced crates/core/src/bin/import_equine.rs source paths and reads moved to the binary
|
||||
packages/anatomy/src/legacy/svg.ts ported crates/core/src/curation/legacy/svg.rs, crates/core/src/anatomy/svg/mod.rs xmldom replaced by the core SVG reader (declared, RUST.md §11.10)
|
||||
packages/anatomy/src/legacy/types.ts ported crates/core/src/curation/legacy/types.rs -
|
||||
packages/anatomy/src/legacy/vertebrae.ts ported crates/core/src/curation/legacy/vertebrae.rs -
|
||||
packages/anatomy/src/markdown.ts ported crates/core/src/curation/markdown.rs -
|
||||
packages/anatomy/src/render/compose.ts ported crates/core/src/anatomy/compose.rs R3 (oracles/r3)
|
||||
packages/anatomy/src/render/dom.ts replaced apps/app/src/anatomy/drawing.ts, crates/core/src/anatomy/svg/serialize.rs the core returns SVG text; the app imports it with DOMParser + importNode (R3)
|
||||
packages/anatomy/src/render/index.ts ported crates/core/src/anatomy/mod.rs module index
|
||||
packages/anatomy/src/render/layer.ts ported crates/core/src/anatomy/layer.rs R3 (oracles/r3)
|
||||
packages/anatomy/src/render/serialize.ts ported crates/core/src/anatomy/svg/serialize.rs -
|
||||
packages/anatomy/tests/curation.apply.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.assets.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.migration-map.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.overlay.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.pipeline.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/curation.schema.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/document.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/fixtures/mini-sheet.ts replaced crates/core/tests/oracles/r5/curation-synthetic.json, crates/core/tests/oracles/r5/review-synthetic.json the mini sheet is recorded as the baseline of the synthetic oracles
|
||||
packages/anatomy/tests/helpers.ts deleted - test helpers of the TS suites (paths, draft loading)
|
||||
packages/anatomy/tests/importer.counts.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/importer.guards.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/importer.special-cases.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/legacy.regions.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r3.layer-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.curation-synthetic-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.format-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.legacy-synthetic-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.markdown-sweep-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/r5.review-synthetic-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/render.compose.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/render.layer.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tests/seed.golden.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/anatomy/tsconfig.json deleted - package tooling, deleted with the package
|
||||
packages/anatomy/vitest.config.ts deleted - package tooling, deleted with the package
|
||||
packages/domain/eslint.config.js deleted - package tooling, deleted with the package
|
||||
packages/domain/package.json deleted - package tooling, deleted with the package
|
||||
packages/domain/src/anatomical-sheet/create.ts ported crates/core/src/domain/sheet/create.rs, packages/core-wasm/tests/n-1/domain/anatomical-sheet/create.ts R2; byte-identical frozen N-1 copy kept
|
||||
packages/domain/src/anatomical-sheet/index.ts ported crates/core/src/domain/sheet/mod.rs, packages/core-wasm/tests/n-1/domain/anatomical-sheet/index.ts module index; N-1 copy kept
|
||||
packages/domain/src/anatomical-sheet/schema.ts ported crates/core/src/domain/sheet/schema.rs, packages/core-wasm/tests/n-1/domain/anatomical-sheet/schema.ts R2; N-1 copy kept
|
||||
packages/domain/src/anatomical-sheet/sheet-index.ts ported crates/core/src/domain/sheet/index.rs, crates/core/src/domain/sheet/index_data.rs, packages/core-wasm/tests/n-1/domain/anatomical-sheet/sheet-index.ts R2; N-1 copy kept
|
||||
packages/domain/src/anatomical-sheet/validate.ts ported crates/core/src/domain/sheet/validate.rs, crates/core/src/domain/sheet/check.rs, packages/core-wasm/tests/n-1/domain/anatomical-sheet/validate.ts R2; N-1 copy kept
|
||||
packages/domain/src/archive/branding.ts ported crates/core/src/domain/archive/branding.rs, packages/core-wasm/tests/n-1/domain/archive/branding.ts R2; N-1 copy kept
|
||||
packages/domain/src/archive/envelope.ts ported crates/core/src/domain/archive/envelope.rs, crates/core/src/domain/archive/read.rs, packages/core-wasm/tests/n-1/domain/archive/envelope.ts R2; N-1 copy kept
|
||||
packages/domain/src/archive/index.ts ported crates/core/src/domain/archive/mod.rs, packages/core-wasm/tests/n-1/domain/archive/index.ts module index; N-1 copy kept
|
||||
packages/domain/src/archive/labels.ts ported crates/core/src/domain/archive/labels.rs, packages/core-wasm/tests/n-1/domain/archive/labels.ts R2; N-1 copy kept
|
||||
packages/domain/src/archive/snapshot.ts ported crates/core/src/domain/archive/snapshot.rs, crates/core/src/domain/archive/snapshot_rules.rs, packages/core-wasm/tests/n-1/domain/archive/snapshot.ts R2; N-1 copy kept
|
||||
packages/domain/src/index.ts ported crates/core/src/domain/mod.rs, packages/core-wasm/tests/n-1/domain/index.ts package index; N-1 copy kept
|
||||
packages/domain/src/report/identity.ts ported crates/core/src/domain/report/identity.rs, packages/core-wasm/tests/n-1/domain/report/identity.ts R2; N-1 copy kept
|
||||
packages/domain/src/report/index.ts ported crates/core/src/domain/report/mod.rs, packages/core-wasm/tests/n-1/domain/report/index.ts module index; N-1 copy kept
|
||||
packages/domain/src/report/migrate.ts ported crates/core/src/domain/report/read.rs, packages/core-wasm/tests/n-1/domain/report/migrate.ts migrate_report_v2_to_v3; N-1 copy kept
|
||||
packages/domain/src/report/migration-map.ts ported crates/core/src/domain/report/migration_map.rs, packages/core-wasm/tests/n-1/domain/report/migration-map.ts R2; N-1 copy kept
|
||||
packages/domain/src/report/rebase.ts ported crates/core/src/domain/report/rebase.rs, packages/core-wasm/tests/n-1/domain/report/rebase.ts R2; N-1 copy kept
|
||||
packages/domain/src/report/v2.ts ported crates/core/src/domain/report/v2.rs, packages/core-wasm/tests/n-1/domain/report/v2.ts R2; N-1 copy kept
|
||||
packages/domain/src/report/v3.ts ported crates/core/src/domain/report/v3.rs, packages/core-wasm/tests/n-1/domain/report/v3.ts R2; N-1 copy kept
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/archive.branding-labels.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/archive.envelope.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/archive.snapshot.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/fixtures/horse-slice.ts replaced crates/core/tests/fixtures/horse-slice.json the slice as Zod parsed it (R2)
|
||||
packages/domain/tests/fixtures/report-v2.full.json replaced crates/core/tests/fixtures/report-v2.full.json moved by git mv, sha256 e96b0882…729c kept (= apps/app/tests/fixtures copy)
|
||||
packages/domain/tests/fixtures/report-v2.minimal.json replaced crates/core/tests/fixtures/report-v2.minimal.json moved by git mv, sha256 ba79698c…dfe7 kept (= apps/app/tests/fixtures copy)
|
||||
packages/domain/tests/helpers/draft-sheet.ts replaced crates/core/tests/archive_support/mod.rs draft_sheet, draft_map
|
||||
packages/domain/tests/helpers/legacy-leaves.ts replaced crates/core/tests/archive_support/mod.rs legacy_leaves, leaves_as_v2_report
|
||||
packages/domain/tests/r2-characterisation.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/r2-conformance.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/r2-horse-slice.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/r2-oracles.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/report.migrate.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/report.rebase.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/report.schema.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tests/sheet-index.test.ts replaced crates/core/tests/curation/LEDGER.tsv every case: one ledger row
|
||||
packages/domain/tsconfig.json deleted - package tooling, deleted with the package
|
||||
packages/domain/vitest.config.ts deleted - package tooling, deleted with the package
|
||||
packages/supabase/scripts/upload-sheet-assets.ts replaced crates/core/src/bin/upload_sheet_assets/main.rs, crates/core/src/curation/upload.rs, scripts/upload-sheet-assets.sh pnpm assets:upload (R5.5, owner e2e PASS 11/11); assets:upload:legacy removed
|
||||
|
@@ -0,0 +1,408 @@
|
||||
ts_file case_title contract disposition target oracle note
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: set > sets a field and records before / after changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json case set-fields op0 = same input (region:C count_range {6,8}); formatted document bytes and the full records (before null, after) compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: set > creates a missing nested object for a dot path changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json set-fields: flexion description.en and document scope_disclaimer.fr create the missing nested object; document bytes compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: set > applies a subtree set to the target and every descendant changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json subtree-sets op0: same target, value reviewed (TS to_confirm); records list the same 5 targets in the same order
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: set > skips items without the field and items already at the value changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json subtree-sets: kind subtree records the category only (nodes lack the field); repeated description subtree records nothing (already at value); TS used requires_vet_referral, same rule
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames a zone and the annotations follow, one record each changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json renames-cascade: zone:hip->hip-joint records (zone:hip,null) then (annotation:hip,finding_zone_id), before item compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames a region code and the vertebral annotations follow changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json renames-cascade: region:C->CE with record annotation:neck vertebral_region_code; document compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames a view: parent links and trigger targets follow changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json renames-cascade: view:head->skull records (view:head,null),(annotation:head-trigger,opens_view_id)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames a main view: parent_view_id and view_id follow changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_draft::the_migration_map_replays_cascade_records_by_their_op_as_the_typescript_does crates/core/tests/oracles/r5/curation-synthetic.json case quirk-view-rename-retargets-annotation = same input (rename view:main): parent_view_id and view_id records and document compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames an annotation category: annotations follow changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json renames-cascade: category:joints->articulations, annotation:hip category_id record and document
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: rename > renames a reference: every citation follows changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json case quirk-reference-rename-renames-finding-path = same input (cite atlas then rename reference): last record before [atlas] after [atlas-2]
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds a node at position {"after":"flexion"} changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced crates/core/tests/oracles/r5/curation-synthetic.json, crates/core/tests/oracles/r5/pipeline.json add-remove-move: abduction at {after:flexion}; equine CHG-017 {after:pterygoid-tension} in the frozen records; document order compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds a node at position {"before":"flexion"} changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json add-remove-move: adduction at {before:extension} (TS anchor was the first sibling, same rule)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds a node at position 1 changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced crates/core/tests/oracles/r5/curation-synthetic.json, crates/core/tests/oracles/r5/pipeline.json numeric positions 0 (rotation, equine x3) and 1 (=append into one child); a mid-list index is not exercised as such, same splice
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds a node at position undefined changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json no position appends (deep-flexion, neck-anamnesis, carpus zone); records before null
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds children under a lean leaf changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json add-remove-move op0: deep-flexion added under the lean leaf flexion
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > adds a zone, an annotation and a reference at document level changeset application (ops, positions, review rule, refusals) ported cargo curation_draft::a_reference_added_at_document_level_can_be_cited_by_the_same_change ; cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced crates/core/tests/oracles/r5/curation-synthetic.json, crates/core/tests/oracles/r5/pipeline.json ported at R5.7: level A, the cite of the reference the same change added
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > removes a node and records the whole item changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json add-remove-move removes leaf extension; rehome removes category hip-dysfunctions with children: record before = whole item, after null
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: add, remove, move > moves a node into a sibling, then across zones changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json add-remove-move: rotation into sibling flexion, pain across zones before vet, trauma into surgery; records after = new paths (equine has 0 moves)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: cite > cites one item without duplicates changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json cite case: ids deduped inside one op, a cite of a present id writes no record, a new id appended after the existing one (hip/anamnesis), children untouched
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: cite > cites a subtree, and a zone stands for its categories changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json cite case: zone:hip stands for its two categories; zone:neck and finding:hip/anamnesis subtree records listed
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"set","target":"zone:nope","field":"name","value":{}}] → unknown target changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-unknown-target = same input; op message compared by equality (CHG-001 op 0: unknown target ...)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"set","target":"finding:hip","field":"name","value":{}}] → malformed target changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-malformed-target = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"set","target":"galaxy:x","field":"name","value":{}}] → unknown target changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-unknown-kind = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"set","target":"zone:hip","field":"colour","value":1}] → unknown field changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-unknown-field = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"set","target":"zone:hip","field":"id","value":"x"}] → unknown field changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-set-id = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"add","target":"finding:hip/hip-dysfunctions/mobility","value":{"id":"flexion","name":{"fr":"a","en":"a"}}}] → already exists changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-add-existing (value names differ); message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"add","target":"finding:hip/hip-dysfunctions/mobility","value":{"id":"x","name":{"fr":"a","en":"a"}},"position":{"after":"nope"}}] → unknown sibling changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-add-unknown-sibling (value names differ); message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"rename","target":"zone:hip","id":"neck"}] → already exists changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-rename-taken = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"cite","target":"finding:hip/hip-dysfunctions/mobility","reference_ids":["ghost"]}] → undeclared reference changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-cite-undeclared = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > [{"op":"move","target":"finding:hip/hip-dysfunctions/mobility","to":"finding:hip/hip-dysfunctions/mobility/flexion"}] → into itself changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-move-into-itself = same input; message equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > rejects a change citing an undeclared reference changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-change-undeclared = same input; message CHG-001: undeclared reference(s): ghost compared by equality
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > rejects an integrity error left after the ops changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo sheet_rules::annotation_finding_zone_and_region_missing crates/core/tests/oracles/r5/curation-synthetic.json apply-remove-zone-integrity = same input; only the gate prefix is compared, the text Finding zone hip does not exist is not (R2 rule code and path checked by sheet_rules)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: errors fail loud > rejects a shape error left after the ops changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-shape-error = same input; gate prefix curated document is not shape-valid compared
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: purity > is deterministic changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::two_runs_emit_the_same_bytes ; cargo curation_review::two_runs_emit_the_same_review_files - determinism held on the equine run (byte-equal artifacts), not on a mini-sheet double run; the core takes no clock or randomness (clippy disallowed_methods)
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: purity > never mutates its inputs changeset application (ops, positions, review rule, refusals) deleted - - JS aliasing hazard only: apply_changeset(baseline: &Value, references: &[Reference], changes: &[Change]) (apply.rs:210) cannot mutate its inputs; the not.toBe identity check has no Rust meaning
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > marks a node set by a B change to_confirm, with a record changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json review-rule-b: set name at level B then record (mobility review_status inherited->to_confirm, change CHG-001) compared in full
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > marks every node of an added subtree changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json review-rule-b: added new and new/child marked, a child already to_confirm skipped
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > marks cited targets under a C change changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json two-changes: level C CHG-0011 cite zone:cervical marks finding:cervical/neck-dysfunctions; review-rule-b marks cited subtree
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > marks an annotation set by a B change changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json review-rule-b: set annotation:neck name.en -> annotation:neck review_status record
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > leaves a level A change untouched changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json every level A case (set-fields, js-index-key-in-value-overwritten on mobility name) has no marking record
|
||||
packages/anatomy/tests/curation.apply.test.ts applyChangeset: review rule of levels B and C > throws when a B change sets review_status to reviewed changeset application (ops, positions, review rule, refusals) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json apply-b-sets-reviewed = same input; full message equality
|
||||
packages/anatomy/tests/curation.assets.test.ts stripLegacyAnnotations on the real Horse.svg > removes exactly the elements carrying data-anno-id draft drawing asset (frozen horse.svg, view box) replaced cargo svg_sanitiser::the_product_svgs_come_out_untouched ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte crates/core/tests/oracles/r3/sanitiser.json, supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg stripLegacyAnnotations not ported: cleaned horse.svg kept as frozen TS bytes (BDR-068, RUST.md 11.11-11.12); pinned by its parsed tree and sha256/size; the removed-element count is not re-asserted
|
||||
packages/anatomy/tests/curation.assets.test.ts stripLegacyAnnotations on the real Horse.svg > keeps the 270 drawing paths and every non-annotation byte draft drawing asset (frozen horse.svg, view box) replaced cargo svg_sanitiser::the_product_svgs_come_out_untouched ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte crates/core/tests/oracles/r3/sanitiser.json, supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg 270 paths, no data-anno-, XML declaration, no max-width: properties of the frozen file pinned by the sanitiser legitimate tree and sha256, not re-asserted one by one
|
||||
packages/anatomy/tests/curation.assets.test.ts stripLegacyAnnotations on the real Horse.svg > is deterministic and parses as XML draft drawing asset (frozen horse.svg, view box) replaced cargo svg_sanitiser::the_product_svgs_come_out_untouched crates/core/tests/oracles/r3/sanitiser.json the core reader reads the frozen horse.svg with nothing removed and the frozen tree; determinism of a cleaning step is moot (no cleaning in Rust)
|
||||
packages/anatomy/tests/curation.assets.test.ts stripLegacyAnnotations on the real Horse.svg > describes the cleaned bytes with their sha256 draft drawing asset (frozen horse.svg, view box) ported cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced ; cargo curation_format::slugs_and_uuids_match_the_typescript crates/core/tests/oracles/r5/pipeline.json, crates/core/tests/oracles/r5/ids.json sha256 and byte_size of the frozen horse.svg asserted inline; file and svg_asset_id via draft.assets == frozen record; asset uuid row in ids.json
|
||||
packages/anatomy/tests/curation.assets.test.ts stripLegacyAnnotations on the real Horse.svg > reads a viewBox into a document view_box draft drawing asset (frozen horse.svg, view box) ported cargo curation_draft::a_view_box_of_four_numbers_is_read_and_three_are_refused ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte supabase/seed/anatomical-sheets/equine/draft/document.json ported at R5.7: four numbers read, three refused
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > migrates the 612 leaves: 442 identical, 141 moved, 29 removed the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::migrates_the_612_leaves_442_identical_141_moved_29_removed ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured ; vitest apps/app/tests/unit/migration.leaves.test.ts > the 612 legacy leaves in the application > resolves every migrated leaf to a leaf node of the bundled sheet supabase/seed/anatomical-sheets/equine/legacy-import/document.json ported at R5.7: on the committed map; 612 leaves, 612 findings, (442,141,29) asserted inline on the map Rust produces (byte-equal to the committed one); app asserts 612 and 29 unresolved
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > lands every resolved leaf on a leaf of the draft document the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::lands_every_resolved_leaf_on_a_leaf_of_the_draft_document ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured ; vitest apps/app/tests/unit/migration.leaves.test.ts > the 612 legacy leaves in the application > resolves every migrated leaf to a leaf node of the bundled sheet ; cargo report_rules::the_612_legacy_leaves_migrate_through_the_draft_map supabase/seed/anatomical-sheets/equine/legacy-import/document.json ported at R5.7; node_is_leaf == Some(true) on the produced document; app: leaf node of the bundled sheet; report_rules: node exists (not leafness)
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > keeps the legacy snapshots and the vet flag verbatim on every finding the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::keeps_the_legacy_snapshots_and_the_vet_flag_verbatim_on_every_finding ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured ; cargo report_rules::the_612_legacy_leaves_migrate_through_the_draft_map supabase/seed/anatomical-sheets/equine/legacy-import/document.json ported at R5.7: FR, EN and vet per finding
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > flags exactly the leaves the curation removed, with their legacy path kept the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::flags_exactly_the_leaves_the_curation_removed_with_their_legacy_path_kept ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured supabase/seed/anatomical-sheets/equine/legacy-import/document.json ported at R5.7; flagged paths == the leaves the map sends to null (same order), each absent from the document, 29 by the fate count
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > moves the 141 relocated leaves inside their zone: 134 under a renamed category, 7 renamed leaves the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::moves_the_141_relocated_leaves_inside_their_zone_134_category_7_leaf ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured supabase/seed/anatomical-sheets/equine/legacy-import/document.json ported at R5.7: 134 / 7
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy leaf through the v2 → v3 migration > reads the migrated report back unchanged (v3 is stable) the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::reads_the_migrated_report_back_unchanged ; cargo report_rules::read_report_document_returns_v3_as_is_and_migrates_v2 ; cargo archive_rules::envelope_reads_a_bare_v3_as_is ; vitest apps/app/tests/unit/migration.leaves.test.ts > the 612 legacy leaves in the application > keeps every finding, resolved or not, through an archive PDF export and import - ported at R5.7; v3 read as is on fixtures (counters 0); the 612-leaf v3 report survives export/import equal with its 29 flags; a bare re-read of that v3 with 0/0 counters is not asserted
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy annotation as a report zone > maps the 26 observable legacy ids to annotations of the right view, names snapshotted the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::maps_the_26_observable_legacy_ids_to_annotations_of_the_right_view ; cargo report_rules::migrate_maps_legacy_ids_views_and_snapshots_the_legacy_names - ported at R5.7
|
||||
packages/anatomy/tests/curation.migration-leaves.test.ts every legacy annotation as a report zone > keeps vertebrae on the spine zones with region codes the draft defines the 612 legacy leaves and 27 annotations through the migration ported cargo curation_leaves::keeps_vertebrae_on_the_spine_zones_with_region_codes_the_draft_defines ; cargo report_rules::migrate_maps_legacy_ids_views_and_snapshots_the_legacy_names ; cargo sheet_rules::the_curated_draft_validates_with_no_issue ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte supabase/seed/anatomical-sheets/equine/draft/document.json ported at R5.7; vertebrae kept on the cervical zone (fixture, hand map); every region code defined enforced by the R2 region rule on the committed draft; 5 spine annotations in the byte-exact document
|
||||
packages/anatomy/tests/curation.migration-map.test.ts report migration map on the real draft > is a valid map covering every legacy node, with the expected fates report migration map (fates, renames, re-homing) replaced cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo report_contract::the_v2_fixtures_and_the_migration_map_parse crates/core/tests/oracles/r5/pipeline.json, supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json migrationStats 792/571/180/7/34 vs the frozen run; map byte-exact (792 paths); strict parse of the committed map
|
||||
packages/anatomy/tests/curation.migration-map.test.ts report migration map on the real draft > maps every legacy annotation with its legacy labels and the views report migration map (fates, renames, re-homing) replaced cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json, supabase/seed/anatomical-sheets/equine/legacy-import/legacy-id-map.json 27 annotations, point-mpbwtst0 and zone-mpby55kd entries, views, main_view_id frozen in the byte-exact map; legacy id map byte-exact
|
||||
packages/anatomy/tests/curation.migration-map.test.ts report migration map on the real draft > every target path exists in the draft; identical, renamed, re-homed and removed cases report migration map (fates, renames, re-homing) replaced cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json the 6 named targets frozen in the byte-exact map; every non-null target exists by construction (migration_map.rs:270-280), asserted for the 612 leaves; no Rust walk of all 792 targets
|
||||
packages/anatomy/tests/curation.migration-map.test.ts report migration map replay on a synthetic changeset > follows a rename, a move and a removal, and a renamed annotation report migration map (fates, renames, re-homing) ported cargo curation_draft::the_map_follows_a_rename_then_a_move_through_the_renamed_path ; cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json ported at R5.7: move through a just-renamed path
|
||||
packages/anatomy/tests/curation.migration-map.test.ts report migration map replay on a synthetic changeset > re-homes a node whose category was replaced by another one holding the same path report migration map (fates, renames, re-homing) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json case rehome = TS input plus an annotation rename: mobility/flexion -> hip-new/mobility/flexion, extension and hip-dysfunctions null, rehomed 2
|
||||
packages/anatomy/tests/curation.overlay.test.ts review overlay > marks moved annotations with their previous position review overlays (moved, removed, added markers) replaced cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared ; cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced crates/core/tests/oracles/r5/review-synthetic.json, supabase/seed/anatomical-sheets/equine/draft/review/annotations-main.svg every-section overlay (byte-exact): hip moved + its previous position removed, neck added; equine overlays 5 moved / 5 removed; the marker list itself is not asserted
|
||||
packages/anatomy/tests/curation.overlay.test.ts review overlay > reports an annotation dropped by the changeset review overlays (moved, removed, added markers) ported cargo curation_review::an_annotation_dropped_by_the_changeset_is_drawn_as_removed ; cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared crates/core/tests/oracles/r5/review-synthetic.json ported at R5.7
|
||||
packages/anatomy/tests/curation.overlay.test.ts review overlay > renders a framed SVG with one group per marker and a legend review overlays (moved, removed, added markers) replaced cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared crates/core/tests/oracles/r5/review-synthetic.json every-section main overlay byte-exact: root without width, groups moved/removed/added, stroke-dasharray, legend inchange, the drawing kept
|
||||
packages/anatomy/tests/curation.overlay.test.ts review overlay > frames a detail view on its view box review overlays (moved, removed, added markers) replaced cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared ; cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced crates/core/tests/oracles/r5/review-synthetic.json, supabase/seed/anatomical-sheets/equine/draft/review/annotations-head.svg detail-view-and-path head overlay framed on 2.5 1 40 30; equine head overlay on 60 100 500 380, both byte-exact
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > validates with zero integrity error equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) ported cargo sheet_rules::the_curated_draft_validates_with_no_issue ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced supabase/seed/anatomical-sheets/equine/draft/document.json, crates/core/tests/oracles/r5/pipeline.json validate == [] asserted on the committed draft; build refuses integrity errors; issues [] and sheetId vs frozen (legacy and draft sheetId equal there)
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > carries one drawing and the curated content equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) replaced cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced ; cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte crates/core/tests/oracles/r5/pipeline.json, supabase/seed/anatomical-sheets/equine/draft/document.json assets 2->1, nodes 811, descriptionsFrOnly 0 in frozen statsBefore/After; main asset id, head view_box, Cd 15-21, carpus annotation and zone in the byte-exact document
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > lists CHG-000 and the Cd range change in the CHANGELOG equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) replaced cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced supabase/seed/anatomical-sheets/equine/draft/CHANGELOG.md CHANGELOG byte-exact holds the comparison heading, the CHG-000 view:head.view_box row and the region:Cd.count_range row
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > writes the ten review sections in order equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) replaced cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared supabase/seed/anatomical-sheets/equine/draft/REVIEW-REPORT.md, crates/core/tests/oracles/r5/review-synthetic.json REVIEW-REPORT byte-exact holds the ten headings in order; synthetic every-section too
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > seeds a converging draft and never publishes equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) replaced cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike supabase/seed/anatomical-sheets/equine/draft/equine_draft.sql, crates/core/tests/oracles/r5/curation-synthetic.json equine_draft.sql byte-exact (insert_sheet_draft, converging update to status draft, no publish_sheet_version); synthetic seed SQL compared per accepted case
|
||||
packages/anatomy/tests/curation.pipeline.test.ts equine working draft (real sources + committed curation) > refuses a changeset that reuses the reserved CHG-000 equine working draft (CHG-000, CHANGELOG, REVIEW-REPORT, seed SQL) ported cargo curation_draft::a_changeset_reusing_the_reserved_asset_change_id_is_refused - ported at R5.7
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > parse the committed curation files changeset and references schema replaced cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced ; cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; cargo curation_caps::committed_files_keep_a_wide_margin_under_the_cap supabase/seed/anatomical-sheets/equine/curation/changes.json, crates/core/tests/oracles/r5/pipeline.json committed files parsed by every equine test; unique ids, C question, cited ids declared are enforced by parse/apply; id order and legacy-catalog presence only frozen (46 summaries, bibliography), not invariant checks
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects an unknown op changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-unknown-op (swap, TS test replace): refused at parse with the changes.json prefix
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects a level C change without question changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-level-c-without-question refused at parse
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects a bad change id changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-bad-id (CHG-12, TS test CHANGE-1) refused at parse
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects a change without ops changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-empty-ops refused at parse
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects an unknown key changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-unknown-change-key (extra, TS test needs_confirmation) refused at parse
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > accepts a level C change with its question changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared crates/core/tests/oracles/r5/curation-synthetic.json, crates/core/tests/oracles/r5/review-synthetic.json level C with question accepted: review-rule-c (low), two-changes, review every-section CHG-0011 (high)
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > rejects duplicate change ids and duplicate reference ids changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json schema-duplicate-change-ids and reference case references-duplicate-id refused
|
||||
packages/anatomy/tests/curation.schema.test.ts curation schemas > derives needs_confirmation from the level changeset and references schema replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/curation-synthetic.json needs_confirmation (schema.rs:34) drives the marking: B and C cases marked, A cases not; no direct unit test of the three levels
|
||||
packages/anatomy/tests/document.test.ts equine document > parses and validates with no error and no warning legacy import document validity replaced cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run ; cargo sheet_contract::the_legacy_import_baseline_prints_as_zod_outputs_it crates/core/tests/oracles/r5/pipeline.json, supabase/seed/anatomical-sheets/equine/legacy-import/document.json importer issues = validate_sheet_document of the document (importer.rs:358) compared to the frozen empty list; Zod-oracle parse of the committed baseline
|
||||
packages/anatomy/tests/document.test.ts equine document > is deterministic: same result and same bytes on two runs legacy import document validity ported cargo curation_legacy::two_runs_emit_the_same_bytes - two runs, rendered files equal; whole-result equality replaced by the frozen intermediate values
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > imports 27 annotations, 26 linked to a finding zone legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json 27 annotations, 26 linked: frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > has two views and one trigger opening head from main legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json views main/head, one trigger main->head: frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > codes exactly the five zone-colonne polygons with C, T, L, S, Cd legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json five zone-colonne zones coded C T L S Cd: frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > counts 9 bilateral annotations legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json 9 bilateral: frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > writes 792 nodes, 612 leaves, 41 vet referrals in the document legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; cargo report_rules::the_612_legacy_leaves_migrate_through_the_draft_map ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json 792 nodes / 612 leaves / 41 vet in the document (report_rules also asserts 612 and 41): frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > reports the input side from the sources: 27 ids, 26 zones, 792/612/41 legacy catalog conversion (counts) replaced cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run crates/core/tests/oracles/r5/pipeline.json stats (legacyAnnotations 27, findingZones 26, nodes 792, leaves 612, vetReferrals 41) compared whole with the frozen run
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > maps every data-anno-id of both SVGs legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/legacy-id-map.json every data-anno-id of both SVGs mapped (legacy-id-map byte-exact; legacy sources never change): frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.counts.test.ts equine import volumes > places the nine head annotations in view head legacy catalog conversion (counts) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json nine head annotations in view head: frozen in the byte-exact committed legacy import, not re-asserted as numbers
|
||||
packages/anatomy/tests/importer.guards.test.ts importer guards > throws when a zone loses a vet referral importer guards (nothing dropped, seed dollar tag) replaced cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/legacy-synthetic.json case truthy-referral (TS: zone hip: vetReferrals 1 in, 0 out) refused; Rust checks is_err only, the reason is not compared; equal counts pass on every accepted import
|
||||
packages/anatomy/tests/importer.guards.test.ts importer guards > copies FR into EN when data-anno-name-en is absent, and says so importer guards (nothing dropped, seed dollar tag) replaced cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/legacy-synthetic.json generic case: h1 and p2 without name-en get en = fr in document.json and anomaly annotation.name_en.missing a_valider in parts.anomalies, both compared
|
||||
packages/anatomy/tests/importer.guards.test.ts importer guards > refuses a document that contains the dollar-quote tag importer guards (nothing dropped, seed dollar tag) ported cargo curation_draft::a_document_holding_the_dollar_quote_tag_is_refused_by_the_seed - ported at R5.7
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > turns vertebral-precision into a region code legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json lumbar L and caudal Cd zones: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > makes data-anno-lateral explicit legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json explicit laterality (hip bilateral, c7-t1 unpaired): frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > imports the trigger without name and without finding zone legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json trigger with name null and no finding_zone_id: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > keeps ssb-dysfunctions under sphenoid and names it in the report legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run supabase/seed/anatomical-sheets/equine/legacy-import/document.json, supabase/seed/anatomical-sheets/equine/legacy-import/IMPORT-REPORT.md ssb-dysfunctions under sphenoid in the byte-exact document; IMPORT-REPORT byte-exact holds sphenoid/ssb-dysfunctions and sphenoid-dysfunctions attendu; anomalies frozen
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > keeps the anamnesis category in all zones with its three variants legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json anamnesis in 26 zones, 3 variants, id trees equal to the frozen catalog: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > writes no en key where description_en is absent legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json description without en key: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > maps category kinds from their ids legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json category kinds of hip: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > preserves node ids at every level of every zone legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json node ids preserved against the frozen catalog: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts equine import special cases > writes the lean form: no default keys on plain leaves legacy catalog conversion (special cases) replaced cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json lean form of plain leaves: frozen in the byte-exact committed document (sources never change), not re-asserted
|
||||
packages/anatomy/tests/importer.special-cases.test.ts importer-authored labels > declares every label written without a source legacy catalog conversion (special cases) replaced cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run crates/core/tests/oracles/r5/pipeline.json the nine label.authored a_valider subjects are part of the frozen anomaly list compared in order
|
||||
packages/anatomy/tests/legacy.regions.test.ts inferRegionCode > matches FR roots, with and without accents spine region inference from legacy labels ported cargo curation_format::region_inference_follows_the_typescript ; cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run ; cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/js-semantics.json ported at R5.7
|
||||
packages/anatomy/tests/legacy.regions.test.ts inferRegionCode > matches EN roots when the FR label is absent spine region inference from legacy labels ported cargo curation_format::region_inference_follows_the_typescript crates/core/tests/oracles/r5/js-semantics.json ported at R5.7
|
||||
packages/anatomy/tests/legacy.regions.test.ts inferRegionCode > returns null when no root matches spine region inference from legacy labels replaced cargo curation_format::region_inference_follows_the_typescript ; cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/legacy-synthetic.json p1 Colonne -> code null, root null and anomaly annotation.region.unknown; empty and null labels not exercised (js-semantics rows unread)
|
||||
packages/anatomy/tests/legacy.regions.test.ts inferRegionCode > reports the matched root and label, FR before EN spine region inference from legacy labels ported cargo curation_format::region_inference_follows_the_typescript ; cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run ; cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/js-semantics.json ported at R5.7: FR before EN, EN fallback
|
||||
packages/anatomy/tests/r3.layer-oracles.test.ts R3 layer oracles (TypeScript freeze) > matches the frozen layer trees annotation layer rendering (R3 oracle) replaced cargo anatomy_layer::every_frozen_layer_is_reproduced_with_its_attribute_order ; cargo anatomy_layer::an_unknown_view_is_refused ; cargo anatomy_layer::an_unnamed_trigger_names_the_opened_view_in_each_language_and_a_named_one_keeps_its_names crates/core/tests/oracles/r3/layer.json generator (MAKE_R3_ORACLES); its 8 cases are read whole with attribute order by anatomy_layer, trigger names under the declared R3 rule
|
||||
packages/anatomy/tests/r5.curation-synthetic-oracles.test.ts R5.3 synthetic curation oracle > curation-synthetic.json changeset applier on synthetic cases (R5.3 oracle) replaced cargo curation_draft::the_synthetic_cases_match_the_typescript_or_are_refused_alike ; cargo curation_draft::an_inherited_member_name_is_a_plain_key_and_bypasses_nothing ; cargo curation_draft::the_migration_map_replays_cascade_records_by_their_op_as_the_typescript_does crates/core/tests/oracles/r5/curation-synthetic.json generator; 82 cases and 7 reference files read (14 compared, 67 refused alike, 1 declared accept, counts asserted)
|
||||
packages/anatomy/tests/r5.format-oracles.test.ts R5.2 format and semantics oracles > prettier-json.json Prettier layout and JavaScript semantics (R5.2 oracle) replaced cargo curation_format::json_layout_matches_prettier_on_every_probe crates/core/tests/oracles/r5/prettier-json.json generator; every probe read, case 19 (emoji) the declared refusal
|
||||
packages/anatomy/tests/r5.format-oracles.test.ts R5.2 format and semantics oracles > markdown-tables.json Prettier layout and JavaScript semantics (R5.2 oracle) replaced cargo curation_format::tables_align_as_prettier_aligns_them crates/core/tests/oracles/r5/markdown-tables.json generator; 10 tables read, case 5 (emoji) the declared refusal
|
||||
packages/anatomy/tests/r5.format-oracles.test.ts R5.2 format and semantics oracles > js-semantics.json Prettier layout and JavaScript semantics (R5.2 oracle) replaced cargo curation_format::region_inference_follows_the_typescript ; cargo curation_format::slugs_and_uuids_match_the_typescript ; cargo curation_format::number_points_round_and_trim_follow_javascript ; cargo curation_format::object_keys_follow_javascript_order crates/core/tests/oracles/r5/js-semantics.json every section read since R5.7 (inferRegionCode added)
|
||||
packages/anatomy/tests/r5.legacy-synthetic-oracles.test.ts R5.2 synthetic importer oracle > legacy-synthetic.json legacy importer on synthetic sources (R5.2 oracle) replaced cargo curation_legacy::the_synthetic_cases_match_the_typescript_or_are_refused_alike crates/core/tests/oracles/r5/legacy-synthetic.json generator; 2 accepted cases compared on files and parts; the 8 refusals checked as is_err only, reasons not compared
|
||||
packages/anatomy/tests/r5.markdown-sweep-oracles.test.ts R5.4 Markdown sweep oracle > markdown-sweep.json Markdown report guard (R5.4 oracle) replaced cargo curation_markdown::every_probe_is_formatted_as_the_typescript_or_refused crates/core/tests/oracles/r5/markdown-sweep.json generator; 798 probes read (raw digests, then same text or UnsupportedMarkdown)
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > the RFC 8785 canonicaliser passes the RFC vectors R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger replaced cargo sheet_fingerprint::the_rfc_8785_vectors_are_reproduced crates/core/tests/oracles/r5/fingerprints.json the same two RFC 8785 vectors, frozen in fingerprints.json, run through the core canonicaliser; the TS canonicaliser was test-local
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > pipeline.json: intermediate values and the artifact ledger R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger replaced cargo curation_legacy::the_intermediate_values_match_the_frozen_typescript_run ; cargo curation_draft::the_draft_section_of_the_frozen_run_is_reproduced ; cargo curation_draft::every_ledger_row_of_the_r5_1_run_is_the_committed_file ; cargo curation_legacy::the_raw_report_is_the_text_prettier_received ; cargo curation_draft::the_pre_switch_copies_are_the_files_the_typescript_wrote ; cargo curation_review::the_raw_reports_are_the_texts_prettier_received crates/core/tests/oracles/r5/pipeline.json generator; legacy and draft sections read whole; the ledger read in part (row 117)
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > ids.json: deterministic uuids and slugs R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger replaced cargo curation_format::slugs_and_uuids_match_the_typescript crates/core/tests/oracles/r5/ids.json generator; every uuid and slug row read
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > fingerprints.json: the D-R5 matrix and the number printing R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger replaced cargo sheet_fingerprint::the_rfc_8785_vectors_are_reproduced ; cargo sheet_fingerprint::the_draft_gives_the_frozen_validated_value crates/core/tests/oracles/r5/fingerprints.json generator; Rust reads the RFC vectors and the draft/document.json row only; the D-R5 matrix of the other artifacts and the 65-number list are decided study data (BDR-068), printing held by numbers.json
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > the ledger digests are the committed files (the golden folders) R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger replaced cargo curation_draft::every_ledger_row_of_the_r5_1_run_is_the_committed_file ; cargo curation_draft::the_pre_switch_copies_are_the_files_the_typescript_wrote ; cargo curation_review::the_raw_reports_are_the_texts_prettier_received ; cargo curation_legacy::the_raw_report_is_the_text_prettier_received ; cargo sheet_fingerprint::the_draft_gives_the_frozen_validated_value crates/core/tests/oracles/r5/pipeline.json ported at R5.7: the 16 rows, pre-switch substitution
|
||||
packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tests/oracles/r5) > two runs emit the same bytes for every artifact R5.1 freeze: intermediate values, ids, fingerprints, artifact ledger ported cargo curation_legacy::two_runs_emit_the_same_bytes ; cargo curation_draft::two_runs_emit_the_same_bytes ; cargo curation_review::two_runs_emit_the_same_review_files - both folders rendered twice and compared; cleanedSvg equality moot (frozen bytes read)
|
||||
packages/anatomy/tests/r5.review-synthetic-oracles.test.ts R5.4 synthetic review oracle > review-synthetic.json review files on synthetic cases (R5.4 oracle) replaced cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared ; cargo curation_review::a_label_the_drawing_cannot_carry_is_refused ; cargo curation_review::ids_and_field_segments_that_could_forge_report_structure_are_refused crates/core/tests/oracles/r5/review-synthetic.json generator; its 4 cases read (raw and aligned reports, overlays bytes, app drawings bytes or declared rule)
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > keeps both elements of a selected point and the selected spine zone, haloed on the main view view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json hip (demo obs-demo-2) and cervical (obs-demo-3) haloed on main: circles r34/r22, polygon, #b85a3f, url(#osteo-halo), viewBox 0 0 2073.4 1629.4, no width/height; separate observations in the oracle
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > creates <defs> as the first child of an asset without one and fills it with the halo filter view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json main cases carry the defs with the halo filter before the asset children; edge asset with nested defs gets the filter appended there; tree equality (filter attribute order not compared)
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > never duplicates the filter on a root that already holds it view composition and highlight (SVG rendering) ported cargo anatomy_compose::the_halo_filter_is_never_duplicated_on_a_root_that_holds_it - ported at R5.7: compose of a root already holding the filter
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > frames the head view on its view box without any halo view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json head cases (atm, frontal, occipital; TS used parietal): viewBox 60 100 500 380, no defs, #b85a3f circles without filter
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > leaves an empty layer when nothing is selected view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json v2unresolved observations and edge-4 (no zones): empty layer
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > keeps the <title> of every kept marker and emits no data attribute view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json titles are text nodes of the frozen trees, compared; no data-* attribute in any highlighted layer
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > refuses an unknown view view composition and highlight (SVG rendering) replaced cargo anatomy_layer::an_unknown_view_is_refused ; cargo anatomy_canvas_op::closed_kinds_for_an_unknown_view_a_rejected_or_altered_drawing_and_bad_input - unknown view refused by render_layer and by view.canvas (unknown_view); compose_highlight's own UnknownView branch (compose.rs:90) has no direct test
|
||||
packages/anatomy/tests/render.compose.test.ts highlightLayer on the layer tree > filters, restyles and strips data attributes without touching the input view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json restyle (fill, fill-opacity, stroke-width kept), no filter when halo off, data-* stripped: all in the trees; highlight_layer takes the layer by value, so input untouched by construction
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg without a highlight (review drawings) > renderAppReviewDrawing(main) equals the committed review drawing view composition and highlight (SVG rendering) replaced cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; cargo curation_review::app_main_differs_only_by_the_r3_trigger_names ; import-equine --check supabase/seed/anatomical-sheets/equine/draft/review/app-main.svg declared R3 difference (trigger EN name and title, RUST.md 11.14): tree equality after the rule, the difference measured to the byte; TS asserted byte equality
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg without a highlight (review drawings) > renderAppReviewDrawing(head) equals the committed review drawing view composition and highlight (SVG rendering) ported cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; import-equine --check supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg app-head.svg byte for byte (Match::Bytes)
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg without a highlight (review drawings) > keeps the full interactive layer with its data attributes view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_canvas_equals_the_frozen_tree_and_every_state_set_its_layer ; cargo anatomy_canvas_op::each_view_answers_the_frozen_canvas ; vitest apps/app/tests/unit/canvas.trees.test.tsx > the main canvas > builds the frozen tree with no state apps/app/tests/fixtures/goldens/r3/canvas.main.json the canvas (compose_canvas) keeps the full layer with its data attributes and no defs, equal to the frozen R3 canvas golden
|
||||
packages/anatomy/tests/render.layer.test.ts annotation layer on the real draft > draws every annotation of the main view as the legacy pair, zone or trigger annotation layer rendering replaced cargo anatomy_layer::every_frozen_layer_is_reproduced_with_its_attribute_order ; cargo anatomy_layer::an_unnamed_trigger_names_the_opened_view_in_each_language_and_a_named_one_keeps_its_names crates/core/tests/oracles/r3/layer.json draft/main/no-state case: hip pair attrs (34 transparent, 22 #ff9500 0.65 stroke), title, cervical polygon, trigger attrs, attribute order; draft = oracles/sheet.draft.json
|
||||
packages/anatomy/tests/render.layer.test.ts annotation layer on the real draft > uses the detail style, the annotation colour override and the view box on the head view annotation layer rendering replaced cargo anatomy_layer::every_frozen_layer_is_reproduced_with_its_attribute_order crates/core/tests/oracles/r3/layer.json draft/head case: c0-c1 27/15 #ff0000 0.5, atm/hyoid/parietal colours, no hip
|
||||
packages/anatomy/tests/render.layer.test.ts annotation layer on the real draft > applies states as data-state on both elements of a point annotation layer rendering replaced cargo anatomy_layer::every_frozen_layer_is_reproduced_with_its_attribute_order ; cargo anatomy_compose::every_canvas_equals_the_frozen_tree_and_every_state_set_its_layer crates/core/tests/oracles/r3/layer.json, apps/app/tests/fixtures/goldens/r3/canvas.main.layers.json state case (hip, cervical, head-trigger, atm) data-state on both point elements, none elsewhere
|
||||
packages/anatomy/tests/render.layer.test.ts annotation layer on the real draft > materialises through a DOM and serialises to the same markup annotation layer rendering replaced cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; vitest apps/app/tests/unit/canvas.trees.test.tsx > the head canvas > builds the frozen tree with no state supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg DOM materialisation moved to the app (buildViewSvg, R3); serialised group, title Appareil hyoidien / Hyoid apparatus, 18 circles, no script held by the byte-exact app-head.svg; createLayerElement and serializeLayer were TS-only
|
||||
packages/anatomy/tests/render.layer.test.ts annotation layer edge cases > skips annotations without geometry and falls back to grey without any colour annotation layer rendering replaced cargo anatomy_layer::every_frozen_layer_is_reproduced_with_its_attribute_order ; cargo anatomy_layer::an_unknown_view_is_refused crates/core/tests/oracles/r3/layer.json edge document: neck and head-trigger without geometry absent, #888888 for colourless bones and missing category; unknown view refused (is_err, message not compared)
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > document.json equals a fresh run (rerun pnpm import:equine) generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/document.json document.json of a fresh run equals the committed file byte for byte
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > legacy-id-map.json equals a fresh run (rerun pnpm import:equine) generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/legacy-id-map.json legacy-id-map.json of a fresh run equals the committed file byte for byte
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > assets.json equals a fresh run (rerun pnpm import:equine) generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/assets.json assets.json of a fresh run equals the committed file byte for byte
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > IMPORT-REPORT.md equals a fresh run (rerun pnpm import:equine) generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/IMPORT-REPORT.md IMPORT-REPORT.md of a fresh run equals the committed file byte for byte
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > carries no SQL: the draft folder holds the only seed generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/ the rendered name list is exactly the four non-SQL files; --check flags any extra file
|
||||
packages/anatomy/tests/seed.golden.test.ts committed legacy-import folder (golden) > copies the SVG assets byte for byte with the recorded sha256 generated seed folders byte for byte (seed SQL included) ported cargo curation_legacy::the_committed_legacy_import_folder_is_reproduced_byte_for_byte ; import-equine --check supabase/seed/anatomical-sheets/equine/legacy-import/assets/ each copy equals its source and its recorded sha256; byte_size held by assets.json byte equality
|
||||
packages/anatomy/tests/seed.golden.test.ts committed draft folder (golden) > equals a fresh run for every produced file (the two fingerprinted ones before R5.6) generated seed folders byte for byte (seed SQL included) replaced cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte ; cargo curation_review::the_review_files_of_the_committed_draft_are_reproduced ; cargo curation_draft::the_switch_changes_only_the_fingerprint_of_the_two_files ; cargo curation_draft::the_pre_switch_copies_are_the_files_the_typescript_wrote ; import-equine --check supabase/seed/anatomical-sheets/equine/draft/, crates/core/tests/fixtures/r5-6/pre-switch/ Rust output vs the committed (switched) draft; pre-switch files = ledger and = committed under rule R5.6-fingerprint-v1; app-main.svg under the R3 rule
|
||||
packages/anatomy/tests/seed.golden.test.ts committed draft folder (golden) > holds no file the run does not produce generated seed folders byte for byte (seed SQL included) replaced cargo curation_draft::the_generated_folders_hold_exactly_the_files_the_pipeline_writes ; import-equine --check supabase/seed/anatomical-sheets/equine/draft/ listing of not-produced files (import_equine.rs:258-265) runs only in the manual --check; no cargo test or gate (rust:check, check:all) lists the committed draft folder
|
||||
packages/anatomy/tests/seed.golden.test.ts committed draft folder (golden) > holds the cleaned drawing with the recorded sha256 generated seed folders byte for byte (seed SQL included) ported cargo curation_draft::the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg sha256 and byte length of the frozen horse.svg equal the recorded asset; cleanedSvg string equality moot
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > accepts the horse slice fixture sheet document shape (anatomical model validation) ported cargo sheet_shape::accepts_the_horse_slice_and_its_own_output - parses the lean input of crates/core/tests/fixtures/horse-slice.json (frozen JSON of horseSliceInput)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > accepts a parsed document again (output is valid input) sheet document shape (anatomical model validation) ported cargo sheet_shape::accepts_the_horse_slice_and_its_own_output - parsed document serialised then reparsed equal (sheet_shape.rs:59-62)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects an unknown top-level key sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects an unknown nested key sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a stable id with spaces sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a stable id with an accent sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects an empty stable id sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects schema_version 1 sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a non-uuid svg_asset_id sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a polygon with 2 points sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a circle with r 0 sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a region count of 0 sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a missing en label sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a detail view without parent_view_id sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a detail_trigger with finding_zone_id sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a javascript: reference url sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a reference type foo sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a review_status foo sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a count_range with min 0 sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts AnatomicalSheetDocumentSchema > rejects a finding category kind foo sheet document shape (anatomical model validation) ported cargo sheet_shape::refuses_what_zod_refuses - same mutation and refusal in the Rust table (sheet_shape.rs:70-247)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > accepts hip sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern - accept loop sheet_shape.rs:252-254; is_stable_id is the deserializer check (sheet/schema.rs:42)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > accepts c7-t1 sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern - accept loop sheet_shape.rs:252-254; is_stable_id is the deserializer check (sheet/schema.rs:42)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > accepts view_main sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern - accept loop sheet_shape.rs:252-254; is_stable_id is the deserializer check (sheet/schema.rs:42)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > accepts 0 sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern - accept loop sheet_shape.rs:252-254; is_stable_id is the deserializer check (sheet/schema.rs:42)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > rejects "Hip Joint" sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern ; cargo faunosteo_core::domain::js::tests::patterns_match_the_zod_regular_expressions - refuse loop sheet_shape.rs:255-257
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > rejects "É" sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern ; cargo faunosteo_core::domain::js::tests::patterns_match_the_zod_regular_expressions - refuse loop sheet_shape.rs:255-257
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > rejects "" sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern ; cargo faunosteo_core::domain::js::tests::patterns_match_the_zod_regular_expressions - refuse loop sheet_shape.rs:255-257
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > rejects "-hip" sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern ; cargo faunosteo_core::domain::js::tests::patterns_match_the_zod_regular_expressions - refuse loop sheet_shape.rs:255-257
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts StableIdSchema > rejects "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" sheet document shape (anatomical model validation) ported cargo sheet_shape::stable_ids_follow_the_pattern ; cargo faunosteo_core::domain::js::tests::patterns_match_the_zod_regular_expressions - refuse loop sheet_shape.rs:255-257
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts FindingNodeSchema defaults > fills the optional keys of a lean node, recursively sheet document shape (anatomical model validation) ported cargo sheet_shape::a_lean_node_gets_its_defaults_recursively - defaults and recursive child equality (sheet_shape.rs:268-283)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts FindingNodeSchema defaults > keeps explicit values of the fixture sheet document shape (anatomical model validation) ported cargo sheet_shape::explicit_values_of_the_fixture_are_kept - lameness vet flag, trauma refs, Cd 15-21, C null, annotation[0] inherited (sheet_shape.rs:288-300)
|
||||
packages/domain/tests/anatomical-sheet.schema.test.ts FindingNodeSchema defaults > does not add default keys to the lean input sheet document shape (anatomical model validation) ported cargo sheet_shape::the_lean_input_carries_no_default_key - checked on the frozen JSON fixture instead of the TS factory
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts validateSheetDocument on the horse slice > reports no error and no warning sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::the_horse_slice_has_no_issue - empty issue list (sheet_rules.rs:87)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.main.count sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_main_count - [view.main.count, views] (sheet_rules.rs:99)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.main.count with no main view sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_main_count - no main view contains view.main.count (sheet_rules.rs:100-105)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.id.duplicate sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_id_duplicate - views[2].id (sheet_rules.rs:111-114)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.parent.missing sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_parent_missing - views[2].parent_view_id (sheet_rules.rs:120-123)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.parent.cycle (terminates on a two-view loop) sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_parent_cycle_terminates_on_a_two_view_loop - two cycle issues (sheet_rules.rs:134-140)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.parent.cycle on a self-parent sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_parent_cycle_on_a_self_parent - sheet_rules.rs:150-153
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.unreachable sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_unreachable - views[1] (sheet_rules.rs:159)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.asset.missing on the main view sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_asset_missing_on_the_main_view_and_on_a_bare_detail - views[0].svg_asset_id (sheet_rules.rs:164-168)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > view.asset.missing on a detail view without asset nor view_box sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::view_asset_missing_on_the_main_view_and_on_a_bare_detail - views[1].view_box (sheet_rules.rs:169-177)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.id.duplicate (across views) sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_id_duplicate_across_views - copy of annotations[4] (atm, observable) moved to view-main (sheet_rules.rs:182-192)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.view.missing sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_view_and_category_missing - annotations[6].view_id (sheet_rules.rs:197-204)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.category.missing sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_view_and_category_missing - annotations[0].category_id (sheet_rules.rs:205-213)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.opens_view.invalid when the target is not a child sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_opens_view_invalid - loop trigger (sheet_rules.rs:218-228)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.opens_view.invalid when the target is main or absent sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_opens_view_invalid - to-main and to-ghost (sheet_rules.rs:229-247)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.finding_zone.missing sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_finding_zone_and_region_missing - annotations[6].finding_zone_id (sheet_rules.rs:252-262)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.region.missing sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_finding_zone_and_region_missing - annotations[1].vertebral_region_code (sheet_rules.rs:263-274)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > annotation.no_findings is a warning sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::annotation_no_findings_is_a_warning - code, path and Warning severity (sheet_rules.rs:283-290)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > region.code.duplicate sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::region_category_and_zone_duplicates - vertebral_config.regions[5].code (sheet_rules.rs:295-302)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > category.id.duplicate sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::region_category_and_zone_duplicates - categories[4].id (sheet_rules.rs:303-307)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding_zone.id.duplicate sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::region_category_and_zone_duplicates - finding_zones[5].id (sheet_rules.rs:308-312)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding.id.duplicate among finding categories sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::finding_id_duplicate_among_categories_and_nested_children - categories[3].id (sheet_rules.rs:317-324)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding.id.duplicate among nested children sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::finding_id_duplicate_among_categories_and_nested_children - children[0].children[2].id (sheet_rules.rs:325-336)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding ids may repeat across different sibling arrays sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::finding_ids_may_repeat_across_different_sibling_arrays - no issue (sheet_rules.rs:345)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > reference.id.duplicate sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::reference_duplicate_and_missing_citations - references[1].id (sheet_rules.rs:350-354)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding.reference.missing on a category and on a nested node sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::reference_duplicate_and_missing_citations - both reference_ids paths (sheet_rules.rs:355-373)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > region.count_range.invalid when count sits outside the range sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::region_count_range_invalid_and_bounds - code and path, plus the message (sheet_rules.rs:382-394)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > region.count_range accepts count on the bounds sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::region_count_range_invalid_and_bounds - 18-18 gives no issue (sheet_rules.rs:395-396)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts integrity rules (one mutation per code) > finding_zone.unreferenced is a warning sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::finding_zone_unreferenced_is_a_warning - finding_zones[5] and Warning (sheet_rules.rs:408-415)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts publication gate > accepts the fixture sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::publication_gate - is_publishable(slice) (sheet_rules.rs:442); assertPublishable no-throw has no separate Rust call
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts publication gate > accepts a document with warnings only sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::publication_gate - one warning, publishable (sheet_rules.rs:443-448)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts publication gate > refuses a document with an error, exposing the issues sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::publication_gate - not publishable, check_sheet_document issues = [view.asset.missing] (sheet_rules.rs:449-454)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts createEmptySheetDocument > is valid for the shape tier sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::the_empty_document_is_shape_valid_but_not_publishable - PARTIAL: reparse, one main view-main without asset (sheet_rules.rs:464-470); view_box null not asserted (literal in sheet/create.rs:32)
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts createEmptySheetDocument > is not publishable: the main view has no asset sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::the_empty_document_is_shape_valid_but_not_publishable - codes = [view.asset.missing] (sheet_rules.rs:471-475); the throw / is_publishable=false is not called on it
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts ID stability under translation > keeps ids, references and validation output when labels change sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::ids_and_validation_output_survive_a_translation - PARTIAL: counter>50, ids and validation equal (sheet_rules.rs:532-541); TS 'relabeled differs' and 'non-label content identical after parse' not asserted
|
||||
packages/domain/tests/anatomical-sheet.validate.test.ts ID stability under translation > keeps validation output identical on a broken document too sheet integrity rules (reference integrity, stable ids) ported cargo sheet_rules::validation_output_survives_a_translation_of_a_broken_document - sheet_rules.rs:557-560
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > accepts the current identity and both image kinds archive branding and PDF labels ported cargo archive_rules::branding_accepts_the_identity_and_both_image_kinds - sample and bare branding parse to themselves (archive_rules.rs:41-45)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects unknown key archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 0 of the table (archive_rules.rs:56)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects non-http URL archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 1 of the table (archive_rules.rs:57)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects ftp URL archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 2 of the table (archive_rules.rs:58)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects URL over 2048 chars archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 3 of the table (archive_rules.rs:59)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects PNG base64 over 512 KiB archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 4 of the table (archive_rules.rs:64)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects PNG base64 with foreign characters archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 5 of the table (archive_rules.rs:69)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects SVG over 256 KiB archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 6 of the table (archive_rules.rs:74)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects fallback text over 128 chars archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 7 of the table (archive_rules.rs:79)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema > rejects credit with unknown key archive branding and PDF labels ported cargo archive_rules::branding_rejects_its_faults - case 8 of the table (archive_rules.rs:80)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts https://faunosteo.com archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts https://zenquality.fr archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts https://www.instagram.com/paws.iin.harmony archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts http://localhost:5173 archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts https://x.test/a-b_c~d?e=1&f=2#frag archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > accepts https://x.test/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa archive branding and PDF labels ported cargo archive_rules::branding_urls - accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a closing parenthesis in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects an opening parenthesis in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a PDF action injection in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a backslash in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a space in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a tab in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a control character in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects DEL in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects an angle bracket in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a double quote in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a single quote in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a non-ASCII character in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects no host in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts BrandingSchema URLs > rejects a scheme in upper case in the site URL and in a credit URL archive branding and PDF labels ported cargo archive_rules::branding_urls - refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.branding-labels.test.ts PdfLabelSetSchema > lists 25 distinct keys and accepts a complete set in both locales archive branding and PDF labels ported cargo archive_rules::label_sets ; cargo archive_rules::envelope_v1_is_accepted_whole - 25 distinct keys, set parses (archive_rules.rs:135-144); full equality of the set inside the envelope (archive_rules.rs:652)
|
||||
packages/domain/tests/archive.branding-labels.test.ts PdfLabelSetSchema > rejects a missing key, an extra key, a long value, a missing locale archive branding and PDF labels ported cargo archive_rules::label_sets - missing, extra, 257 chars, no en, extra de (archive_rules.rs:145-158)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > accepts the current identity and both image kinds archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_accepts_the_identity_and_both_image_kinds - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; sample and bare branding parse to themselves (archive_rules.rs:41-45)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects unknown key archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 0 of the table (archive_rules.rs:56)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects non-http URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 1 of the table (archive_rules.rs:57)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects ftp URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 2 of the table (archive_rules.rs:58)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects URL over 2048 chars archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 3 of the table (archive_rules.rs:59)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects PNG base64 over 512 KiB archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 4 of the table (archive_rules.rs:64)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects PNG base64 with foreign characters archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 5 of the table (archive_rules.rs:69)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects SVG over 256 KiB archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 6 of the table (archive_rules.rs:74)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects fallback text over 128 chars archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 7 of the table (archive_rules.rs:79)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema > rejects credit with unknown key archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; case 8 of the table (archive_rules.rs:80)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts https://faunosteo.com archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts https://zenquality.fr archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts https://www.instagram.com/paws.iin.harmony archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts http://localhost:5173 archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts https://x.test/a-b_c~d?e=1&f=2#frag archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > accepts https://x.test/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a closing parenthesis in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects an opening parenthesis in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a PDF action injection in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a backslash in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a space in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a tab in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a control character in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects DEL in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects an angle bracket in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a double quote in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a single quote in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a non-ASCII character in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects no host in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts BrandingSchema URLs > rejects a scheme in upper case in the site URL and in a credit URL archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/archive.envelope.test.ts PdfLabelSetSchema > lists 25 distinct keys and accepts a complete set in both locales archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::label_sets ; cargo archive_rules::envelope_v1_is_accepted_whole - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; 25 distinct keys, set parses (archive_rules.rs:135-144); full equality of the set inside the envelope (archive_rules.rs:652)
|
||||
packages/domain/tests/archive.envelope.test.ts PdfLabelSetSchema > rejects a missing key, an extra key, a long value, a missing locale archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::label_sets - same body re-registered by the import of archive.branding-labels.test in archive.envelope.test.ts; missing, extra, 257 chars, no en, extra de (archive_rules.rs:145-158)
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: bare reports > reads a bare v3 as is archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_reads_a_bare_v3_as_is - whole outcome equality (archive_rules.rs:591)
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: bare reports > migrates a bare v2 with the counts of the migration archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_migrates_a_bare_v2_with_the_counts_of_the_migration - origin v2, migrated, counts of the 612 leaves (archive_rules.rs:606-617); reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: bare reports > throws for a report version it cannot read, or a non-object archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_throws_for_an_unreadable_report_version_or_a_non_object - version 1 and null/string/42/array (archive_rules.rs:624-640); TS 'undefined' has no JSON form
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > accepts a valid v1 envelope whole archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_v1_is_accepted_whole - archive_rules.rs:646-653
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > keeps the report of an envelope version it does not know archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_of_an_unknown_version_keeps_the_report - archive_rules.rs:662-668
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > names the report version when the wrapped report is unknown archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_names_the_wrapped_report_version_it_cannot_read - found 4 (archive_rules.rs:679)
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > ignores unknown metadata keys, __proto__ included, within v1 archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_ignores_unknown_metadata_keys_proto_included - futureField and __proto__ absent from the archive (archive_rules.rs:695,708); JS prototype-pollution probe has no Rust equivalent
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > drops the envelope on a wrapper fault (schema): branding, labels, metadata archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_is_dropped_on_a_wrapper_fault - branding, labels, locale, format (archive_rules.rs:724-740)
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > drops a snapshot over the caps or failing its own schema archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_drops_a_snapshot_over_the_caps_or_failing_its_schema - caps, schema x2, integrity (archive_rules.rs:748-770)
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > drops a snapshot of another sheet than the report (sheet_mismatch) archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_drops_a_snapshot_of_another_sheet - sha and sheetId give sheet_mismatch (archive_rules.rs:779-792); report equality on the sha case not asserted
|
||||
packages/domain/tests/archive.envelope.test.ts readArchiveDocument: envelopes > migrates a v2 report found inside an envelope and still checks the snapshot archive envelope v1 reading (old archive compatibility) ported cargo archive_rules::envelope_migrates_a_wrapped_v2_report_and_still_checks_the_snapshot - archive_rules.rs:804-807; reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > keeps every view, annotation, category and region, empties the bibliography sheet snapshot carried by an archive ported cargo archive_rules::draft_snapshot_keeps_every_view_annotation_category_and_region - archive_rules.rs:215-227; draft_full_report reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > prunes finding trees to the paths the report uses, every zone kept sheet snapshot carried by an archive ported cargo archive_rules::draft_snapshot_prunes_finding_trees_to_the_paths_used - archive_rules.rs:238-275
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > carries the reachable asset with its manifest hash and the full ref sheet snapshot carried by an archive ported cargo archive_rules::draft_snapshot_carries_the_reachable_asset_hash_and_full_ref - archive_rules.rs:283-304
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > is a valid document with no integrity error, under 250,000 bytes pretty-printed sheet snapshot carried by an archive ported cargo archive_rules::draft_snapshot_is_valid_small_and_passes_its_gate - 0 errors, < 250000 bytes, gate returns it (archive_rules.rs:315-319)
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > is pure and deterministic sheet snapshot carried by an archive ported cargo archive_rules::draft_snapshot_is_pure_and_deterministic - document unchanged, rebuild equal (archive_rules.rs:328-329); JS no-aliasing (not.toBe) is TS-only
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the equine draft > keeps what exists of an unresolved path and nothing else (legacy leaves) sheet snapshot carried by an archive ported cargo archive_rules::legacy_leaves_snapshot_keeps_what_exists_of_an_unresolved_path_and_nothing_else - PARTIAL: node present iff resolved (archive_rules.rs:336-365); TS ref/assets checks of snapshotIndexSource (TS-only adapter) not ported
|
||||
packages/domain/tests/archive.snapshot.test.ts buildSheetSnapshot on the slice > copies review_status and requires_vet_referral, skips an asset it has no text for sheet snapshot carried by an archive ported cargo archive_rules::slice_snapshot_copies_review_status_and_vet_flag_and_skips_a_missing_asset - archive_rules.rs:372-423
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > accepts the slice snapshot and returns the parsed copy sheet snapshot carried by an archive ported cargo archive_rules::assert_accepts_the_slice_snapshot_and_returns_the_parsed_copy - archive_rules.rs:427-428
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects a finding tree deeper than the cap before parsing anything (caps) sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_a_tree_deeper_than_the_cap_before_parsing_anything - caps, schema, schema (archive_rules.rs:438-445)
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects shape faults (schema): unknown key, missing field, too many assets, non-object sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_shape_faults - archive_rules.rs:450-466
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects a __proto__ key without polluting anything sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_a_proto_key - schema (archive_rules.rs:476); JS pollution probe is TS-only
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects counts over the caps (caps) sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_counts_over_the_caps - views, annotations, nodes, label (archive_rules.rs:489-511)
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects oversize assets in bytes, single and total (caps) sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_oversize_assets_in_bytes_single_and_total - archive_rules.rs:518-526
|
||||
packages/domain/tests/archive.snapshot.test.ts assertSnapshot > rejects integrity faults: a sheet rule error, a view reaching no carried asset sheet snapshot carried by an archive ported cargo archive_rules::assert_rejects_a_sheet_rule_error ; cargo archive_rules::assert_rejects_a_view_reaching_no_carried_asset - atm zone removed; no asset; other asset id (archive_rules.rs:530-537, 550)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > accepts the current identity and both image kinds R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_accepts_the_identity_and_both_image_kinds - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; sample and bare branding parse to themselves (archive_rules.rs:41-45)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects unknown key R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 0 of the table (archive_rules.rs:56)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects non-http URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 1 of the table (archive_rules.rs:57)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects ftp URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 2 of the table (archive_rules.rs:58)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects URL over 2048 chars R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 3 of the table (archive_rules.rs:59)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects PNG base64 over 512 KiB R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 4 of the table (archive_rules.rs:64)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects PNG base64 with foreign characters R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 5 of the table (archive_rules.rs:69)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects SVG over 256 KiB R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 6 of the table (archive_rules.rs:74)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects fallback text over 128 chars R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 7 of the table (archive_rules.rs:79)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema > rejects credit with unknown key R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_rejects_its_faults - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; case 8 of the table (archive_rules.rs:80)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts https://faunosteo.com R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts https://zenquality.fr R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts https://www.instagram.com/paws.iin.harmony R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts http://localhost:5173 R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts https://x.test/a-b_c~d?e=1&f=2#frag R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > accepts https://x.test/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; accept loop (archive_rules.rs:93-105)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a closing parenthesis in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects an opening parenthesis in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a PDF action injection in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a backslash in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a space in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a tab in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a control character in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects DEL in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects an angle bracket in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a double quote in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a single quote in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a non-ASCII character in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects no host in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls ; cargo faunosteo_core::domain::archive::branding::tests::branding_urls_follow_the_zod_pattern - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts BrandingSchema URLs > rejects a scheme in upper case in the site URL and in a credit URL R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::branding_urls - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; refused as siteUrl and as partner.url (archive_rules.rs:107-130)
|
||||
packages/domain/tests/r2-characterisation.test.ts PdfLabelSetSchema > lists 25 distinct keys and accepts a complete set in both locales R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::label_sets ; cargo archive_rules::envelope_v1_is_accepted_whole - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; 25 distinct keys, set parses (archive_rules.rs:135-144); full equality of the set inside the envelope (archive_rules.rs:652)
|
||||
packages/domain/tests/r2-characterisation.test.ts PdfLabelSetSchema > rejects a missing key, an extra key, a long value, a missing locale R2 freeze: report and archive readers, rebase, snapshot verdicts ported cargo archive_rules::label_sets - same body re-registered by the import of archive.branding-labels.test in r2-characterisation.test.ts; missing, extra, 257 chars, no en, extra de (archive_rules.rs:145-158)
|
||||
packages/domain/tests/r2-characterisation.test.ts R2 characterisation oracles (frozen from the TypeScript domain) > characterisation.json: report, archive, rebase and snapshot functions R2 freeze: report and archive readers, rebase, snapshot verdicts replaced cargo characterisation::rust_does_what_the_typescript_did ; cargo characterisation::rust_does_what_the_typescript_did_with_the_integrity_rules ; cargo characterisation::lone_surrogates_are_refused_never_replaced crates/core/tests/oracles/characterisation.json TS (MAKE unset) recomputes the 85 cases and asserts the committed file byte for byte; Rust compares its outputs to the same file; generator side is TS-only
|
||||
packages/domain/tests/r2-characterisation.test.ts R2 characterisation oracles (frozen from the TypeScript domain) > verdicts.json: accept / refuse of the Zod schemas on hostile inputs R2 freeze: report and archive readers, rebase, snapshot verdicts replaced cargo characterisation::the_contracts_accept_and_refuse_what_zod_does crates/core/tests/oracles/verdicts.json TS (MAKE unset) recomputes the 765 Zod verdicts and asserts the committed file; Rust replays every verdict (1 L1 exception pinned)
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > clean integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/clean.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-main-count integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-main-count.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-parent-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-parent-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-parent-cycle integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-parent-cycle.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-unreachable integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-unreachable.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-asset-missing-main integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-asset-missing-main.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > view-asset-missing-detail integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/view-asset-missing-detail.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-view-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-view-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-category-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-category-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-opens-view-invalid integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-opens-view-invalid.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-finding-zone-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-finding-zone-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-region-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-region-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > annotation-no-findings integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/annotation-no-findings.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > region-code-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/region-code-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > category-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/category-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > finding-zone-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/finding-zone-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > finding-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/finding-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > reference-id-duplicate integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/reference-id-duplicate.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > finding-reference-missing integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/finding-reference-missing.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > region-count-range-invalid integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/region-count-range-invalid.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > finding-zone-unreferenced integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/finding-zone-unreferenced.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > several-errors integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/several-errors.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > shape-references-not-array integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/shape-references-not-array.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > shape-reference-url-scheme integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_rust_rules_report_what_the_typescript_rules_reported ; cargo sheet_conformance::the_sql_expectations_are_the_mirrored_error_codes ; cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance/shape-reference-url-scheme.json TS (MAKE unset) asserts the fixture file = TS validateSheetDocument output (+ shape tier verdict); Rust checks its rules and the SQL codes against the same file
|
||||
packages/domain/tests/r2-conformance.test.ts sheet conformance fixtures > has no stale fixture file integrity codes shared with SQL (pgTAP conformance) replaced cargo sheet_conformance::the_pgtap_file_is_generated_from_the_fixtures crates/core/tests/conformance TS lists files absent from its CASES; Rust reads every *.json of the folder (>=25) and the committed supabase/tests/011_sheet_conformance.sql (26 asserts) pins the set
|
||||
packages/domain/tests/r2-horse-slice.test.ts horse slice JSON fixture > equals the TypeScript lean input horse slice fixture freeze deleted - - TS generator/asserter of crates/core/tests/fixtures/horse-slice.json from horse-slice.ts; once the TS fixture is gone the JSON is the source; no business contract
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > sheet.draft.json Zod output oracles (contracts byte for byte) replaced cargo sheet_contract::the_curated_draft_prints_as_zod_outputs_it crates/core/tests/oracles/sheet.draft.json TS asserts source path and Zod(draft/document.json) = oracle output; Rust prints its parse of the same source and compares to the oracle output
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > sheet.legacy-import.json Zod output oracles (contracts byte for byte) replaced cargo sheet_contract::the_legacy_import_baseline_prints_as_zod_outputs_it crates/core/tests/oracles/sheet.legacy-import.json same mechanism on legacy-import/document.json
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > migration-map.draft.json Zod output oracles (contracts byte for byte) replaced cargo report_contract::the_draft_migration_map_reads_as_zod_read_it_entry_by_entry ; cargo report_contract::the_v2_fixtures_and_the_migration_map_parse ; cargo curation_draft::the_pre_switch_copies_are_the_files_the_typescript_wrote ; cargo curation_draft::the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured crates/core/tests/oracles/migration-map.draft.json entry by entry since R5.7; PARTIAL: TS compares Zod(pre-switch copy crates/core/tests/fixtures/r5-6/pre-switch/report-migration-map.json) to the oracle output; no Rust test reads the oracle output, only parse of the committed map with counts >20 and >600 (actual 27 and 792)
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > report-v3.demo.json Zod output oracles (contracts byte for byte) replaced cargo report_contract::the_demo_report_prints_as_zod_outputs_it crates/core/tests/oracles/report-v3.demo.json byte-for-byte print of the Rust parse vs the oracle output
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > report-v2.full.json Zod output oracles (contracts byte for byte) replaced cargo report_contract::the_v2_fixtures_and_the_migration_map_parse ; cargo characterisation::rust_does_what_the_typescript_did crates/core/tests/oracles/report-v2.full.json Rust only checks the v2 parse succeeds (ReportV2 is never printed); the migrated output of the same fixture is compared exactly (case 'readReport: v2 full' of characterisation.json)
|
||||
packages/domain/tests/r2-oracles.test.ts Zod output oracles of the R2 switch > report-v2.minimal.json Zod output oracles (contracts byte for byte) replaced cargo report_contract::the_v2_fixtures_and_the_migration_map_parse ; cargo characterisation::rust_does_what_the_typescript_did crates/core/tests/oracles/report-v2.minimal.json as above, case 'readReport: v2 minimal'
|
||||
packages/domain/tests/r2-oracles.test.ts the committed migration map after R5.6 > is the oracle with only the fingerprint moved to the canonical value Zod output oracles (contracts byte for byte) replaced cargo curation_draft::the_switch_changes_only_the_fingerprint_of_the_two_files ; cargo curation_draft::the_pre_switch_copies_are_the_files_the_typescript_wrote crates/core/tests/oracles/migration-map.draft.json TS: committed map = oracle with documentSha256 27c7..->12d7..; Rust: committed = pre-switch copy + same rule byte-exact, pre-switch = TS bytes (sha in oracles/r5/pipeline.json)
|
||||
packages/domain/tests/report.migrate.test.ts Report v3 schema > accepts a report with an empty reserved localAnnotations and defaults it Report v2 → v3 migration ported cargo report_rules::report_v3_schema_defaults_and_refusals - localAnnotations defaults to [] (report_rules.rs:154-155)
|
||||
packages/domain/tests/report.migrate.test.ts Report v3 schema > rejects version 2 Report v2 → v3 migration ported cargo report_rules::report_v3_schema_defaults_and_refusals - same patch on the migrated minimal report (report_rules.rs:156-167); reads packages/domain/tests/fixtures/report-v2.minimal.json
|
||||
packages/domain/tests/report.migrate.test.ts Report v3 schema > rejects a reserved localAnnotations entry Report v2 → v3 migration ported cargo report_rules::report_v3_schema_defaults_and_refusals - same patch on the migrated minimal report (report_rules.rs:156-167); reads packages/domain/tests/fixtures/report-v2.minimal.json
|
||||
packages/domain/tests/report.migrate.test.ts Report v3 schema > rejects a French severity value Report v2 → v3 migration ported cargo report_rules::report_v3_schema_defaults_and_refusals - same patch on the migrated minimal report (report_rules.rs:156-167); reads packages/domain/tests/fixtures/report-v2.minimal.json
|
||||
packages/domain/tests/report.migrate.test.ts Report v3 schema > rejects a malformed document hash Report v2 → v3 migration ported cargo report_rules::report_v3_schema_defaults_and_refusals - same patch on the migrated minimal report (report_rules.rs:156-167); reads packages/domain/tests/fixtures/report-v2.minimal.json
|
||||
packages/domain/tests/report.migrate.test.ts migrateReportV2ToV3 on the golden fixtures > keeps identity, dates, conclusion and appointment verbatim Report v2 → v3 migration ported cargo report_rules::migrate_keeps_identity_dates_conclusion_and_appointment - report_rules.rs:175-194; reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/report.migrate.test.ts migrateReportV2ToV3 on the golden fixtures > maps legacy ids to annotation ids, views and snapshots the legacy names Report v2 → v3 migration ported cargo report_rules::migrate_maps_legacy_ids_views_and_snapshots_the_legacy_names - report_rules.rs:210-231; reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/report.migrate.test.ts migrateReportV2ToV3 on the golden fixtures > remaps moved finding paths, keeps removed ones flagged with their snapshots Report v2 → v3 migration ported cargo report_rules::migrate_remaps_moved_paths_and_flags_removed_ones - report_rules.rs:247-264; reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/report.migrate.test.ts migrateReportV2ToV3 on the golden fixtures > converts severities to stable codes Report v2 → v3 migration ported cargo report_rules::migrate_converts_severities_to_stable_codes - moderate and severe present (report_rules.rs:276); the 'only the three codes' check is the Severity type; reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/report.migrate.test.ts migrateReportV2ToV3 on the golden fixtures > flags an unknown legacy zone id and an unknown finding path instead of dropping them Report v2 → v3 migration ported cargo report_rules::migrate_flags_an_unknown_zone_and_an_unknown_path_instead_of_dropping_them - whole zone and finding objects, counts 1/1 (report_rules.rs:292-301); reads packages/domain/tests/fixtures/report-v2.full.json
|
||||
packages/domain/tests/report.migrate.test.ts readReportDocument > returns a v3 document as is and migrates a v2 one Report v2 → v3 migration ported cargo report_rules::read_report_document_returns_v3_as_is_and_migrates_v2 - report_rules.rs:308-315; reads report-v2.minimal.json of packages/domain
|
||||
packages/domain/tests/report.migrate.test.ts readReportDocument > refuses unknown versions with the found version Report v2 → v3 migration ported cargo report_rules::read_report_document_refuses_unknown_versions_with_the_found_version - 1, none, 7 (report_rules.rs:322-333); reads report-v2.minimal.json of packages/domain
|
||||
packages/domain/tests/report.migrate.test.ts hostile identifiers > treats prototype keys as unknown ids instead of throwing Report v2 → v3 migration ported cargo report_rules::hostile_identifiers_are_unknown_ids - 2 zones, 1 finding, viewId __proto__ (report_rules.rs:349-350); reads report-v2.minimal.json of packages/domain
|
||||
packages/domain/tests/report.rebase.test.ts rebaseReportOnSheet > returns the report untouched when it already sits on the loaded sheet rebase of a report on a sheet ported cargo report_rules::rebase_returns_the_report_untouched_on_the_loaded_sheet - equality and 0/0/false (report_rules.rs:474-482); JS identity (toBe) is TS-only
|
||||
packages/domain/tests/report.rebase.test.ts rebaseReportOnSheet > flags what the new sheet lost, labels it from the archive, keeps the rest rebase of a report on a sheet ported cargo report_rules::rebase_flags_what_the_new_sheet_lost_labels_it_from_the_archive_keeps_the_rest - report_rules.rs:490-527; the TS re-parse of the output by ReportSchema is not repeated
|
||||
packages/domain/tests/report.rebase.test.ts rebaseReportOnSheet > fills no label without an archived snapshot rebase of a report on a sheet ported cargo report_rules::rebase_fills_no_label_without_an_archived_snapshot - report_rules.rs:533-537
|
||||
packages/domain/tests/report.rebase.test.ts rebaseReportOnSheet > counts nothing twice: a rebased report rebased again onto the same sheet is stable rebase of a report on a sheet ported cargo report_rules::rebase_counts_nothing_twice - report_rules.rs:546-550
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > FindingSchema rejects empty path and empty findingZoneId Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:54-60
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > LateralSideSchema rejects both and empty Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:61-62
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > VertebraSchema rejects index 0 and non-integer index Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:63-65
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > ObservationSchema rejects an empty id Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:66-71
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > SeveritySchema accepts the three codes only Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:72-75
|
||||
packages/domain/tests/report.schema.test.ts report v3 leaf schemas > ReportZoneSchema rejects an empty annotationId Report v3 and v2 contract ported cargo report_rules::report_v3_leaf_schemas - report_rules.rs:76-82
|
||||
packages/domain/tests/report.schema.test.ts report v3 document and identity > ReportSchema validates nextAppointment variants Report v3 and v2 contract ported cargo report_rules::report_v3_document_and_identity - report_rules.rs:87-95
|
||||
packages/domain/tests/report.schema.test.ts report v3 document and identity > PractitionerSchema rejects an empty name Report v3 and v2 contract ported cargo report_rules::report_v3_document_and_identity - report_rules.rs:96
|
||||
packages/domain/tests/report.schema.test.ts report v3 document and identity > AnimalSchema rejects an empty speciesId Report v3 and v2 contract ported cargo report_rules::report_v3_document_and_identity - report_rules.rs:97
|
||||
packages/domain/tests/report.schema.test.ts report v3 permissive boundaries > strips unknown keys silently Report v3 and v2 contract ported cargo report_rules::report_v3_permissive_boundaries - report_rules.rs:102-103
|
||||
packages/domain/tests/report.schema.test.ts report v3 permissive boundaries > accepts a vertebra index above any region count (bounds are a sheet concern) Report v3 and v2 contract ported cargo report_rules::report_v3_permissive_boundaries - report_rules.rs:104
|
||||
packages/domain/tests/report.schema.test.ts report v3 permissive boundaries > accepts an unregistered speciesId Report v3 and v2 contract ported cargo report_rules::report_v3_permissive_boundaries - report_rules.rs:105-106
|
||||
packages/domain/tests/report.schema.test.ts report v3 permissive boundaries > accepts orphan findings citing a zone absent from zones (D5) Report v3 and v2 contract ported cargo report_rules::report_v3_permissive_boundaries - report_rules.rs:107-112
|
||||
packages/domain/tests/sheet-index.test.ts buildSheetIndex > keeps the source as given, typed as the caller passed it sheet index lookups ported cargo sheet_index::views_by_id_and_the_main_view - PARTIAL: main view, view-head detail, unknown view absent (sheet_index.rs:34-39); passthrough of caller fields (extra, ref) is a TS generic API detail, not ported
|
||||
packages/domain/tests/sheet-index.test.ts buildSheetIndex > looks up annotations, zones, regions and spine markers by id sheet index lookups ported cargo sheet_index::annotations_zones_regions_and_spine_markers_by_id - sheet_index.rs:47-68; hip kind 'point' checked as observable() only
|
||||
packages/domain/tests/sheet-index.test.ts buildSheetIndex > resolves finding paths and reports absent ones sheet index lookups ported cargo sheet_index::finding_paths_resolve_or_report_absence - sheet_index.rs:77-91
|
||||
packages/domain/tests/sheet-index.test.ts buildSheetIndex > names a nameless trigger after the view it opens sheet index lookups ported cargo sheet_index::a_nameless_trigger_is_named_after_the_view_it_opens ; cargo faunosteo_core::anatomy::layer::tests::an_unnamed_trigger_takes_the_opened_view_name_in_each_language - Tete/Head and hip en (sheet_index.rs:100-105)
|
||||
packages/domain/tests/sheet-index.test.ts buildSheetIndex > refuses a document without a main view sheet index lookups ported cargo sheet_index::a_document_without_a_main_view_cannot_be_indexed - Err(NoMainView) instead of the 'no main view' message (sheet_index.rs:113)
|
||||
packages/domain/tests/sheet-index.test.ts pickLabel / isObservable > falls back to the other locale and to the empty string sheet index lookups ported vitest apps/app/tests/unit/i18n.keys.test.ts > pickLocaleLabel > returns the active locale label ; vitest apps/app/tests/unit/i18n.keys.test.ts > pickLocaleLabel > falls back to the other language when empty ; vitest apps/app/tests/unit/i18n.keys.test.ts > pickLocaleLabel > returns the fallback when both are empty ; cargo faunosteo_core::anatomy::layer::tests::a_missing_language_falls_back_to_the_other - the app's pickLabel (apps/app/src/i18n/pickLocaleLabel.ts) has the same rule; the null-text wrapper path is covered only through undefined fr/en; domain pickLabel has no consumer left
|
||||
packages/domain/tests/sheet-index.test.ts pickLabel / isObservable > tells observable annotations from triggers sheet index lookups ported cargo sheet_index::annotations_zones_regions_and_spine_markers_by_id ; cargo sheet_index::a_nameless_trigger_is_named_after_the_view_it_opens - observable() Some for hip (sheet_index.rs:47), None for head-trigger (sheet_index.rs:106); isObservable(undefined) is TS-only
|
||||
|
Can't render this file because it contains an unexpected character in line 12 and column 108.
|
@@ -26,7 +26,6 @@
|
||||
"check:all": "bash scripts/check-all.sh",
|
||||
"report:compare": "bash scripts/report-compare.sh",
|
||||
"import:equine": "bash scripts/import-equine.sh",
|
||||
"import:equine:legacy": "pnpm --filter @faunosteo/anatomy import:equine",
|
||||
"r5:import-equine": "bash scripts/import-equine.sh",
|
||||
"supabase": "bash scripts/supabase.sh",
|
||||
"db:start": "bash scripts/supabase.sh start",
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
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: '^_' },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"name": "@faunosteo/anatomy",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Faunosteo anatomy tooling: deterministic legacy importer, curation pipeline (changeset \u2192 draft, report migration map) and the pure annotation-layer renderer shared with the application",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./render": "./src/render/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",
|
||||
"import:equine": "tsx src/cli/import-equine.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@faunosteo/domain": "workspace:*",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.19.41",
|
||||
"@xmldom/xmldom": "^0.9.8",
|
||||
"eslint": "^9.17.0",
|
||||
"globals": "^15.14.0",
|
||||
"prettier": "^3.4.2",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.7.2",
|
||||
"typescript-eslint": "^8.19.0",
|
||||
"vitest": "^3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* Generates the two GENERATED folders of the official equine sheet from
|
||||
* the legacy sources and the AUTHORED curation files:
|
||||
*
|
||||
* supabase/seed/anatomical-sheets/equine/legacy-import/ baseline
|
||||
* supabase/seed/anatomical-sheets/equine/draft/ working revision
|
||||
*
|
||||
* pnpm import:equine (from the repository root)
|
||||
*
|
||||
* Output is byte-identical across runs; files a run no longer produces are
|
||||
* removed from those two folders. Commit the result and review the reports.
|
||||
*/
|
||||
import { copyFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
buildEquineDraft,
|
||||
EQUINE_DRAFT_DIR,
|
||||
EQUINE_LEGACY_IMPORT_DIR,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
HEAD_VIEW_ID,
|
||||
importEquineLegacy,
|
||||
parseViewBox,
|
||||
readEquineCuration,
|
||||
readEquineSources,
|
||||
renderArtifacts,
|
||||
renderDraftArtifacts,
|
||||
type DraftResult,
|
||||
type ImportResult,
|
||||
} from '../index'
|
||||
|
||||
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
|
||||
/** File contents by path relative to a generated folder. */
|
||||
type FolderFiles = Record<string, string | { copyFrom: string }>
|
||||
|
||||
async function writeFolder(dir: string, files: FolderFiles): Promise<void> {
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
const path = join(dir, name)
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
if (typeof content === 'string') await writeFile(path, content, 'utf8')
|
||||
else await copyFile(join(REPO_ROOT, content.copyFrom), path)
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes what this run did not produce, inside the folder only. */
|
||||
async function removeStale(dir: string, files: FolderFiles): Promise<void> {
|
||||
const entries = await readdir(dir, { recursive: true, withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue
|
||||
const path = join(entry.parentPath, entry.name)
|
||||
const name = path.slice(dir.length + 1)
|
||||
if (!(name in files)) await rm(path)
|
||||
}
|
||||
}
|
||||
|
||||
async function generate(folder: string, files: FolderFiles): Promise<void> {
|
||||
const dir = join(REPO_ROOT, folder)
|
||||
await writeFolder(dir, files)
|
||||
await removeStale(dir, files)
|
||||
}
|
||||
|
||||
function legacyAssets(): FolderFiles {
|
||||
const files: FolderFiles = {}
|
||||
for (const source of [
|
||||
EQUINE_SOURCE_PATHS.mainSvg,
|
||||
EQUINE_SOURCE_PATHS.headSvg,
|
||||
]) {
|
||||
files[`assets/${source.slice(source.lastIndexOf('/') + 1)}`] = {
|
||||
copyFrom: source,
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
function legacySummary(result: ImportResult): string {
|
||||
const errors = result.issues.filter((i) => i.severity === 'error').length
|
||||
return (
|
||||
`${EQUINE_LEGACY_IMPORT_DIR}: ${result.stats.annotations} annotations, ` +
|
||||
`${result.stats.nodes} nodes, ${result.anomalies.length} anomalies, ` +
|
||||
`${errors} integrity errors, ${result.issues.length - errors} warnings`
|
||||
)
|
||||
}
|
||||
|
||||
function draftSummary(draft: DraftResult): string {
|
||||
const changes = draft.changes.length
|
||||
return (
|
||||
`${EQUINE_DRAFT_DIR}: ${changes} changes (CHG-000 included), ` +
|
||||
`${draft.records.length} records, ${draft.statsAfter.nodes} nodes, ` +
|
||||
`${draft.assets.length} asset, 0 integrity errors, ${draft.issues.length} warnings`
|
||||
)
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const input = await readEquineSources(REPO_ROOT)
|
||||
const result = importEquineLegacy(input)
|
||||
const curation = await readEquineCuration(REPO_ROOT)
|
||||
const draft = buildEquineDraft({
|
||||
importResult: result,
|
||||
legacyMainSvgBytes: input.mainSvg.bytes,
|
||||
headViewBox: parseViewBox(result.viewBoxes[HEAD_VIEW_ID] ?? null),
|
||||
...curation,
|
||||
})
|
||||
await generate(EQUINE_LEGACY_IMPORT_DIR, {
|
||||
...(await renderArtifacts(result)),
|
||||
...legacyAssets(),
|
||||
})
|
||||
await generate(EQUINE_DRAFT_DIR, {
|
||||
...(await renderDraftArtifacts(draft, result.anomalies)),
|
||||
[`assets/${draft.assets[0]!.file}`]: draft.cleanedSvg,
|
||||
})
|
||||
console.log(legacySummary(result))
|
||||
console.log(draftSummary(draft))
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,26 +0,0 @@
|
||||
import { DOMParser, XMLSerializer } from '@xmldom/xmldom'
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import { composeViewSvg } from '../render/compose'
|
||||
|
||||
/**
|
||||
* The drawing of one view exactly as the application renders it: the
|
||||
* cleaned asset framed on the view's box plus the annotation layer the app
|
||||
* generates from the document. Written under draft/review/app-<view>.svg
|
||||
* so the markers and the framing can be compared with the legacy files
|
||||
* before and after a change, outside the browser. Parse and serialise
|
||||
* here; the composition itself is the shared `composeViewSvg`.
|
||||
*/
|
||||
|
||||
export interface AppReviewInput {
|
||||
cleanedSvg: string
|
||||
document: AnatomicalSheetDocumentInput
|
||||
viewId: string
|
||||
}
|
||||
|
||||
export function renderAppReviewDrawing(input: AppReviewInput): string {
|
||||
const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
|
||||
composeViewSvg({ root, document: input.document, viewId: input.viewId })
|
||||
return new XMLSerializer().serializeToString(doc)
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
validateSheetDocument,
|
||||
type AnatomicalSheetDocumentInput,
|
||||
type Reference,
|
||||
type SheetIssue,
|
||||
} from '@faunosteo/domain'
|
||||
import { applyOp, assertDeclared } from './ops'
|
||||
import {
|
||||
changeSummary,
|
||||
needsConfirmation,
|
||||
type Change,
|
||||
type ChangeSummary,
|
||||
type Changeset,
|
||||
} from './schema'
|
||||
import { allFindings, topCollection, type Item } from './targets'
|
||||
import type { ChangeRecord, CurationResult } from './types'
|
||||
|
||||
/**
|
||||
* Applies a changeset on a baseline document, deterministically and with a
|
||||
* record per elementary edit. The references file replaces the document
|
||||
* registry first (it is the source of truth). Any op that cannot apply
|
||||
* exactly as written, and any integrity error left at the end, throws:
|
||||
* a curated document is never produced from a partially applied changeset.
|
||||
*
|
||||
* Review rule: a level B or C change never leaves what it touched
|
||||
* (findings, finding categories, annotations: every item a set, add, cite,
|
||||
* rename or move resolved to, whole added subtrees and subtree scopes
|
||||
* included) as inherited or reviewed. After its ops, the applier sets
|
||||
* `review_status = 'to_confirm'` on each one and records that edit under the
|
||||
* same change id. An explicit 'reviewed' in such a change throws. Level A
|
||||
* is untouched by the rule.
|
||||
*/
|
||||
|
||||
/** Findings and annotations of the document, by item, with their target. */
|
||||
function reviewable(doc: Item): Map<Item, string> {
|
||||
const map = new Map<Item, string>()
|
||||
for (const { item, target } of allFindings(doc)) map.set(item, target)
|
||||
for (const item of topCollection(doc, 'annotation')) {
|
||||
map.set(item, `annotation:${String(item.id)}`)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/** Marks every touched item still in the document 'to_confirm'. */
|
||||
function markToConfirm(
|
||||
doc: Item,
|
||||
change: ChangeSummary,
|
||||
touched: readonly Item[],
|
||||
records: ChangeRecord[],
|
||||
) {
|
||||
const targets = reviewable(doc)
|
||||
for (const item of new Set(touched)) {
|
||||
const target = targets.get(item)
|
||||
if (target === undefined || item.review_status === 'to_confirm') continue
|
||||
const before = item.review_status ?? 'inherited'
|
||||
item.review_status = 'to_confirm'
|
||||
const op = {
|
||||
op: 'set',
|
||||
target,
|
||||
field: 'review_status',
|
||||
value: 'to_confirm',
|
||||
} as const
|
||||
records.push({
|
||||
change,
|
||||
op,
|
||||
target,
|
||||
field: 'review_status',
|
||||
before,
|
||||
after: 'to_confirm',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function applyChange(doc: Item, change: Change, records: ChangeRecord[]) {
|
||||
const summarised = changeSummary(change)
|
||||
try {
|
||||
assertDeclared(doc, change.reference_ids)
|
||||
} catch (error) {
|
||||
throw new Error(`${change.id}: ${(error as Error).message}`)
|
||||
}
|
||||
const touched: Item[] = []
|
||||
change.ops.forEach((op, index) => {
|
||||
try {
|
||||
applyOp({ doc, change: summarised, op, records, touched })
|
||||
} catch (error) {
|
||||
throw new Error(`${change.id} op ${index}: ${(error as Error).message}`)
|
||||
}
|
||||
})
|
||||
if (needsConfirmation(change.level)) {
|
||||
markToConfirm(doc, summarised, touched, records)
|
||||
}
|
||||
}
|
||||
|
||||
function describe(issues: readonly { path: string; message: string }[]) {
|
||||
return issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape (Zod) then integrity check of a curated document. Throws on any
|
||||
* shape issue or integrity error; returns the warnings, which are allowed.
|
||||
*/
|
||||
export function curatedIssues(doc: AnatomicalSheetDocumentInput): SheetIssue[] {
|
||||
const parsed = AnatomicalSheetDocumentSchema.safeParse(doc)
|
||||
if (!parsed.success) {
|
||||
const issues = parsed.error.issues.map((issue) => ({
|
||||
path: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
}))
|
||||
throw new Error(`curated document is not shape-valid: ${describe(issues)}`)
|
||||
}
|
||||
const issues = validateSheetDocument(parsed.data)
|
||||
const errors = issues.filter((issue) => issue.severity === 'error')
|
||||
if (errors.length > 0) {
|
||||
throw new Error(
|
||||
`curated document has integrity errors: ${describe(errors)}`,
|
||||
)
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
export function applyChangeset(
|
||||
baseline: AnatomicalSheetDocumentInput,
|
||||
references: readonly Reference[],
|
||||
changeset: Changeset,
|
||||
): CurationResult {
|
||||
const doc = structuredClone(baseline) as unknown as Item
|
||||
doc.references = structuredClone(references)
|
||||
const records: ChangeRecord[] = []
|
||||
for (const change of changeset.changes) applyChange(doc, change, records)
|
||||
const document = doc as unknown as AnatomicalSheetDocumentInput
|
||||
curatedIssues(document)
|
||||
return { document, records }
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
|
||||
import type { ViewBox } from '@faunosteo/domain'
|
||||
import { assetIdFromSha256, sha256Hex } from '../legacy/ids'
|
||||
import type { AssetRecord } from '../legacy/types'
|
||||
|
||||
/**
|
||||
* The curated sheet draws one clean anatomy: the legacy annotation layer
|
||||
* (hitboxes, visual markers, the head detail-zone) now lives in the
|
||||
* document as data, so every element carrying data-anno-id leaves the
|
||||
* drawing. Everything else is serialised back untouched (xmldom keeps the
|
||||
* declaration, attribute order and whitespace).
|
||||
*/
|
||||
|
||||
export const CLEANED_ASSET_FILE = 'horse.svg'
|
||||
|
||||
/** Sizing the legacy app inlined on the root; the app sizes the drawing now. */
|
||||
const LEGACY_ROOT_STYLE = 'width: 100%; height: auto; max-width: 100%;'
|
||||
|
||||
function annotatedElements(root: Element): Element[] {
|
||||
const all = Array.from(root.getElementsByTagName('*'))
|
||||
return all.filter((element) => element.hasAttribute('data-anno-id'))
|
||||
}
|
||||
|
||||
export function stripLegacyAnnotations(svgText: string): string {
|
||||
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
|
||||
for (const element of annotatedElements(root)) {
|
||||
element.parentNode?.removeChild(element)
|
||||
}
|
||||
if (root.getAttribute('style') === LEGACY_ROOT_STYLE) {
|
||||
root.removeAttribute('style')
|
||||
}
|
||||
return new XMLSerializer().serializeToString(doc)
|
||||
}
|
||||
|
||||
/** Manifest entry of the cleaned drawing; id derived from its sha256. */
|
||||
export function cleanedAsset(bytes: Uint8Array): AssetRecord {
|
||||
const sha256 = sha256Hex(bytes)
|
||||
return {
|
||||
file: CLEANED_ASSET_FILE,
|
||||
sha256,
|
||||
byte_size: bytes.byteLength,
|
||||
svg_asset_id: assetIdFromSha256(sha256),
|
||||
}
|
||||
}
|
||||
|
||||
/** SVG viewBox attribute ("minX minY width height") → document view_box. */
|
||||
export function parseViewBox(raw: string | null): ViewBox {
|
||||
const numbers = (raw ?? '')
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const [min_x, min_y, width, height] = numbers
|
||||
if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n))) {
|
||||
throw new Error(`invalid viewBox "${raw}"`)
|
||||
}
|
||||
return { min_x: min_x!, min_y: min_y!, width: width!, height: height! }
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { code, table } from '../markdown'
|
||||
import { KIND_LABELS, LEVEL_LABELS, LEVELS } from './labels'
|
||||
import { needsConfirmation, type ChangeLevel } from './schema'
|
||||
import { statRows, type DocumentStats } from './stats'
|
||||
import { isItem } from './targets'
|
||||
import type { MigrationMapStats } from './migration-map'
|
||||
import type { ChangeRecord } from './types'
|
||||
|
||||
/**
|
||||
* French CHANGELOG of the working revision: volumes before / after, then
|
||||
* one table per change level with every elementary edit. Pure formatting
|
||||
* of the records, deterministic (no dates).
|
||||
*/
|
||||
|
||||
const MAX_VALUE_LENGTH = 120
|
||||
|
||||
function isLabel(value: unknown): value is Record<string, string> {
|
||||
if (!isItem(value)) return false
|
||||
const entries = Object.entries(value)
|
||||
return (
|
||||
entries.length > 0 &&
|
||||
entries.every(
|
||||
([k, v]) => (k === 'fr' || k === 'en') && typeof v === 'string',
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** Compact text of a recorded value: labels as text, objects as JSON. */
|
||||
export function compactValue(value: unknown): string {
|
||||
let text: string
|
||||
if (typeof value === 'string') text = value
|
||||
else if (isLabel(value)) text = Object.values(value).join(' / ')
|
||||
else text = JSON.stringify(value)
|
||||
if (text.length <= MAX_VALUE_LENGTH) return text
|
||||
return `${text.slice(0, MAX_VALUE_LENGTH - 1)}…`
|
||||
}
|
||||
|
||||
export function recordSubject(record: ChangeRecord): string {
|
||||
return record.field === null
|
||||
? record.target
|
||||
: `${record.target}.${record.field}`
|
||||
}
|
||||
|
||||
function recordRow(record: ChangeRecord): string[] {
|
||||
const { change } = record
|
||||
return [
|
||||
`${code(change.id)} ${change.title.fr}`,
|
||||
code(recordSubject(record)),
|
||||
compactValue(record.before),
|
||||
compactValue(record.after),
|
||||
KIND_LABELS[change.kind],
|
||||
change.rationale,
|
||||
change.reference_ids.map(code).join(', ') || '-',
|
||||
needsConfirmation(change.level) ? 'oui' : 'non',
|
||||
]
|
||||
}
|
||||
|
||||
function levelSection(level: ChangeLevel, records: readonly ChangeRecord[]) {
|
||||
const rows = records.filter((r) => r.change.level === level).map(recordRow)
|
||||
const head = [
|
||||
'Changement',
|
||||
'Objet',
|
||||
'Avant',
|
||||
'Après',
|
||||
'Nature',
|
||||
'Justification',
|
||||
'Références',
|
||||
'Confirmation requise',
|
||||
]
|
||||
const body =
|
||||
rows.length === 0 ? 'Aucun changement de ce niveau.' : table(head, rows)
|
||||
return `## ${LEVEL_LABELS[level]}\n\n${body}`
|
||||
}
|
||||
|
||||
function comparison(before: DocumentStats, after: DocumentStats): string {
|
||||
const afterRows = new Map(statRows(after))
|
||||
const rows = statRows(before).map(([label, value]) => [
|
||||
label,
|
||||
value,
|
||||
afterRows.get(label) ?? 0,
|
||||
])
|
||||
return `## Comparaison quantitative\n\n${table(['Indicateur', 'Avant', 'Après'], rows)}`
|
||||
}
|
||||
|
||||
function intro(): string {
|
||||
return [
|
||||
'# Journal des changements : révision de travail',
|
||||
'',
|
||||
'Généré par `pnpm import:equine` : import historique (`legacy-import/`) ' +
|
||||
'puis changements rédigés (`curation/changes.json`). Ne pas modifier ' +
|
||||
'à la main : relancer la commande.',
|
||||
'',
|
||||
'Niveaux : A = erreur démontrée, B = amélioration étayée, C = point ' +
|
||||
'incertain. Les niveaux B et C demandent une confirmation professionnelle.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** Fate of the legacy finding nodes a Report v2 may cite (report-migration-map.json). */
|
||||
function migration(stats: MigrationMapStats): string {
|
||||
const rows = [
|
||||
['Nœuds du catalogue historique', String(stats.nodes)],
|
||||
['Chemin identique', String(stats.identical)],
|
||||
[
|
||||
'Chemin renommé ou déplacé (suivi des renommages)',
|
||||
String(stats.remapped),
|
||||
],
|
||||
[
|
||||
'Relogé sous une autre catégorie (correspondance unique)',
|
||||
String(stats.rehomed),
|
||||
],
|
||||
[
|
||||
'Retiré : le bilan garde le constat avec ses libellés figés',
|
||||
String(stats.removed),
|
||||
],
|
||||
]
|
||||
return `## Migration des bilans v2\n\n${table(['Nœuds', 'Nombre'], rows)}`
|
||||
}
|
||||
|
||||
export function renderChangelog(
|
||||
result: { records: readonly ChangeRecord[] },
|
||||
before: DocumentStats,
|
||||
after: DocumentStats,
|
||||
migrationStats: MigrationMapStats,
|
||||
): string {
|
||||
const sections = [
|
||||
intro(),
|
||||
comparison(before, after),
|
||||
migration(migrationStats),
|
||||
...LEVELS.map((level) => levelSection(level, result.records)),
|
||||
]
|
||||
return `${sections.join('\n\n')}\n`
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { isItem, type Item, type ParsedTarget } from './targets'
|
||||
|
||||
/**
|
||||
* Fields a `set` may write, per kind of item. Ids are left out on purpose:
|
||||
* an id changes through `rename`, which also rewrites every reference to
|
||||
* it. Unlisted field → the op fails instead of writing a stray key.
|
||||
*/
|
||||
|
||||
const SETTABLE: Record<string, readonly string[]> = {
|
||||
document: ['name', 'description', 'scope_disclaimer', 'attribution'],
|
||||
region: ['name', 'count', 'count_range'],
|
||||
reference: ['type', 'citation', 'url', 'doi'],
|
||||
category: ['name', 'color'],
|
||||
view: ['name', 'svg_asset_id', 'view_box', 'parent_view_id'],
|
||||
annotation: [
|
||||
'name',
|
||||
'kind',
|
||||
'view_id',
|
||||
'category_id',
|
||||
'laterality',
|
||||
'geometry',
|
||||
'review_status',
|
||||
'finding_zone_id',
|
||||
'vertebral_region_code',
|
||||
'opens_view_id',
|
||||
'color',
|
||||
],
|
||||
zone: ['name'],
|
||||
finding_category: [
|
||||
'kind',
|
||||
'name',
|
||||
'description',
|
||||
'reference_ids',
|
||||
'review_status',
|
||||
],
|
||||
finding_node: [
|
||||
'name',
|
||||
'description',
|
||||
'requires_vet_referral',
|
||||
'reference_ids',
|
||||
'review_status',
|
||||
],
|
||||
}
|
||||
|
||||
export function splitField(field: string): string[] {
|
||||
const path = field.split('.')
|
||||
if (path.includes('')) throw new Error(`malformed field "${field}"`)
|
||||
return path
|
||||
}
|
||||
|
||||
/** Item kind of the settable table; a finding is a category or a node. */
|
||||
export function fieldKind(target: ParsedTarget, isCategory?: boolean): string {
|
||||
if (target.kind !== 'finding') return target.kind
|
||||
const category = isCategory ?? target.ids.length === 2
|
||||
return category ? 'finding_category' : 'finding_node'
|
||||
}
|
||||
|
||||
export function isSettable(kind: string, field: string): boolean {
|
||||
return SETTABLE[kind]?.includes(splitField(field)[0]!) ?? false
|
||||
}
|
||||
|
||||
export function readField(item: Item, field: string): unknown {
|
||||
let value: unknown = item
|
||||
for (const key of splitField(field)) {
|
||||
if (!isItem(value)) return undefined
|
||||
value = value[key]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** Writes a deep copy of value; missing intermediate objects are created. */
|
||||
export function writeField(item: Item, field: string, value: unknown): void {
|
||||
const path = splitField(field)
|
||||
let holder = item
|
||||
for (const key of path.slice(0, -1)) {
|
||||
if (!isItem(holder[key])) holder[key] = {}
|
||||
holder = holder[key] as Item
|
||||
}
|
||||
holder[path[path.length - 1]!] = structuredClone(value)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
export { applyChangeset, curatedIssues } from './apply'
|
||||
export {
|
||||
CLEANED_ASSET_FILE,
|
||||
cleanedAsset,
|
||||
parseViewBox,
|
||||
stripLegacyAnnotations,
|
||||
} from './assets'
|
||||
export { compactValue, renderChangelog } from './changelog'
|
||||
export {
|
||||
buildEquineDraft,
|
||||
DRAFT_SEED_SQL_FILE,
|
||||
MIGRATION_MAP_FILE,
|
||||
SHEET_REF_FILE,
|
||||
renderDraftArtifacts,
|
||||
type DraftInput,
|
||||
type DraftResult,
|
||||
} from './pipeline'
|
||||
export {
|
||||
buildReportMigrationMap,
|
||||
type MigrationMapInput,
|
||||
type MigrationMapStats,
|
||||
} from './migration-map'
|
||||
export { renderAppReviewDrawing, type AppReviewInput } from './app-review'
|
||||
export {
|
||||
REVIEW_OVERLAY_DIR,
|
||||
overlayMarkers,
|
||||
renderReviewOverlay,
|
||||
type OverlayInput,
|
||||
} from './overlay'
|
||||
export { renderReviewReport, type ReviewReportInput } from './review-report'
|
||||
export {
|
||||
ASSET_CHANGE_ID,
|
||||
ChangeSchema,
|
||||
ChangesetSchema,
|
||||
OpSchema,
|
||||
ReferencesFileSchema,
|
||||
needsConfirmation,
|
||||
} from './schema'
|
||||
export type * from './schema'
|
||||
export {
|
||||
DOCUMENT_DOLLAR_TAG,
|
||||
DRAFT_CHANGE_NOTE,
|
||||
renderDraftSeedSql,
|
||||
type DraftSeedParams,
|
||||
} from './seed'
|
||||
export {
|
||||
CURATION_FILES,
|
||||
readEquineCuration,
|
||||
type CurationInput,
|
||||
} from './sources'
|
||||
export { documentStats, statRows, type DocumentStats } from './stats'
|
||||
export { parseTarget, formatTarget } from './targets'
|
||||
export type { ChangeRecord, CurationResult } from './types'
|
||||
@@ -1,29 +0,0 @@
|
||||
import type { ChangeKind, ChangeLevel, ChangePriority } from './schema'
|
||||
|
||||
/** French labels shared by the CHANGELOG and the review report. */
|
||||
|
||||
export const KIND_LABELS: Record<ChangeKind, string> = {
|
||||
correction: 'Correction',
|
||||
terminology: 'Terminologie',
|
||||
translation: 'Traduction',
|
||||
restructure: 'Réorganisation',
|
||||
enrichment: 'Ajout',
|
||||
reference: 'Référence',
|
||||
geometry: 'Géométrie',
|
||||
removal: 'Suppression',
|
||||
technical: 'Technique',
|
||||
}
|
||||
|
||||
export const LEVEL_LABELS: Record<ChangeLevel, string> = {
|
||||
A: 'Niveau A : erreurs démontrées',
|
||||
B: 'Niveau B : améliorations étayées (confirmation requise)',
|
||||
C: 'Niveau C : points incertains (question au professionnel)',
|
||||
}
|
||||
|
||||
export const PRIORITY_LABELS: Record<ChangePriority, string> = {
|
||||
high: 'haute',
|
||||
medium: 'moyenne',
|
||||
low: 'basse',
|
||||
}
|
||||
|
||||
export const LEVELS: readonly ChangeLevel[] = ['A', 'B', 'C']
|
||||
@@ -1,178 +0,0 @@
|
||||
import type { ReportMigrationMap, SheetRef } from '@faunosteo/domain'
|
||||
import type { LegacyIdMap } from '../legacy/types'
|
||||
import { allFindings, topCollection, type Item } from './targets'
|
||||
import type { ChangeRecord } from './types'
|
||||
|
||||
/**
|
||||
* Report migration map: where every identifier a Report v2 may carry lands
|
||||
* in the curated draft. Annotations come from the legacy id map (then
|
||||
* follow annotation renames), finding paths from replaying the applier's
|
||||
* rename, move and remove records over every node of the legacy baseline.
|
||||
* A node removed with its category and re-added under another category at
|
||||
* the same relative place (the sphenoid restructure) is re-homed when the
|
||||
* match is unique; anything else stays null = "removed", and the report
|
||||
* keeps the finding with its snapshots.
|
||||
*/
|
||||
|
||||
const FINDING = 'finding:'
|
||||
|
||||
export interface MigrationMapInput {
|
||||
baseline: Item
|
||||
final: Item
|
||||
legacyIdMap: LegacyIdMap
|
||||
records: readonly ChangeRecord[]
|
||||
sheet: SheetRef
|
||||
mainViewId: string
|
||||
}
|
||||
|
||||
export interface MigrationMapStats {
|
||||
nodes: number
|
||||
identical: number
|
||||
remapped: number
|
||||
rehomed: number
|
||||
removed: number
|
||||
}
|
||||
|
||||
interface PathEntry {
|
||||
legacy: string
|
||||
current: string | null
|
||||
rehomed: boolean
|
||||
}
|
||||
|
||||
function strip(target: string): string {
|
||||
return target.slice(FINDING.length)
|
||||
}
|
||||
|
||||
function lastSegment(path: string): string {
|
||||
return path.slice(path.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
function withLastSegment(path: string, id: string): string {
|
||||
const cut = path.lastIndexOf('/')
|
||||
return cut < 0 ? id : `${path.slice(0, cut + 1)}${id}`
|
||||
}
|
||||
|
||||
function replacePrefix(entries: PathEntry[], from: string, to: string | null) {
|
||||
for (const entry of entries) {
|
||||
const current = entry.current
|
||||
if (current === null) continue
|
||||
if (current === from) entry.current = to
|
||||
else if (current.startsWith(`${from}/`)) {
|
||||
entry.current = to === null ? null : `${to}${current.slice(from.length)}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyRecord(
|
||||
entries: PathEntry[],
|
||||
ids: { annotations: Map<string, string>; views: Map<string, string> },
|
||||
record: ChangeRecord,
|
||||
) {
|
||||
const { op, target } = record
|
||||
if (op.op !== 'rename' && op.op !== 'remove' && op.op !== 'move') return
|
||||
if (target.startsWith(FINDING)) {
|
||||
const from = strip(target)
|
||||
if (op.op === 'rename')
|
||||
replacePrefix(entries, from, withLastSegment(from, op.id))
|
||||
if (op.op === 'remove') replacePrefix(entries, from, null)
|
||||
if (op.op === 'move')
|
||||
replacePrefix(entries, from, `${strip(op.to)}/${lastSegment(from)}`)
|
||||
return
|
||||
}
|
||||
const [kind, id] = target.split(':', 2) as [string, string]
|
||||
if (kind === 'zone') {
|
||||
for (const entry of entries) {
|
||||
if (entry.current?.startsWith(`${id}/`)) {
|
||||
entry.current =
|
||||
op.op === 'remove'
|
||||
? null
|
||||
: `${op.op === 'rename' ? op.id : id}${entry.current.slice(id.length)}`
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (op.op === 'rename' && (kind === 'annotation' || kind === 'view')) {
|
||||
const map = kind === 'annotation' ? ids.annotations : ids.views
|
||||
for (const [legacy, current] of map)
|
||||
if (current === id) map.set(legacy, op.id)
|
||||
}
|
||||
}
|
||||
|
||||
/** `zone/<any category>/<rest>` present exactly once in the final document. */
|
||||
function rehome(entry: PathEntry, finalPaths: ReadonlySet<string>): void {
|
||||
const [zone, , ...rest] = entry.legacy.split('/')
|
||||
if (rest.length === 0) return
|
||||
const tail = `/${rest.join('/')}`
|
||||
const matches = [...finalPaths].filter(
|
||||
(p) =>
|
||||
p.startsWith(`${zone}/`) &&
|
||||
p.endsWith(tail) &&
|
||||
p.split('/').length === rest.length + 2,
|
||||
)
|
||||
if (matches.length === 1) {
|
||||
entry.current = matches[0]!
|
||||
entry.rehomed = true
|
||||
}
|
||||
}
|
||||
|
||||
function annotationNames(doc: Item): Map<string, { fr: string; en: string }> {
|
||||
const names = new Map<string, { fr: string; en: string }>()
|
||||
for (const a of topCollection(doc, 'annotation')) {
|
||||
const name = a.name as { fr?: string; en?: string } | null
|
||||
names.set(String(a.id), { fr: name?.fr ?? '', en: name?.en ?? '' })
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
export function buildReportMigrationMap(input: MigrationMapInput): {
|
||||
map: ReportMigrationMap
|
||||
stats: MigrationMapStats
|
||||
} {
|
||||
const entries: PathEntry[] = allFindings(input.baseline).map((e) => ({
|
||||
legacy: strip(e.target),
|
||||
current: strip(e.target),
|
||||
rehomed: false,
|
||||
}))
|
||||
const ids = {
|
||||
annotations: new Map(Object.entries(input.legacyIdMap.annotations)),
|
||||
views: new Map(Object.entries(input.legacyIdMap.views)),
|
||||
}
|
||||
for (const record of input.records) applyRecord(entries, ids, record)
|
||||
const finalPaths = new Set(
|
||||
allFindings(input.final).map((e) => strip(e.target)),
|
||||
)
|
||||
for (const entry of entries) {
|
||||
if (entry.current !== null && !finalPaths.has(entry.current))
|
||||
entry.current = null
|
||||
if (entry.current === null) rehome(entry, finalPaths)
|
||||
}
|
||||
const legacyNames = annotationNames(input.baseline)
|
||||
const importIds = new Map(Object.entries(input.legacyIdMap.annotations))
|
||||
const annotations: ReportMigrationMap['annotations'] = {}
|
||||
for (const [legacy, finalId] of ids.annotations) {
|
||||
annotations[legacy] = {
|
||||
id: finalId,
|
||||
name: legacyNames.get(importIds.get(legacy)!) ?? { fr: '', en: '' },
|
||||
}
|
||||
}
|
||||
const finding_paths: Record<string, string | null> = {}
|
||||
for (const entry of entries) finding_paths[entry.legacy] = entry.current
|
||||
const map: ReportMigrationMap = {
|
||||
schema_version: 1,
|
||||
sheet: input.sheet,
|
||||
main_view_id: input.mainViewId,
|
||||
views: Object.fromEntries(ids.views),
|
||||
annotations,
|
||||
finding_paths,
|
||||
}
|
||||
const stats: MigrationMapStats = {
|
||||
nodes: entries.length,
|
||||
identical: entries.filter((e) => e.current === e.legacy).length,
|
||||
remapped: entries.filter(
|
||||
(e) => e.current !== null && e.current !== e.legacy && !e.rehomed,
|
||||
).length,
|
||||
rehomed: entries.filter((e) => e.rehomed).length,
|
||||
removed: entries.filter((e) => e.current === null).length,
|
||||
}
|
||||
return { map, stats }
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import { fieldKind, isSettable, readField, writeField } from './fields'
|
||||
import { propagateRename } from './rename'
|
||||
import { needsConfirmation, type Op, type Position } from './schema'
|
||||
import {
|
||||
childList,
|
||||
childPrefix,
|
||||
findingScope,
|
||||
isItem,
|
||||
keyField,
|
||||
locate,
|
||||
topCollection,
|
||||
type Item,
|
||||
type Located,
|
||||
type TargetKind,
|
||||
} from './targets'
|
||||
import { record, type OpContext } from './types'
|
||||
|
||||
/**
|
||||
* The six op kinds of a change. Each one resolves its target, edits the
|
||||
* working document in place and records what it changed; anything it
|
||||
* cannot do exactly as written throws (the caller adds change id and op
|
||||
* index to the message).
|
||||
*/
|
||||
|
||||
type OpOf<K extends Op['op']> = Extract<Op, { op: K }>
|
||||
|
||||
const COLLECTION_KIND: Record<string, TargetKind> = {
|
||||
references: 'reference',
|
||||
categories: 'category',
|
||||
views: 'view',
|
||||
annotations: 'annotation',
|
||||
finding_zones: 'zone',
|
||||
regions: 'region',
|
||||
}
|
||||
|
||||
function assertFree(list: Item[], key: string, id: string, self?: Item) {
|
||||
if (list.some((entry) => entry !== self && entry[key] === id)) {
|
||||
throw new Error(`"${id}" already exists among its siblings`)
|
||||
}
|
||||
}
|
||||
|
||||
function insertionIndex(list: Item[], key: string, position?: Position) {
|
||||
if (position === undefined) return list.length
|
||||
if (typeof position === 'number') {
|
||||
if (position > list.length)
|
||||
throw new Error(`position ${position} out of range`)
|
||||
return position
|
||||
}
|
||||
const anchor = 'after' in position ? position.after : position.before
|
||||
const index = list.findIndex((entry) => entry[key] === anchor)
|
||||
if (index < 0) throw new Error(`unknown sibling "${anchor}"`)
|
||||
return 'after' in position ? index + 1 : index
|
||||
}
|
||||
|
||||
function unknownField(op: OpOf<'set'>): Error {
|
||||
return new Error(`unknown field "${op.field}" on "${op.target}"`)
|
||||
}
|
||||
|
||||
/** A B or C change leaves findings to the professional: no 'reviewed'. */
|
||||
function assertNotReviewed(ctx: OpContext, op: OpOf<'set'>) {
|
||||
if (op.field !== 'review_status' || op.value !== 'reviewed') return
|
||||
if (needsConfirmation(ctx.change.level)) {
|
||||
throw new Error(
|
||||
`level ${ctx.change.level} cannot set ` +
|
||||
`"${op.target}" review_status to "reviewed"`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function setSelf(ctx: OpContext, located: Located, op: OpOf<'set'>) {
|
||||
if (!isSettable(fieldKind(located.target), op.field)) throw unknownField(op)
|
||||
ctx.touched.push(located.item)
|
||||
const before = readField(located.item, op.field)
|
||||
writeField(located.item, op.field, op.value)
|
||||
record(ctx, op.target, op.field, { before, after: op.value })
|
||||
}
|
||||
|
||||
/** Target and descendants that carry the field; unchanged items are skipped. */
|
||||
function setSubtree(ctx: OpContext, located: Located, op: OpOf<'set'>) {
|
||||
if (located.target.kind !== 'finding') {
|
||||
throw new Error(`scope subtree needs a finding target, got "${op.target}"`)
|
||||
}
|
||||
const entries = findingScope(located, 'subtree').filter((entry) =>
|
||||
isSettable(fieldKind(located.target, entry.isCategory), op.field),
|
||||
)
|
||||
if (entries.length === 0) throw unknownField(op)
|
||||
ctx.touched.push(...entries.map((entry) => entry.item))
|
||||
for (const { target, item } of entries) {
|
||||
const before = readField(item, op.field)
|
||||
if (isDeepStrictEqual(before, op.value)) continue
|
||||
writeField(item, op.field, op.value)
|
||||
record(ctx, target, op.field, { before, after: op.value })
|
||||
}
|
||||
}
|
||||
|
||||
function applySet(ctx: OpContext, op: OpOf<'set'>): void {
|
||||
assertNotReviewed(ctx, op)
|
||||
const located = locate(ctx.doc, op.target)
|
||||
if ((op.scope ?? 'self') === 'self') setSelf(ctx, located, op)
|
||||
else setSubtree(ctx, located, op)
|
||||
}
|
||||
|
||||
function applyRename(ctx: OpContext, op: OpOf<'rename'>): void {
|
||||
const { target, siblings, item } = locate(ctx.doc, op.target)
|
||||
if (siblings === null) throw new Error('the document has no id to rename')
|
||||
const key = keyField(target.kind)
|
||||
assertFree(siblings, key, op.id, item)
|
||||
const before = structuredClone(item)
|
||||
const from = String(item[key])
|
||||
item[key] = op.id
|
||||
ctx.touched.push(item)
|
||||
record(ctx, op.target, null, { before, after: item })
|
||||
propagateRename(ctx, { kind: target.kind, from, to: op.id })
|
||||
}
|
||||
|
||||
interface Destination {
|
||||
list: Item[]
|
||||
key: 'id' | 'code'
|
||||
prefix: string
|
||||
}
|
||||
|
||||
function addDestination(ctx: OpContext, op: OpOf<'add'>): Destination {
|
||||
const parent = locate(ctx.doc, op.target)
|
||||
if (parent.target.kind !== 'document') {
|
||||
if (op.field)
|
||||
throw new Error(`field "${op.field}" is only valid on document`)
|
||||
return { list: childList(parent), key: 'id', prefix: childPrefix(parent) }
|
||||
}
|
||||
if (!op.field) throw new Error('add on document needs a field')
|
||||
const kind = COLLECTION_KIND[op.field]!
|
||||
const list = topCollection(ctx.doc, kind)
|
||||
return { list, key: keyField(kind), prefix: `${kind}:` }
|
||||
}
|
||||
|
||||
function descendants(item: Item): Item[] {
|
||||
const children = Array.isArray(item.children) ? (item.children as Item[]) : []
|
||||
return children.flatMap((child) => [child, ...descendants(child)])
|
||||
}
|
||||
|
||||
function applyAdd(ctx: OpContext, op: OpOf<'add'>): void {
|
||||
if (!isItem(op.value)) throw new Error('add needs an object value')
|
||||
const dest = addDestination(ctx, op)
|
||||
const id = op.value[dest.key]
|
||||
if (typeof id !== 'string') {
|
||||
throw new Error(`the added item needs a string "${dest.key}"`)
|
||||
}
|
||||
assertFree(dest.list, dest.key, id)
|
||||
const index = insertionIndex(dest.list, dest.key, op.position)
|
||||
const added = structuredClone(op.value)
|
||||
dest.list.splice(index, 0, added)
|
||||
ctx.touched.push(added, ...descendants(added))
|
||||
record(ctx, dest.prefix + id, null, { before: null, after: op.value })
|
||||
}
|
||||
|
||||
function applyRemove(ctx: OpContext, op: OpOf<'remove'>): void {
|
||||
const { siblings, item } = locate(ctx.doc, op.target)
|
||||
if (siblings === null) throw new Error('the document cannot be removed')
|
||||
siblings.splice(siblings.indexOf(item), 1)
|
||||
record(ctx, op.target, null, { before: item, after: null })
|
||||
}
|
||||
|
||||
/** `after` of a move record is the new target path of the item. */
|
||||
function applyMove(ctx: OpContext, op: OpOf<'move'>): void {
|
||||
const source = locate(ctx.doc, op.target)
|
||||
if (source.target.kind !== 'finding') {
|
||||
throw new Error(`only findings move, got "${op.target}"`)
|
||||
}
|
||||
if (op.to === op.target || op.to.startsWith(`${op.target}/`)) {
|
||||
throw new Error(`cannot move "${op.target}" into itself`)
|
||||
}
|
||||
const parent = locate(ctx.doc, op.to)
|
||||
const list = childList(parent)
|
||||
const id = String(source.item.id)
|
||||
assertFree(list, 'id', id, source.item)
|
||||
source.siblings!.splice(source.siblings!.indexOf(source.item), 1)
|
||||
list.splice(insertionIndex(list, 'id', op.position), 0, source.item)
|
||||
ctx.touched.push(source.item)
|
||||
const after = childPrefix(parent) + id
|
||||
record(ctx, op.target, null, { before: source.item, after })
|
||||
}
|
||||
|
||||
/** Every cited id must be declared in the document references. */
|
||||
export function assertDeclared(doc: Item, ids: readonly string[]): void {
|
||||
const declared = new Set(topCollection(doc, 'reference').map((r) => r.id))
|
||||
const missing = ids.filter((id) => !declared.has(id))
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`undeclared reference(s): ${missing.join(', ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Appends citations in order, never twice on the same item. */
|
||||
function applyCite(ctx: OpContext, op: OpOf<'cite'>): void {
|
||||
assertDeclared(ctx.doc, op.reference_ids)
|
||||
const located = locate(ctx.doc, op.target)
|
||||
const scope = findingScope(located, op.scope ?? 'self')
|
||||
ctx.touched.push(...scope.map((entry) => entry.item))
|
||||
for (const { target, item } of scope) {
|
||||
const before = Array.isArray(item.reference_ids) ? item.reference_ids : []
|
||||
const added = [...new Set(op.reference_ids)].filter(
|
||||
(id) => !before.includes(id),
|
||||
)
|
||||
if (added.length === 0) continue
|
||||
item.reference_ids = [...before, ...added]
|
||||
record(ctx, target, 'reference_ids', { before, after: item.reference_ids })
|
||||
}
|
||||
}
|
||||
|
||||
export function applyOp(ctx: OpContext): void {
|
||||
const op = ctx.op
|
||||
switch (op.op) {
|
||||
case 'set':
|
||||
return applySet(ctx, op)
|
||||
case 'rename':
|
||||
return applyRename(ctx, op)
|
||||
case 'add':
|
||||
return applyAdd(ctx, op)
|
||||
case 'remove':
|
||||
return applyRemove(ctx, op)
|
||||
case 'move':
|
||||
return applyMove(ctx, op)
|
||||
case 'cite':
|
||||
return applyCite(ctx, op)
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
import {
|
||||
DOMParser,
|
||||
XMLSerializer,
|
||||
type Document,
|
||||
type Element,
|
||||
} from '@xmldom/xmldom'
|
||||
import type { AnatomicalSheetDocumentInput, Geometry } from '@faunosteo/domain'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
|
||||
/**
|
||||
* Before/after drawing of one view for the professional review: the
|
||||
* cleaned anatomy, the curated annotations as an SVG layer, and the
|
||||
* baseline position of every moved or removed annotation beside it
|
||||
* (dashed). Pure data, deterministic, opens in any browser.
|
||||
*/
|
||||
|
||||
export const REVIEW_OVERLAY_DIR = 'review'
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
const LAYER_ID = 'review-annotations'
|
||||
|
||||
type Doc = AnatomicalSheetDocumentInput
|
||||
type Annotation = Doc['annotations'][number]
|
||||
type Status = 'unchanged' | 'moved' | 'added' | 'removed'
|
||||
|
||||
const STYLE: Record<Status, Record<string, string>> = {
|
||||
unchanged: { stroke: '#1d4ed8', fill: '#1d4ed8', 'fill-opacity': '0.12' },
|
||||
moved: { stroke: '#15803d', fill: '#15803d', 'fill-opacity': '0.2' },
|
||||
added: { stroke: '#15803d', fill: '#15803d', 'fill-opacity': '0.2' },
|
||||
// fill-opacity rather than fill="none": some rasterizers drop unfilled shapes.
|
||||
removed: {
|
||||
stroke: '#b91c1c',
|
||||
fill: '#b91c1c',
|
||||
'fill-opacity': '0.04',
|
||||
'stroke-dasharray': '8 6',
|
||||
},
|
||||
}
|
||||
|
||||
interface Marker {
|
||||
id: string
|
||||
geometry: Geometry
|
||||
status: Status
|
||||
}
|
||||
|
||||
function withGeometry(annotations: readonly Annotation[], viewId: string) {
|
||||
return annotations.filter((a) => a.view_id === viewId && a.geometry !== null)
|
||||
}
|
||||
|
||||
/** Curated annotations with their status, then the baseline shapes they left. */
|
||||
export function overlayMarkers(
|
||||
before: Doc,
|
||||
after: Doc,
|
||||
viewId: string,
|
||||
): Marker[] {
|
||||
const previous = new Map(
|
||||
withGeometry(before.annotations, viewId).map((a) => [a.id, a.geometry!]),
|
||||
)
|
||||
const markers: Marker[] = []
|
||||
for (const a of withGeometry(after.annotations, viewId)) {
|
||||
const old = previous.get(a.id)
|
||||
const status: Status =
|
||||
old === undefined
|
||||
? 'added'
|
||||
: isDeepStrictEqual(old, a.geometry)
|
||||
? 'unchanged'
|
||||
: 'moved'
|
||||
markers.push({ id: a.id, geometry: a.geometry!, status })
|
||||
if (status === 'moved') {
|
||||
markers.push({ id: a.id, geometry: old!, status: 'removed' })
|
||||
}
|
||||
}
|
||||
const kept = new Set(after.annotations.map((a) => a.id))
|
||||
for (const [id, geometry] of previous) {
|
||||
if (!kept.has(id)) markers.push({ id, geometry, status: 'removed' })
|
||||
}
|
||||
return markers
|
||||
}
|
||||
|
||||
function shapeElement(doc: Document, geometry: Geometry): Element {
|
||||
switch (geometry.type) {
|
||||
case 'circle': {
|
||||
const el = doc.createElementNS(SVG_NS, 'circle')
|
||||
el.setAttribute('cx', String(geometry.cx))
|
||||
el.setAttribute('cy', String(geometry.cy))
|
||||
el.setAttribute('r', String(geometry.r))
|
||||
return el
|
||||
}
|
||||
case 'polygon': {
|
||||
const el = doc.createElementNS(SVG_NS, 'polygon')
|
||||
el.setAttribute(
|
||||
'points',
|
||||
geometry.points.map(([x, y]) => `${x},${y}`).join(' '),
|
||||
)
|
||||
return el
|
||||
}
|
||||
case 'path': {
|
||||
const el = doc.createElementNS(SVG_NS, 'path')
|
||||
el.setAttribute('d', geometry.d)
|
||||
return el
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function labelAnchor(geometry: Geometry): [number, number] | null {
|
||||
if (geometry.type === 'circle') {
|
||||
return [geometry.cx, geometry.cy - geometry.r - 4]
|
||||
}
|
||||
if (geometry.type === 'polygon') {
|
||||
const n = geometry.points.length
|
||||
const [sx, sy] = geometry.points.reduce(
|
||||
([ax, ay], [x, y]) => [ax + x, ay + y],
|
||||
[0, 0],
|
||||
)
|
||||
return [sx / n, sy / n]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function markerGroup(
|
||||
doc: Document,
|
||||
layer: Element,
|
||||
marker: Marker,
|
||||
fontSize: number,
|
||||
) {
|
||||
const group = doc.createElementNS(SVG_NS, 'g')
|
||||
group.setAttribute('data-review-id', marker.id)
|
||||
group.setAttribute('data-review-status', marker.status)
|
||||
const shape = shapeElement(doc, marker.geometry)
|
||||
for (const [k, v] of Object.entries(STYLE[marker.status])) {
|
||||
shape.setAttribute(k, v)
|
||||
}
|
||||
shape.setAttribute('stroke-width', String(fontSize / 8))
|
||||
const title = doc.createElementNS(SVG_NS, 'title')
|
||||
title.appendChild(doc.createTextNode(`${marker.id} (${marker.status})`))
|
||||
group.appendChild(title)
|
||||
group.appendChild(shape)
|
||||
const anchor = labelAnchor(marker.geometry)
|
||||
if (anchor && marker.status !== 'removed') {
|
||||
const text = doc.createElementNS(SVG_NS, 'text')
|
||||
text.setAttribute('x', String(anchor[0]))
|
||||
text.setAttribute('y', String(anchor[1]))
|
||||
text.setAttribute('text-anchor', 'middle')
|
||||
text.setAttribute('font-family', 'sans-serif')
|
||||
text.setAttribute('font-size', String(fontSize))
|
||||
text.setAttribute('fill', STYLE[marker.status].stroke!)
|
||||
text.appendChild(doc.createTextNode(marker.id))
|
||||
group.appendChild(text)
|
||||
}
|
||||
layer.appendChild(group)
|
||||
}
|
||||
|
||||
function legend(
|
||||
doc: Document,
|
||||
layer: Element,
|
||||
[x, y]: [number, number],
|
||||
fontSize: number,
|
||||
) {
|
||||
const lines = [
|
||||
['unchanged', 'bleu : inchangé'],
|
||||
[
|
||||
'moved',
|
||||
'vert : déplacé ou ajouté (pointillé rouge = position précédente)',
|
||||
],
|
||||
['removed', 'rouge pointillé : retiré'],
|
||||
] as const
|
||||
lines.forEach(([status, label], i) => {
|
||||
const text = doc.createElementNS(SVG_NS, 'text')
|
||||
text.setAttribute('x', String(x))
|
||||
text.setAttribute('y', String(y + (i + 1) * fontSize * 1.3))
|
||||
text.setAttribute('font-family', 'sans-serif')
|
||||
text.setAttribute('font-size', String(fontSize))
|
||||
text.setAttribute('fill', STYLE[status].stroke!)
|
||||
text.appendChild(doc.createTextNode(label))
|
||||
layer.appendChild(text)
|
||||
})
|
||||
}
|
||||
|
||||
export interface OverlayInput {
|
||||
cleanedSvg: string
|
||||
before: Doc
|
||||
after: Doc
|
||||
viewId: string
|
||||
}
|
||||
|
||||
/** The review drawing of one view, framed on that view's box. */
|
||||
export function renderReviewOverlay(input: OverlayInput): string {
|
||||
const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
|
||||
const view = input.after.views.find((v) => v.id === input.viewId)
|
||||
if (!view) throw new Error(`unknown view "${input.viewId}"`)
|
||||
if (view.view_box) {
|
||||
const { min_x, min_y, width, height } = view.view_box
|
||||
root.setAttribute('viewBox', `${min_x} ${min_y} ${width} ${height}`)
|
||||
}
|
||||
root.removeAttribute('width')
|
||||
root.removeAttribute('height')
|
||||
const box = (root.getAttribute('viewBox') ?? '0 0 1000 1000')
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
// ~1% of the frame width, never below 10 units (detail views are small).
|
||||
const fontSize = Math.max(Math.round(box[2]! / 90), 10)
|
||||
const layer = doc.createElementNS(SVG_NS, 'g')
|
||||
layer.setAttribute('id', LAYER_ID)
|
||||
for (const marker of overlayMarkers(
|
||||
input.before,
|
||||
input.after,
|
||||
input.viewId,
|
||||
)) {
|
||||
markerGroup(doc, layer, marker, fontSize)
|
||||
}
|
||||
legend(doc, layer, [box[0]! + fontSize, box[1]!], fontSize)
|
||||
root.appendChild(layer)
|
||||
return new XMLSerializer().serializeToString(doc)
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
Reference,
|
||||
SheetIssue,
|
||||
ViewBox,
|
||||
} from '@faunosteo/domain'
|
||||
import { formatJson, formatMarkdown } from '../format'
|
||||
import { HEAD_VIEW_ID, MAIN_VIEW_ID } from '../legacy/importer'
|
||||
import type {
|
||||
Anomaly,
|
||||
AssetRecord,
|
||||
ImportResult,
|
||||
LegacyIdMap,
|
||||
} from '../legacy/types'
|
||||
import { applyChangeset, curatedIssues } from './apply'
|
||||
import { cleanedAsset, stripLegacyAnnotations } from './assets'
|
||||
import { renderChangelog } from './changelog'
|
||||
import { REVIEW_OVERLAY_DIR, renderReviewOverlay } from './overlay'
|
||||
import { buildReportMigrationMap } from './migration-map'
|
||||
import { renderAppReviewDrawing } from './app-review'
|
||||
import { sha256Hex } from '../legacy/ids'
|
||||
import { renderReviewReport } from './review-report'
|
||||
import {
|
||||
ASSET_CHANGE_ID,
|
||||
changeSummary,
|
||||
type Change,
|
||||
type ChangeSummary,
|
||||
type Changeset,
|
||||
} from './schema'
|
||||
import { DRAFT_CHANGE_NOTE, renderDraftSeedSql } from './seed'
|
||||
import { documentStats, type DocumentStats } from './stats'
|
||||
import type { ChangeRecord } from './types'
|
||||
|
||||
/**
|
||||
* Legacy import → curated working draft. The asset step runs first as the
|
||||
* reserved change CHG-000 (one cleaned drawing, head view = crop), then
|
||||
* the authored changeset; both land in the same records, so the CHANGELOG
|
||||
* lists them alike. Deterministic: same inputs, same bytes.
|
||||
*/
|
||||
|
||||
export const DRAFT_SEED_SQL_FILE = 'equine_draft.sql'
|
||||
|
||||
export interface DraftInput {
|
||||
importResult: ImportResult
|
||||
legacyMainSvgBytes: Uint8Array
|
||||
headViewBox: ViewBox
|
||||
references: readonly Reference[]
|
||||
changeset: Changeset
|
||||
}
|
||||
|
||||
export interface DraftResult {
|
||||
document: AnatomicalSheetDocumentInput
|
||||
/** Legacy import the changeset was applied to. */
|
||||
baseline: AnatomicalSheetDocumentInput
|
||||
legacyIdMap: LegacyIdMap
|
||||
records: ChangeRecord[]
|
||||
changes: ChangeSummary[]
|
||||
assets: AssetRecord[]
|
||||
/** Cleaned drawing, written as draft/assets/<assets[0].file>. */
|
||||
cleanedSvg: string
|
||||
statsBefore: DocumentStats
|
||||
statsAfter: DocumentStats
|
||||
/** Integrity warnings of the curated document (errors throw). */
|
||||
issues: SheetIssue[]
|
||||
sheetId: string
|
||||
}
|
||||
|
||||
function assetChange(asset: AssetRecord, headViewBox: ViewBox): Change {
|
||||
return {
|
||||
id: ASSET_CHANGE_ID,
|
||||
level: 'A',
|
||||
kind: 'technical',
|
||||
title: {
|
||||
fr: 'Un seul dessin, vue tête = recadrage',
|
||||
en: 'Single drawing, head view = crop',
|
||||
},
|
||||
rationale:
|
||||
'Les deux fichiers historiques portent le même dessin (tracés ' +
|
||||
'identiques) et les marqueurs sont désormais des données de la ' +
|
||||
'fiche : un seul dessin nettoyé, la vue tête en est un recadrage.',
|
||||
reference_ids: [],
|
||||
priority: 'medium',
|
||||
ops: [
|
||||
{
|
||||
op: 'set',
|
||||
target: `view:${MAIN_VIEW_ID}`,
|
||||
field: 'svg_asset_id',
|
||||
value: asset.svg_asset_id,
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: `view:${HEAD_VIEW_ID}`,
|
||||
field: 'svg_asset_id',
|
||||
value: null,
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: `view:${HEAD_VIEW_ID}`,
|
||||
field: 'view_box',
|
||||
value: headViewBox,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function assertNotReserved(changeset: Changeset): void {
|
||||
if (changeset.changes.some((change) => change.id === ASSET_CHANGE_ID)) {
|
||||
throw new Error(`${ASSET_CHANGE_ID} is reserved for the asset step`)
|
||||
}
|
||||
}
|
||||
|
||||
export function buildEquineDraft(input: DraftInput): DraftResult {
|
||||
assertNotReserved(input.changeset)
|
||||
const legacyText = new TextDecoder('utf-8', { fatal: true }).decode(
|
||||
input.legacyMainSvgBytes,
|
||||
)
|
||||
const cleanedSvg = stripLegacyAnnotations(legacyText)
|
||||
const asset = cleanedAsset(new TextEncoder().encode(cleanedSvg))
|
||||
const changes = [
|
||||
assetChange(asset, input.headViewBox),
|
||||
...input.changeset.changes,
|
||||
]
|
||||
const baseline = input.importResult.document
|
||||
const result = applyChangeset(baseline, input.references, { changes })
|
||||
return {
|
||||
document: result.document,
|
||||
baseline,
|
||||
legacyIdMap: input.importResult.legacyIdMap,
|
||||
records: result.records,
|
||||
changes: changes.map(changeSummary),
|
||||
assets: [asset],
|
||||
cleanedSvg,
|
||||
statsBefore: documentStats(baseline),
|
||||
statsAfter: documentStats(result.document),
|
||||
issues: curatedIssues(result.document),
|
||||
sheetId: input.importResult.sheetId,
|
||||
}
|
||||
}
|
||||
|
||||
/** One review drawing per view, under review/annotations-<view>.svg. */
|
||||
function reviewOverlays(draft: DraftResult): Record<string, string> {
|
||||
const files: Record<string, string> = {}
|
||||
for (const view of draft.document.views) {
|
||||
files[`${REVIEW_OVERLAY_DIR}/annotations-${view.id}.svg`] =
|
||||
renderReviewOverlay({
|
||||
cleanedSvg: draft.cleanedSvg,
|
||||
before: draft.baseline,
|
||||
after: draft.document,
|
||||
viewId: view.id,
|
||||
})
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
export const SHEET_REF_FILE = 'sheet-ref.json'
|
||||
export const MIGRATION_MAP_FILE = 'report-migration-map.json'
|
||||
|
||||
/** What a report references: the sheet and the exact document bytes. */
|
||||
function sheetRef(draft: DraftResult, documentJson: string) {
|
||||
return {
|
||||
sheetId: draft.sheetId,
|
||||
versionId: null,
|
||||
documentSha256: sha256Hex(documentJson),
|
||||
}
|
||||
}
|
||||
|
||||
/** The application's own rendering of each view, for the visual check. */
|
||||
function appReviewDrawings(draft: DraftResult): Record<string, string> {
|
||||
const files: Record<string, string> = {}
|
||||
for (const view of draft.document.views) {
|
||||
files[`${REVIEW_OVERLAY_DIR}/app-${view.id}.svg`] = renderAppReviewDrawing({
|
||||
cleanedSvg: draft.cleanedSvg,
|
||||
document: draft.document,
|
||||
viewId: view.id,
|
||||
})
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
/** Text artifacts of the draft folder, keyed by file name. */
|
||||
export async function renderDraftArtifacts(
|
||||
draft: DraftResult,
|
||||
legacyAnomalies: readonly Anomaly[],
|
||||
): Promise<Record<string, string>> {
|
||||
const documentJson = await formatJson(draft.document)
|
||||
const ref = sheetRef(draft, documentJson)
|
||||
const migration = buildReportMigrationMap({
|
||||
baseline: draft.baseline as Record<string, unknown>,
|
||||
final: draft.document as Record<string, unknown>,
|
||||
legacyIdMap: draft.legacyIdMap,
|
||||
records: draft.records,
|
||||
sheet: ref,
|
||||
mainViewId: MAIN_VIEW_ID,
|
||||
})
|
||||
const changelog = renderChangelog(
|
||||
draft,
|
||||
draft.statsBefore,
|
||||
draft.statsAfter,
|
||||
migration.stats,
|
||||
)
|
||||
const review = renderReviewReport({ ...draft, legacyAnomalies })
|
||||
return {
|
||||
'document.json': documentJson,
|
||||
'assets.json': await formatJson(draft.assets),
|
||||
[SHEET_REF_FILE]: await formatJson({
|
||||
sheet_id: ref.sheetId,
|
||||
version_id: ref.versionId,
|
||||
document_sha256: ref.documentSha256,
|
||||
schema_version: draft.document.schema_version,
|
||||
species_id: draft.document.species_id,
|
||||
}),
|
||||
[MIGRATION_MAP_FILE]: await formatJson(migration.map),
|
||||
...reviewOverlays(draft),
|
||||
...appReviewDrawings(draft),
|
||||
'CHANGELOG.md': await formatMarkdown(changelog),
|
||||
'REVIEW-REPORT.md': await formatMarkdown(review),
|
||||
[DRAFT_SEED_SQL_FILE]: renderDraftSeedSql({
|
||||
sheetId: draft.sheetId,
|
||||
assets: draft.assets,
|
||||
documentJson,
|
||||
changeNote: DRAFT_CHANGE_NOTE,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { allFindings, topCollection, type TargetKind } from './targets'
|
||||
import { record, type OpContext } from './types'
|
||||
|
||||
/**
|
||||
* Rename propagation: every field pointing at the renamed id follows, and
|
||||
* each rewrite is a record of its own so the CHANGELOG shows the cascade.
|
||||
*/
|
||||
|
||||
interface Link {
|
||||
kind: 'annotation' | 'view'
|
||||
field: string
|
||||
}
|
||||
|
||||
const LINKS: Partial<Record<TargetKind, readonly Link[]>> = {
|
||||
zone: [{ kind: 'annotation', field: 'finding_zone_id' }],
|
||||
region: [{ kind: 'annotation', field: 'vertebral_region_code' }],
|
||||
view: [
|
||||
{ kind: 'view', field: 'parent_view_id' },
|
||||
{ kind: 'annotation', field: 'view_id' },
|
||||
{ kind: 'annotation', field: 'opens_view_id' },
|
||||
],
|
||||
category: [{ kind: 'annotation', field: 'category_id' }],
|
||||
}
|
||||
|
||||
interface Rename {
|
||||
kind: TargetKind
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
function followLink(ctx: OpContext, link: Link, rename: Rename): void {
|
||||
for (const item of topCollection(ctx.doc, link.kind)) {
|
||||
if (item[link.field] !== rename.from) continue
|
||||
item[link.field] = rename.to
|
||||
record(ctx, `${link.kind}:${String(item.id)}`, link.field, {
|
||||
before: rename.from,
|
||||
after: rename.to,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function followCitations(ctx: OpContext, rename: Rename): void {
|
||||
for (const { target, item } of allFindings(ctx.doc)) {
|
||||
const ids = item.reference_ids
|
||||
if (!Array.isArray(ids) || !ids.includes(rename.from)) continue
|
||||
const after = ids.map((id: unknown) =>
|
||||
id === rename.from ? rename.to : id,
|
||||
)
|
||||
record(ctx, target, 'reference_ids', { before: ids, after })
|
||||
item.reference_ids = after
|
||||
}
|
||||
}
|
||||
|
||||
export function propagateRename(ctx: OpContext, rename: Rename): void {
|
||||
if (rename.kind === 'reference') return followCitations(ctx, rename)
|
||||
for (const link of LINKS[rename.kind] ?? []) followLink(ctx, link, rename)
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import type { Anomaly } from '../legacy/types'
|
||||
import { code, table } from '../markdown'
|
||||
import { compactValue, recordSubject } from './changelog'
|
||||
import { KIND_LABELS, PRIORITY_LABELS } from './labels'
|
||||
import {
|
||||
needsConfirmation,
|
||||
type ChangePriority,
|
||||
type ChangeSummary,
|
||||
} from './schema'
|
||||
import { statRows, type DocumentStats } from './stats'
|
||||
import { allFindings, zoneFindings, type Item } from './targets'
|
||||
import type { ChangeRecord } from './types'
|
||||
|
||||
/**
|
||||
* French review report for the osteopath, ten fixed sections. It only
|
||||
* formats data (changes, records, stats, references): no medical content
|
||||
* is written here, every statement comes from the authored changeset.
|
||||
*/
|
||||
|
||||
export interface ReviewReportInput {
|
||||
changes: readonly ChangeSummary[]
|
||||
records: readonly ChangeRecord[]
|
||||
document: AnatomicalSheetDocumentInput
|
||||
statsBefore: DocumentStats
|
||||
legacyAnomalies: readonly Anomaly[]
|
||||
}
|
||||
|
||||
type Section = (input: ReviewReportInput) => string
|
||||
|
||||
const NONE = 'Aucun élément dans cette révision.'
|
||||
const PRIORITY_ORDER: readonly ChangePriority[] = ['high', 'medium', 'low']
|
||||
|
||||
function subjects(input: ReviewReportInput, change: ChangeSummary): string {
|
||||
const own = input.records.filter((r) => r.change.id === change.id)
|
||||
return [...new Set(own.map(recordSubject))].map(code).join(', ')
|
||||
}
|
||||
|
||||
function references(ids: readonly string[]): string {
|
||||
return ids.length === 0 ? 'aucune' : ids.map(code).join(', ')
|
||||
}
|
||||
|
||||
function changeLine(input: ReviewReportInput, change: ChangeSummary): string {
|
||||
const confirm = needsConfirmation(change.level) ? 'oui' : 'non'
|
||||
return (
|
||||
`- ${code(change.id)} ${change.title.fr} (niveau ${change.level}, ` +
|
||||
`${KIND_LABELS[change.kind]}, confirmation requise : ${confirm}). ` +
|
||||
`${change.rationale} Objets : ${subjects(input, change)}. ` +
|
||||
`Références : ${references(change.reference_ids)}.` +
|
||||
(change.question ? ` Question : ${change.question}` : '')
|
||||
)
|
||||
}
|
||||
|
||||
function changeList(
|
||||
input: ReviewReportInput,
|
||||
keep: (c: ChangeSummary) => boolean,
|
||||
) {
|
||||
const lines = input.changes.filter(keep).map((c) => changeLine(input, c))
|
||||
return lines.length === 0 ? NONE : lines.join('\n')
|
||||
}
|
||||
|
||||
const initialQuality: Section = (input) => {
|
||||
const toValidate = input.legacyAnomalies.filter(
|
||||
(a) => a.level === 'a_valider',
|
||||
)
|
||||
return [
|
||||
`L'import historique signale ${input.legacyAnomalies.length} anomalies, ` +
|
||||
`dont ${toValidate.length} à valider (détail dans ` +
|
||||
'`legacy-import/IMPORT-REPORT.md`).',
|
||||
'',
|
||||
table(
|
||||
['Indicateur (import historique)', 'Valeur'],
|
||||
statRows(input.statsBefore),
|
||||
),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
const mainErrors: Section = (input) =>
|
||||
changeList(
|
||||
input,
|
||||
(c) => c.level === 'A' && (c.kind === 'correction' || c.kind === 'removal'),
|
||||
)
|
||||
|
||||
const translations: Section = (input) => {
|
||||
const changes = input.changes.filter((c) => c.kind === 'translation')
|
||||
const ids = new Set(changes.map((c) => c.id))
|
||||
const touched = input.records.filter((r) => ids.has(r.change.id))
|
||||
const targets = [...new Set(touched.map(recordSubject))]
|
||||
const head =
|
||||
`${changes.length} changement(s) de traduction, ` +
|
||||
`${targets.length} objet(s) traduit(s).`
|
||||
return targets.length === 0
|
||||
? head
|
||||
: `${head}\n\n${targets.map((t) => `- ${code(t)}`).join('\n')}`
|
||||
}
|
||||
|
||||
function vetFlagChanges(input: ReviewReportInput): string {
|
||||
const flips = input.records.filter((r) => r.field === 'requires_vet_referral')
|
||||
if (flips.length === 0)
|
||||
return 'Aucun renvoi vétérinaire modifié dans cette révision.'
|
||||
const line = (r: ChangeRecord) =>
|
||||
`- ${code(r.target)} : ${compactValue(r.before)} → ` +
|
||||
`${compactValue(r.after)} (${code(r.change.id)})`
|
||||
return flips.map(line).join('\n')
|
||||
}
|
||||
|
||||
function vetFlagsPerZone(doc: AnatomicalSheetDocumentInput): string {
|
||||
const rows = (doc.finding_zones as unknown as Item[]).flatMap((zone) => {
|
||||
const flags = zoneFindings(zone).filter(
|
||||
(e) => e.item.requires_vet_referral === true,
|
||||
)
|
||||
return flags.length === 0 ? [] : [[code(String(zone.id)), flags.length]]
|
||||
})
|
||||
return rows.length === 0
|
||||
? 'Aucun renvoi vétérinaire.'
|
||||
: table(['Zone', 'Renvois vétérinaires'], rows)
|
||||
}
|
||||
|
||||
const clinicalVigilance: Section = (input) =>
|
||||
[
|
||||
'Renvois vétérinaires modifiés :',
|
||||
'',
|
||||
vetFlagChanges(input),
|
||||
'',
|
||||
'Renvois vétérinaires de la fiche, par zone :',
|
||||
'',
|
||||
vetFlagsPerZone(input.document),
|
||||
].join('\n')
|
||||
|
||||
function citationCount(doc: AnatomicalSheetDocumentInput, id: string): number {
|
||||
return allFindings(doc as unknown as Item).filter((e) => {
|
||||
const ids = e.item.reference_ids
|
||||
return Array.isArray(ids) && ids.includes(id)
|
||||
}).length
|
||||
}
|
||||
|
||||
const bibliography: Section = (input) => {
|
||||
const lines = input.document.references.map((ref, index) => {
|
||||
const links = [
|
||||
ref.url ? `URL : ${ref.url}` : '',
|
||||
ref.doi ? `DOI : ${ref.doi}` : '',
|
||||
].filter(Boolean)
|
||||
const where = links.length > 0 ? ` (${links.join(', ')})` : ''
|
||||
const cited = citationCount(input.document, ref.id)
|
||||
return (
|
||||
`${index + 1}. ${code(ref.id)} ${ref.citation}${where}, ` +
|
||||
`cité par ${cited} nœud(s).`
|
||||
)
|
||||
})
|
||||
return lines.length === 0 ? 'Aucune référence déclarée.' : lines.join('\n')
|
||||
}
|
||||
|
||||
function byPriorityThenId(a: ChangeSummary, b: ChangeSummary): number {
|
||||
const rank =
|
||||
PRIORITY_ORDER.indexOf(a.priority) - PRIORITY_ORDER.indexOf(b.priority)
|
||||
if (rank !== 0) return rank
|
||||
if (a.id === b.id) return 0
|
||||
return a.id < b.id ? -1 : 1
|
||||
}
|
||||
|
||||
const professionalDecisions: Section = (input) => {
|
||||
const questions = input.changes
|
||||
.filter((c) => c.question !== undefined)
|
||||
.sort(byPriorityThenId)
|
||||
if (questions.length === 0) return 'Aucune question ouverte.'
|
||||
return questions
|
||||
.map(
|
||||
(c, index) =>
|
||||
`${index + 1}. ${code(c.id)} (priorité ${PRIORITY_LABELS[c.priority]}) : ` +
|
||||
`${c.question ?? ''} Références : ${references(c.reference_ids)}.`,
|
||||
)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
const SECTIONS: ReadonlyArray<[string, Section]> = [
|
||||
['1. Qualité des données initiales', initialQuality],
|
||||
['2. Principales erreurs anatomiques et ostéopathiques', mainErrors],
|
||||
['3. Corrections effectuées', (i) => changeList(i, (c) => c.level === 'A')],
|
||||
['4. Ajouts', (i) => changeList(i, (c) => c.kind === 'enrichment')],
|
||||
[
|
||||
'5. Réorganisations du catalogue',
|
||||
(i) => changeList(i, (c) => c.kind === 'restructure'),
|
||||
],
|
||||
['6. Éléments incertains', (i) => changeList(i, (c) => c.level === 'C')],
|
||||
['7. Traductions', translations],
|
||||
['8. Points de vigilance clinique', clinicalVigilance],
|
||||
['9. Bibliographie', bibliography],
|
||||
['10. Décisions réservées au professionnel', professionalDecisions],
|
||||
]
|
||||
|
||||
function intro(): string {
|
||||
return [
|
||||
'# Rapport de revue : révision de travail',
|
||||
'',
|
||||
'Généré par `pnpm import:equine` à partir des changements rédigés ' +
|
||||
'(`curation/changes.json`). Ne pas modifier à la main. Rien n’est ' +
|
||||
'publié : la révision reste un brouillon jusqu’à la décision du professionnel.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function renderReviewReport(input: ReviewReportInput): string {
|
||||
const sections = SECTIONS.map(
|
||||
([title, render]) => `## ${title}\n\n${render(input)}`,
|
||||
)
|
||||
return `${[intro(), ...sections].join('\n\n')}\n`
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { ReferenceSchema } from '@faunosteo/domain'
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Authored curation inputs (supabase/seed/anatomical-sheets/<species>/
|
||||
* curation/): a changeset of traceable changes applied on the legacy
|
||||
* baseline, and the references registry they cite. Every object is strict
|
||||
* so a typo in a hand-written file fails loud instead of being ignored.
|
||||
*/
|
||||
|
||||
/** A demonstrated error, B supported improvement, C uncertain (question). */
|
||||
export const ChangeLevelSchema = z.enum(['A', 'B', 'C'])
|
||||
|
||||
export const ChangeKindSchema = z.enum([
|
||||
'correction',
|
||||
'terminology',
|
||||
'translation',
|
||||
'restructure',
|
||||
'enrichment',
|
||||
'reference',
|
||||
'geometry',
|
||||
'removal',
|
||||
'technical',
|
||||
])
|
||||
|
||||
export const ChangePrioritySchema = z.enum(['high', 'medium', 'low'])
|
||||
|
||||
/** Reserved for the asset step of the pipeline, never authored. */
|
||||
export const ASSET_CHANGE_ID = 'CHG-000'
|
||||
|
||||
const TargetSchema = z.string().min(1)
|
||||
|
||||
const PositionSchema = z.union([
|
||||
z.number().int().min(0),
|
||||
z.object({ after: z.string().min(1) }).strict(),
|
||||
z.object({ before: z.string().min(1) }).strict(),
|
||||
])
|
||||
|
||||
const ScopeSchema = z.enum(['self', 'subtree'])
|
||||
|
||||
/** Document-level collections an `add` on 'document' may extend. */
|
||||
export const DocumentCollectionSchema = z.enum([
|
||||
'references',
|
||||
'categories',
|
||||
'views',
|
||||
'annotations',
|
||||
'finding_zones',
|
||||
'regions',
|
||||
])
|
||||
|
||||
const SetOpSchema = z
|
||||
.object({
|
||||
op: z.literal('set'),
|
||||
target: TargetSchema,
|
||||
field: z.string().min(1),
|
||||
value: z.unknown(),
|
||||
scope: ScopeSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
const RenameOpSchema = z
|
||||
.object({
|
||||
op: z.literal('rename'),
|
||||
target: TargetSchema,
|
||||
id: z.string().min(1),
|
||||
})
|
||||
.strict()
|
||||
|
||||
const AddOpSchema = z
|
||||
.object({
|
||||
op: z.literal('add'),
|
||||
target: TargetSchema,
|
||||
field: DocumentCollectionSchema.optional(),
|
||||
value: z.unknown(),
|
||||
position: PositionSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
const RemoveOpSchema = z
|
||||
.object({ op: z.literal('remove'), target: TargetSchema })
|
||||
.strict()
|
||||
|
||||
const MoveOpSchema = z
|
||||
.object({
|
||||
op: z.literal('move'),
|
||||
target: TargetSchema,
|
||||
to: TargetSchema,
|
||||
position: PositionSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
const CiteOpSchema = z
|
||||
.object({
|
||||
op: z.literal('cite'),
|
||||
target: TargetSchema,
|
||||
reference_ids: z.array(z.string().min(1)).min(1),
|
||||
scope: ScopeSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const OpSchema = z.discriminatedUnion('op', [
|
||||
SetOpSchema,
|
||||
RenameOpSchema,
|
||||
AddOpSchema,
|
||||
RemoveOpSchema,
|
||||
MoveOpSchema,
|
||||
CiteOpSchema,
|
||||
])
|
||||
|
||||
export const ChangeSchema = z
|
||||
.object({
|
||||
id: z.string().regex(/^CHG-\d{3,}$/),
|
||||
level: ChangeLevelSchema,
|
||||
kind: ChangeKindSchema,
|
||||
title: z.object({ fr: z.string().min(1), en: z.string().min(1) }).strict(),
|
||||
rationale: z.string().min(1),
|
||||
reference_ids: z.array(z.string().min(1)),
|
||||
question: z.string().min(1).optional(),
|
||||
priority: ChangePrioritySchema.default('medium'),
|
||||
ops: z.array(OpSchema).min(1),
|
||||
})
|
||||
.strict()
|
||||
.refine((change) => change.level !== 'C' || change.question !== undefined, {
|
||||
message: 'a level C change needs a question',
|
||||
path: ['question'],
|
||||
})
|
||||
|
||||
function duplicates(ids: readonly string[]): string[] {
|
||||
return ids.filter((id, index) => ids.indexOf(id) !== index)
|
||||
}
|
||||
|
||||
export const ChangesetSchema = z
|
||||
.object({ changes: z.array(ChangeSchema) })
|
||||
.strict()
|
||||
.superRefine((set, ctx) => {
|
||||
for (const id of duplicates(set.changes.map((c) => c.id))) {
|
||||
ctx.addIssue({ code: 'custom', message: `duplicate change id ${id}` })
|
||||
}
|
||||
})
|
||||
|
||||
export const ReferencesFileSchema = z
|
||||
.object({ references: z.array(ReferenceSchema) })
|
||||
.strict()
|
||||
.superRefine((file, ctx) => {
|
||||
for (const id of duplicates(file.references.map((r) => r.id))) {
|
||||
ctx.addIssue({ code: 'custom', message: `duplicate reference id ${id}` })
|
||||
}
|
||||
})
|
||||
|
||||
export type ChangeLevel = z.infer<typeof ChangeLevelSchema>
|
||||
export type ChangeKind = z.infer<typeof ChangeKindSchema>
|
||||
export type ChangePriority = z.infer<typeof ChangePrioritySchema>
|
||||
export type Position = z.infer<typeof PositionSchema>
|
||||
export type Op = z.infer<typeof OpSchema>
|
||||
export type Change = z.output<typeof ChangeSchema>
|
||||
export type ChangeInput = z.input<typeof ChangeSchema>
|
||||
export type Changeset = z.output<typeof ChangesetSchema>
|
||||
export type ReferencesFile = z.output<typeof ReferencesFileSchema>
|
||||
|
||||
/** A change as cited by its records: everything but the ops. */
|
||||
export type ChangeSummary = Omit<Change, 'ops'>
|
||||
|
||||
/** Derived, never stored: only a demonstrated error needs no sign-off. */
|
||||
export function needsConfirmation(level: ChangeLevel): boolean {
|
||||
return level !== 'A'
|
||||
}
|
||||
|
||||
export function changeSummary(change: Change): ChangeSummary {
|
||||
const summary: Partial<Change> = { ...change }
|
||||
delete summary.ops
|
||||
return summary as ChangeSummary
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import type { AssetRecord } from '../legacy/types'
|
||||
|
||||
/**
|
||||
* Idempotent and converging PostgreSQL seed of an official sheet's working
|
||||
* DRAFT. Runs as the database owner in `supabase db reset` and in the
|
||||
* PGlite harness. A fresh database gets the draft through
|
||||
* private.insert_sheet_draft (audited, null actor); a database still
|
||||
* holding an older draft as the sheet's only version gets its content
|
||||
* replaced in place. Published rows are never touched and nothing is
|
||||
* published: that stays a human act through publish_sheet_version.
|
||||
*/
|
||||
|
||||
export const DOCUMENT_DOLLAR_TAG = '$equine_doc$'
|
||||
|
||||
const SHEET_DESCRIPTION =
|
||||
'Fiche anatomique officielle du cheval ' +
|
||||
'(import des données historiques, brouillon à valider)'
|
||||
|
||||
export const DRAFT_CHANGE_NOTE =
|
||||
'Révision de travail 4c (audit anatomique et ostéopathique) ' +
|
||||
'sur l’import des données historiques'
|
||||
|
||||
export interface DraftSeedParams {
|
||||
sheetId: string
|
||||
assets: readonly AssetRecord[]
|
||||
/** document.json text, embedded verbatim in a dollar-quoted literal. */
|
||||
documentJson: string
|
||||
changeNote: string
|
||||
}
|
||||
|
||||
/** Only ever fed fixed values; doubled quotes keep it literal-safe. */
|
||||
function sqlText(value: string): string {
|
||||
return `'${value.replace(/'/g, "''")}'`
|
||||
}
|
||||
|
||||
function header(): string {
|
||||
return [
|
||||
'-- Official equine anatomical sheet: working revision, DRAFT.',
|
||||
'-- Generated by `pnpm import:equine` (packages/anatomy): do not edit by hand.',
|
||||
'-- Idempotent and converging. Never publishes: the version stays in status',
|
||||
'-- draft until a platform admin validates REVIEW-REPORT.md and publishes it.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function sheetInsert(sheetId: string): string {
|
||||
return [
|
||||
'insert into public.anatomical_sheets',
|
||||
' (id, species_id, name, slug, description, creator_user_id, is_official, visibility)',
|
||||
'values (',
|
||||
` ${sqlText(sheetId)}, 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval',`,
|
||||
` ${sqlText(SHEET_DESCRIPTION)},`,
|
||||
" null, true, 'private'",
|
||||
')',
|
||||
'on conflict (id) do nothing;',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function assetInserts(sheetId: string, assets: readonly AssetRecord[]): string {
|
||||
const rows = assets.map(
|
||||
(a) =>
|
||||
` (${sqlText(a.svg_asset_id)}, ${sqlText(sheetId)}, ${sqlText(a.sha256)}, ` +
|
||||
`${a.byte_size}, 'image/svg+xml', ${sqlText(a.file)})`,
|
||||
)
|
||||
return [
|
||||
'insert into public.anatomical_sheet_assets',
|
||||
' (id, sheet_id, sha256, byte_size, content_type, file_name)',
|
||||
'values',
|
||||
rows.join(',\n'),
|
||||
'on conflict (sheet_id, sha256) do nothing;',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function documentLiteral(documentJson: string): string {
|
||||
if (documentJson.includes(DOCUMENT_DOLLAR_TAG)) {
|
||||
throw new Error(
|
||||
`document JSON contains the dollar-quote tag ${DOCUMENT_DOLLAR_TAG}`,
|
||||
)
|
||||
}
|
||||
return `${DOCUMENT_DOLLAR_TAG}${documentJson.trimEnd()}${DOCUMENT_DOLLAR_TAG}::jsonb`
|
||||
}
|
||||
|
||||
function draftInsert(params: DraftSeedParams, literal: string): string {
|
||||
const sheet = sqlText(params.sheetId)
|
||||
return [
|
||||
'select private.insert_sheet_draft(',
|
||||
' null,',
|
||||
` ${sheet},`,
|
||||
` ${literal},`,
|
||||
` ${sqlText(params.changeNote)}`,
|
||||
')',
|
||||
'where not exists (',
|
||||
` select 1 from public.anatomical_sheet_versions where sheet_id = ${sheet}`,
|
||||
');',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Only when the sheet's single version is a draft whose content differs;
|
||||
* the document literal is read once through the derived table.
|
||||
*/
|
||||
function draftConverge(params: DraftSeedParams, literal: string): string {
|
||||
const sheet = sqlText(params.sheetId)
|
||||
return [
|
||||
'update public.anatomical_sheet_versions v',
|
||||
`set content = d.content, change_note = ${sqlText(params.changeNote)}`,
|
||||
`from (select ${literal} as content) d`,
|
||||
`where v.sheet_id = ${sheet} and v.status = 'draft'`,
|
||||
' and v.content <> d.content',
|
||||
' and (select count(*) from public.anatomical_sheet_versions o',
|
||||
` where o.sheet_id = ${sheet}) = 1;`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function renderDraftSeedSql(params: DraftSeedParams): string {
|
||||
const literal = documentLiteral(params.documentJson)
|
||||
return (
|
||||
[
|
||||
header(),
|
||||
sheetInsert(params.sheetId),
|
||||
assetInserts(params.sheetId, params.assets),
|
||||
draftInsert(params, literal),
|
||||
draftConverge(params, literal),
|
||||
].join('\n\n') + '\n'
|
||||
)
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import type { Reference } from '@faunosteo/domain'
|
||||
import { EQUINE_CURATION_DIR } from '../legacy/sources'
|
||||
import { ChangesetSchema, ReferencesFileSchema, type Changeset } from './schema'
|
||||
|
||||
/**
|
||||
* The authored curation files of the equine sheet. Both are required: a
|
||||
* missing or invalid file stops the pipeline (no silent empty changeset).
|
||||
*/
|
||||
|
||||
export const CURATION_FILES = {
|
||||
references: 'references.json',
|
||||
changes: 'changes.json',
|
||||
} as const
|
||||
|
||||
export interface CurationInput {
|
||||
references: Reference[]
|
||||
changeset: Changeset
|
||||
}
|
||||
|
||||
async function readJson(path: string): Promise<unknown> {
|
||||
return JSON.parse(await readFile(path, 'utf8')) as unknown
|
||||
}
|
||||
|
||||
export async function readEquineCuration(
|
||||
repoRoot: string,
|
||||
): Promise<CurationInput> {
|
||||
const dir = join(repoRoot, EQUINE_CURATION_DIR)
|
||||
const [references, changes] = await Promise.all([
|
||||
readJson(join(dir, CURATION_FILES.references)),
|
||||
readJson(join(dir, CURATION_FILES.changes)),
|
||||
])
|
||||
return {
|
||||
references: ReferencesFileSchema.parse(references).references,
|
||||
changeset: ChangesetSchema.parse(changes),
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import { allFindings, type FindingEntry, type Item } from './targets'
|
||||
|
||||
/**
|
||||
* Volumes of a sheet document, compared before / after curation in the
|
||||
* CHANGELOG and shown for the baseline in the review report. Nodes count
|
||||
* finding categories too, as countTree does in the import report.
|
||||
*/
|
||||
|
||||
const ANNOTATION_KINDS = ['point', 'zone', 'detail_trigger'] as const
|
||||
const REVIEW_STATUSES = ['inherited', 'reviewed', 'to_confirm'] as const
|
||||
|
||||
type Counts = Record<string, number>
|
||||
|
||||
export interface DocumentStats {
|
||||
views: number
|
||||
assets: number
|
||||
annotations: number
|
||||
annotationsByKind: Counts
|
||||
annotationCategories: number
|
||||
findingZones: number
|
||||
findingCategories: number
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
descriptions: number
|
||||
descriptionsFrOnly: number
|
||||
references: number
|
||||
citedNodes: number
|
||||
nodesByReviewStatus: Counts
|
||||
annotationsByReviewStatus: Counts
|
||||
regionsWithCountRange: number
|
||||
}
|
||||
|
||||
function countBy<T>(
|
||||
items: readonly T[],
|
||||
keys: readonly string[],
|
||||
key: (item: T) => string,
|
||||
) {
|
||||
const counts: Counts = Object.fromEntries(keys.map((k) => [k, 0]))
|
||||
for (const item of items) counts[key(item)] = (counts[key(item)] ?? 0) + 1
|
||||
return counts
|
||||
}
|
||||
|
||||
function description(item: Item): { fr: boolean; en: boolean } {
|
||||
const text = (item.description ?? {}) as { fr?: string; en?: string }
|
||||
return { fr: Boolean(text.fr), en: Boolean(text.en) }
|
||||
}
|
||||
|
||||
function isLeaf(entry: FindingEntry): boolean {
|
||||
const children = entry.item.children
|
||||
return !Array.isArray(children) || children.length === 0
|
||||
}
|
||||
|
||||
function isCited(entry: FindingEntry): boolean {
|
||||
const ids = entry.item.reference_ids
|
||||
return Array.isArray(ids) && ids.length > 0
|
||||
}
|
||||
|
||||
function findingStats(findings: readonly FindingEntry[]) {
|
||||
const texts = findings.map((entry) => description(entry.item))
|
||||
return {
|
||||
findingCategories: findings.filter((entry) => entry.isCategory).length,
|
||||
nodes: findings.length,
|
||||
leaves: findings.filter(isLeaf).length,
|
||||
vetReferrals: findings.filter((e) => e.item.requires_vet_referral === true)
|
||||
.length,
|
||||
descriptions: texts.filter((t) => t.fr || t.en).length,
|
||||
descriptionsFrOnly: texts.filter((t) => t.fr && !t.en).length,
|
||||
citedNodes: findings.filter(isCited).length,
|
||||
nodesByReviewStatus: countBy(findings, REVIEW_STATUSES, (e) =>
|
||||
String(e.item.review_status ?? 'inherited'),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export function documentStats(
|
||||
doc: AnatomicalSheetDocumentInput,
|
||||
): DocumentStats {
|
||||
const assets = doc.views.flatMap((v) =>
|
||||
v.svg_asset_id ? [v.svg_asset_id] : [],
|
||||
)
|
||||
return {
|
||||
views: doc.views.length,
|
||||
assets: new Set(assets).size,
|
||||
annotations: doc.annotations.length,
|
||||
annotationsByKind: countBy(
|
||||
doc.annotations,
|
||||
ANNOTATION_KINDS,
|
||||
(a) => a.kind,
|
||||
),
|
||||
annotationCategories: doc.categories.length,
|
||||
findingZones: doc.finding_zones.length,
|
||||
...findingStats(allFindings(doc as unknown as Item)),
|
||||
references: doc.references.length,
|
||||
annotationsByReviewStatus: countBy(doc.annotations, REVIEW_STATUSES, (a) =>
|
||||
String(a.review_status ?? 'inherited'),
|
||||
),
|
||||
regionsWithCountRange: doc.vertebral_config.regions.filter(
|
||||
(r) => r.count_range,
|
||||
).length,
|
||||
}
|
||||
}
|
||||
|
||||
function countRows(label: string, counts: Counts): Array<[string, number]> {
|
||||
return Object.entries(counts).map(([key, value]) => [
|
||||
`${label} (${key})`,
|
||||
value,
|
||||
])
|
||||
}
|
||||
|
||||
/** Labelled rows, fixed order, French labels. */
|
||||
export function statRows(stats: DocumentStats): Array<[string, number]> {
|
||||
return [
|
||||
['Vues', stats.views],
|
||||
['Dessins SVG distincts', stats.assets],
|
||||
['Annotations', stats.annotations],
|
||||
...countRows('Annotations', stats.annotationsByKind),
|
||||
...countRows('Annotations, revue', stats.annotationsByReviewStatus),
|
||||
["Catégories d'annotation", stats.annotationCategories],
|
||||
['Zones de constats', stats.findingZones],
|
||||
['Catégories de constats', stats.findingCategories],
|
||||
['Nœuds (catégories incluses)', stats.nodes],
|
||||
['Feuilles', stats.leaves],
|
||||
['Renvois vétérinaires', stats.vetReferrals],
|
||||
...countRows('Nœuds, revue', stats.nodesByReviewStatus),
|
||||
['Descriptions', stats.descriptions],
|
||||
['Descriptions en français seulement', stats.descriptionsFrOnly],
|
||||
['Références bibliographiques', stats.references],
|
||||
['Nœuds cités', stats.citedNodes],
|
||||
['Régions vertébrales avec plage documentée', stats.regionsWithCountRange],
|
||||
]
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
/**
|
||||
* Target grammar of the changeset (one string per target):
|
||||
*
|
||||
* document | region:<code> | reference:<id> | category:<id> | view:<id>
|
||||
* annotation:<id> | zone:<zoneId> | finding:<zoneId>/<catId>[/<nodeId>…]
|
||||
*
|
||||
* A finding path walks ids from the zone down; ids are unique among
|
||||
* siblings, so the path names one category or node. Resolution works on
|
||||
* the plain JSON form of the document: the changeset reaches any field
|
||||
* without one accessor per type, and the final Zod parse checks the shape.
|
||||
*/
|
||||
|
||||
export type Item = Record<string, unknown>
|
||||
|
||||
export type TargetKind =
|
||||
| 'document'
|
||||
| 'region'
|
||||
| 'reference'
|
||||
| 'category'
|
||||
| 'view'
|
||||
| 'annotation'
|
||||
| 'zone'
|
||||
| 'finding'
|
||||
|
||||
export interface ParsedTarget {
|
||||
kind: TargetKind
|
||||
ids: string[]
|
||||
}
|
||||
|
||||
/** A resolved target: the item and the list that holds it (null: root). */
|
||||
export interface Located {
|
||||
target: ParsedTarget
|
||||
siblings: Item[] | null
|
||||
item: Item
|
||||
}
|
||||
|
||||
/** One finding category or node met while walking a zone's tree. */
|
||||
export interface FindingEntry {
|
||||
target: string
|
||||
item: Item
|
||||
isCategory: boolean
|
||||
}
|
||||
|
||||
const COLLECTION_KINDS: ReadonlySet<string> = new Set([
|
||||
'region',
|
||||
'reference',
|
||||
'category',
|
||||
'view',
|
||||
'annotation',
|
||||
'zone',
|
||||
'finding',
|
||||
])
|
||||
|
||||
export function isItem(value: unknown): value is Item {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function parseTarget(target: string): ParsedTarget {
|
||||
if (target === 'document') return { kind: 'document', ids: [] }
|
||||
const colon = target.indexOf(':')
|
||||
const kind = target.slice(0, colon)
|
||||
const rest = target.slice(colon + 1)
|
||||
if (colon < 1 || !COLLECTION_KINDS.has(kind) || rest === '') {
|
||||
throw new Error(`unknown target "${target}"`)
|
||||
}
|
||||
const ids = kind === 'finding' ? rest.split('/') : [rest]
|
||||
if (ids.includes('') || (kind === 'finding' && ids.length < 2)) {
|
||||
throw new Error(`malformed target "${target}"`)
|
||||
}
|
||||
return { kind: kind as TargetKind, ids }
|
||||
}
|
||||
|
||||
export function formatTarget(target: ParsedTarget): string {
|
||||
if (target.kind === 'document') return 'document'
|
||||
return `${target.kind}:${target.ids.join('/')}`
|
||||
}
|
||||
|
||||
/** Regions are keyed by their free code, everything else by a stable id. */
|
||||
export function keyField(kind: TargetKind): 'id' | 'code' {
|
||||
return kind === 'region' ? 'code' : 'id'
|
||||
}
|
||||
|
||||
function listAt(holder: Item, key: string): Item[] {
|
||||
const list = holder[key]
|
||||
if (!Array.isArray(list)) throw new Error(`document has no list "${key}"`)
|
||||
return list as Item[]
|
||||
}
|
||||
|
||||
/** Top-level list holding the items of a target kind. */
|
||||
export function topCollection(doc: Item, kind: TargetKind): Item[] {
|
||||
switch (kind) {
|
||||
case 'region':
|
||||
return listAt(doc.vertebral_config as Item, 'regions')
|
||||
case 'reference':
|
||||
return listAt(doc, 'references')
|
||||
case 'category':
|
||||
return listAt(doc, 'categories')
|
||||
case 'view':
|
||||
return listAt(doc, 'views')
|
||||
case 'annotation':
|
||||
return listAt(doc, 'annotations')
|
||||
default:
|
||||
return listAt(doc, 'finding_zones')
|
||||
}
|
||||
}
|
||||
|
||||
function findIn(list: Item[], key: string, id: string, target: string): Item {
|
||||
const item = list.find((entry) => entry[key] === id)
|
||||
if (!item) throw new Error(`unknown target "${target}" (no "${id}")`)
|
||||
return item
|
||||
}
|
||||
|
||||
/** Children of a finding item; lean leaves get an empty list on demand. */
|
||||
export function childrenOf(item: Item): Item[] {
|
||||
if (!Array.isArray(item.children)) item.children = []
|
||||
return item.children as Item[]
|
||||
}
|
||||
|
||||
function locateFinding(doc: Item, target: ParsedTarget, raw: string) {
|
||||
const zone = findIn(topCollection(doc, 'zone'), 'id', target.ids[0]!, raw)
|
||||
let siblings = listAt(zone, 'categories')
|
||||
let item = findIn(siblings, 'id', target.ids[1]!, raw)
|
||||
for (const id of target.ids.slice(2)) {
|
||||
siblings = Array.isArray(item.children) ? (item.children as Item[]) : []
|
||||
item = findIn(siblings, 'id', id, raw)
|
||||
}
|
||||
return { target, siblings, item }
|
||||
}
|
||||
|
||||
/** Resolves a target string or throws "unknown target". */
|
||||
export function locate(doc: Item, raw: string): Located {
|
||||
const target = parseTarget(raw)
|
||||
if (target.kind === 'document') return { target, siblings: null, item: doc }
|
||||
if (target.kind === 'finding') return locateFinding(doc, target, raw)
|
||||
const siblings = topCollection(doc, target.kind)
|
||||
const item = findIn(siblings, keyField(target.kind), target.ids[0]!, raw)
|
||||
return { target, siblings, item }
|
||||
}
|
||||
|
||||
/** The item and every descendant node, depth first, in document order. */
|
||||
function walk(item: Item, target: string, depth: number): FindingEntry[] {
|
||||
const own = { target, item, isCategory: depth === 0 }
|
||||
const children = Array.isArray(item.children) ? (item.children as Item[]) : []
|
||||
const nested = children.flatMap((child) =>
|
||||
walk(child, `${target}/${String(child.id)}`, depth + 1),
|
||||
)
|
||||
return [own, ...nested]
|
||||
}
|
||||
|
||||
/** Every finding category and node of a zone, depth first. */
|
||||
export function zoneFindings(zone: Item): FindingEntry[] {
|
||||
return listAt(zone, 'categories').flatMap((category) =>
|
||||
walk(category, `finding:${String(zone.id)}/${String(category.id)}`, 0),
|
||||
)
|
||||
}
|
||||
|
||||
/** Every finding category and node of the document. */
|
||||
export function allFindings(doc: Item): FindingEntry[] {
|
||||
return topCollection(doc, 'zone').flatMap(zoneFindings)
|
||||
}
|
||||
|
||||
/**
|
||||
* Finding items an op touches. A finding target alone ('self') or with its
|
||||
* descendants ('subtree'); a zone target stands for its categories alone
|
||||
* ('self') or its whole tree ('subtree'): a zone carries no citation.
|
||||
*/
|
||||
export function findingScope(
|
||||
located: Located,
|
||||
scope: 'self' | 'subtree',
|
||||
): FindingEntry[] {
|
||||
const { target, item } = located
|
||||
if (target.kind === 'zone') {
|
||||
const entries = zoneFindings(item)
|
||||
return scope === 'subtree' ? entries : entries.filter((e) => e.isCategory)
|
||||
}
|
||||
if (target.kind !== 'finding') {
|
||||
throw new Error(`"${formatTarget(target)}" is not a finding or a zone`)
|
||||
}
|
||||
const depth = target.ids.length === 2 ? 0 : 1
|
||||
const entries = walk(item, formatTarget(target), depth)
|
||||
return scope === 'subtree' ? entries : entries.slice(0, 1)
|
||||
}
|
||||
|
||||
/** The list an add or a move inserts into under a zone or a finding. */
|
||||
export function childList(parent: Located): Item[] {
|
||||
if (parent.target.kind === 'zone') return listAt(parent.item, 'categories')
|
||||
if (parent.target.kind === 'finding') return childrenOf(parent.item)
|
||||
throw new Error(`"${formatTarget(parent.target)}" holds no findings`)
|
||||
}
|
||||
|
||||
/** Target prefix of the items of childList(parent). */
|
||||
export function childPrefix(parent: Located): string {
|
||||
if (parent.target.kind === 'zone') return `finding:${parent.target.ids[0]}/`
|
||||
return `${formatTarget(parent.target)}/`
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import type { ChangeSummary, Op } from './schema'
|
||||
import type { Item } from './targets'
|
||||
|
||||
/**
|
||||
* One elementary edit of the curated document, kept for the CHANGELOG.
|
||||
* `before` / `after` are deep copies: the field value for a set, the whole
|
||||
* item for a rename, remove or move, null on the missing side.
|
||||
*/
|
||||
export interface ChangeRecord {
|
||||
change: ChangeSummary
|
||||
op: Op
|
||||
target: string
|
||||
field: string | null
|
||||
before: unknown
|
||||
after: unknown
|
||||
}
|
||||
|
||||
export interface CurationResult {
|
||||
document: AnatomicalSheetDocumentInput
|
||||
records: ChangeRecord[]
|
||||
}
|
||||
|
||||
/** State shared by the op functions of one change. */
|
||||
export interface OpContext {
|
||||
doc: Item
|
||||
change: ChangeSummary
|
||||
op: Op
|
||||
records: ChangeRecord[]
|
||||
/** Items the change edited, in order; the applier marks them at the end. */
|
||||
touched: Item[]
|
||||
}
|
||||
|
||||
/** Absent values are recorded as null so records stay plain JSON. */
|
||||
export function record(
|
||||
ctx: OpContext,
|
||||
target: string,
|
||||
field: string | null,
|
||||
values: { before: unknown; after: unknown },
|
||||
): void {
|
||||
ctx.records.push({
|
||||
change: ctx.change,
|
||||
op: ctx.op,
|
||||
target,
|
||||
field,
|
||||
before: structuredClone(values.before ?? null),
|
||||
after: structuredClone(values.after ?? null),
|
||||
})
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { format } from 'prettier'
|
||||
|
||||
/**
|
||||
* Prettier formatting of the generated artifacts with the repository
|
||||
* options, so `prettier --check` accepts the committed files as generated
|
||||
* (no exclusion needed). Shared by the legacy import and the draft.
|
||||
*/
|
||||
|
||||
const PRETTIER_OPTIONS = {
|
||||
semi: false,
|
||||
singleQuote: true,
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
trailingComma: 'all',
|
||||
printWidth: 80,
|
||||
bracketSpacing: true,
|
||||
arrowParens: 'always',
|
||||
endOfLine: 'lf',
|
||||
} as const
|
||||
|
||||
export function formatJson(value: unknown): Promise<string> {
|
||||
return format(JSON.stringify(value, null, 2), {
|
||||
...PRETTIER_OPTIONS,
|
||||
parser: 'json',
|
||||
})
|
||||
}
|
||||
|
||||
export function formatMarkdown(text: string): Promise<string> {
|
||||
return format(text, { ...PRETTIER_OPTIONS, parser: 'markdown' })
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export * from './legacy'
|
||||
export * from './curation'
|
||||
export * from './render'
|
||||
@@ -1,207 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
Geometry,
|
||||
Laterality,
|
||||
} from '@faunosteo/domain'
|
||||
import { normaliseCategoryId } from './categories'
|
||||
import { slugify } from './ids'
|
||||
import { inferRegionCode } from './regions'
|
||||
import type { LegacyAnnotation } from './svg'
|
||||
import type { Anomaly, AnnotationRow, RegionInference } from './types'
|
||||
|
||||
/**
|
||||
* Legacy SVG annotation → canonical annotation. The finding zone link is
|
||||
* resolved here, once, by exact FR + EN equality with the catalog (audit 06
|
||||
* §4); the document then carries finding_zone_id explicitly and nothing
|
||||
* matches labels at runtime.
|
||||
*/
|
||||
|
||||
export interface AnnotationContext {
|
||||
viewId: string
|
||||
fileName: string
|
||||
/** `${name_fr}\n${name_en}` → catalog zone key. */
|
||||
zoneByNames: ReadonlyMap<string, string>
|
||||
}
|
||||
|
||||
/** Authoring form: review_status stays implicit ('inherited'). */
|
||||
export type AnnotationInput =
|
||||
AnatomicalSheetDocumentInput['annotations'][number]
|
||||
|
||||
export interface MappedAnnotation {
|
||||
annotation: AnnotationInput
|
||||
row: AnnotationRow
|
||||
region: RegionInference | null
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
export function zoneNameKey(fr: string, en: string): string {
|
||||
return `${fr}\n${en}`
|
||||
}
|
||||
|
||||
function anomaly(code: string, subject: string, message: string): Anomaly {
|
||||
return { code, level: 'a_valider', subject, message }
|
||||
}
|
||||
|
||||
function laterality(a: LegacyAnnotation, out: Anomaly[]): Laterality {
|
||||
if (a.lateral === 'bilateral') return 'bilateral'
|
||||
if (a.lateral === null || a.lateral === 'unpaired') return 'unpaired'
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.laterality.unknown',
|
||||
a.id,
|
||||
`Latéralité « ${a.lateral} » inconnue, importée en « unpaired ».`,
|
||||
),
|
||||
)
|
||||
return 'unpaired'
|
||||
}
|
||||
|
||||
function describeGeometry(geometry: Geometry | null): string {
|
||||
if (geometry === null) return 'aucune'
|
||||
if (geometry.type === 'circle') {
|
||||
return `cercle (${geometry.cx}, ${geometry.cy}) r ${geometry.r}`
|
||||
}
|
||||
if (geometry.type === 'polygon') {
|
||||
return `polygone ${geometry.points.length} points`
|
||||
}
|
||||
return 'chemin'
|
||||
}
|
||||
|
||||
function regionOf(a: LegacyAnnotation, out: Anomaly[]): RegionInference | null {
|
||||
if (a.special === null) return null
|
||||
if (a.special !== 'vertebral-precision') {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.special.unknown',
|
||||
a.id,
|
||||
`special « ${a.special} » ignoré.`,
|
||||
),
|
||||
)
|
||||
return null
|
||||
}
|
||||
const match = inferRegionCode(a.nameFr, a.nameEn)
|
||||
if (!match) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.region.unknown',
|
||||
a.id,
|
||||
'Région vertébrale non déduite.',
|
||||
),
|
||||
)
|
||||
}
|
||||
return {
|
||||
annotationId: a.id,
|
||||
label: match?.label ?? a.nameFr ?? a.nameEn ?? a.id,
|
||||
root: match?.root ?? null,
|
||||
code: match?.code ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function triggerName(a: LegacyAnnotation, out: Anomaly[]) {
|
||||
if (a.nameFr && a.nameEn) return { fr: a.nameFr, en: a.nameEn }
|
||||
out.push({
|
||||
code: 'annotation.trigger.unnamed',
|
||||
level: 'informatif',
|
||||
subject: a.id,
|
||||
message:
|
||||
'Déclencheur de vue détail sans nom (name null), comme dans le SVG.',
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
function mapTrigger(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
out: Anomaly[],
|
||||
) {
|
||||
const annotation: AnnotationInput = {
|
||||
id: `${a.opensDetail}-trigger`,
|
||||
kind: 'detail_trigger',
|
||||
view_id: ctx.viewId,
|
||||
category_id: normaliseCategoryId(a.category ?? ''),
|
||||
laterality: laterality(a, out),
|
||||
geometry: a.geometry,
|
||||
name: triggerName(a, out),
|
||||
opens_view_id: a.opensDetail ?? '',
|
||||
}
|
||||
return { annotation, region: null }
|
||||
}
|
||||
|
||||
/** Missing labels fall back to the other language, never silently. */
|
||||
function observableName(a: LegacyAnnotation, out: Anomaly[]) {
|
||||
const fr = a.nameFr ?? a.nameEn ?? a.id
|
||||
if (a.nameFr === null) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.name_fr.missing',
|
||||
a.id,
|
||||
`data-anno-name-fr absent : nom FR repris de « ${fr} ».`,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (a.nameEn === null) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.name_en.missing',
|
||||
a.id,
|
||||
`data-anno-name-en absent : nom EN copié du FR « ${fr} », à traduire.`,
|
||||
),
|
||||
)
|
||||
}
|
||||
return { fr, en: a.nameEn ?? fr }
|
||||
}
|
||||
|
||||
function mapObservable(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
out: Anomaly[],
|
||||
) {
|
||||
const name = observableName(a, out)
|
||||
const zoneId = ctx.zoneByNames.get(zoneNameKey(name.fr, name.en)) ?? null
|
||||
if (zoneId === null) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.unmapped',
|
||||
a.id,
|
||||
'Annotation non reliée à une zone de constats.',
|
||||
),
|
||||
)
|
||||
}
|
||||
const region = regionOf(a, out)
|
||||
const annotation: AnnotationInput = {
|
||||
id: zoneId ?? slugify(name.en),
|
||||
kind: a.tagName === 'circle' ? 'point' : 'zone',
|
||||
view_id: ctx.viewId,
|
||||
category_id: normaliseCategoryId(a.category ?? ''),
|
||||
laterality: laterality(a, out),
|
||||
geometry: a.geometry,
|
||||
name,
|
||||
finding_zone_id: zoneId,
|
||||
vertebral_region_code: region?.code ?? null,
|
||||
}
|
||||
return { annotation, region }
|
||||
}
|
||||
|
||||
export function mapAnnotation(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
): MappedAnnotation {
|
||||
const anomalies: Anomaly[] = []
|
||||
const { annotation, region } = a.opensDetail
|
||||
? mapTrigger(a, ctx, anomalies)
|
||||
: mapObservable(a, ctx, anomalies)
|
||||
const row: AnnotationRow = {
|
||||
legacyId: a.id,
|
||||
newId: annotation.id,
|
||||
viewId: ctx.viewId,
|
||||
kind: annotation.kind,
|
||||
laterality: annotation.laterality,
|
||||
regionCode:
|
||||
annotation.kind === 'detail_trigger'
|
||||
? null
|
||||
: annotation.vertebral_region_code,
|
||||
findingZoneId:
|
||||
annotation.kind === 'detail_trigger' ? null : annotation.finding_zone_id,
|
||||
geometry: describeGeometry(annotation.geometry),
|
||||
}
|
||||
return { annotation, row, region, anomalies }
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { formatJson, formatMarkdown } from '../format'
|
||||
import { renderImportReport } from './report'
|
||||
import type { ImportResult } from './types'
|
||||
|
||||
/**
|
||||
* Text artifacts of the generated legacy-import folder, keyed by path
|
||||
* relative to supabase/seed/anatomical-sheets/equine/legacy-import/. This
|
||||
* folder is the baseline of the curation: it carries no SQL, the draft
|
||||
* folder holds the only seed.
|
||||
*/
|
||||
|
||||
/** Deterministic: same result in, same bytes out. */
|
||||
export async function renderArtifacts(
|
||||
result: ImportResult,
|
||||
): Promise<Record<string, string>> {
|
||||
return {
|
||||
'document.json': await formatJson(result.document),
|
||||
'legacy-id-map.json': await formatJson(result.legacyIdMap),
|
||||
'assets.json': await formatJson(result.assets),
|
||||
'IMPORT-REPORT.md': await formatMarkdown(renderImportReport(result)),
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* Lists every FR/EN text the importer writes itself (no source file holds
|
||||
* it), derived from the document so the list can never drift from what is
|
||||
* written. Annotation categories are reported by categories.ts.
|
||||
*/
|
||||
|
||||
export const AUTHORED_LABEL_CODE = 'label.authored'
|
||||
|
||||
function authored(subject: string, text: { fr?: string; en?: string }) {
|
||||
const parts = [
|
||||
text.fr === undefined ? null : `FR « ${text.fr} »`,
|
||||
text.en === undefined ? null : `EN « ${text.en} »`,
|
||||
].filter((part): part is string => part !== null)
|
||||
const anomaly: Anomaly = {
|
||||
code: AUTHORED_LABEL_CODE,
|
||||
level: 'a_valider',
|
||||
subject,
|
||||
message: `Libellé écrit par l'importateur : ${parts.join(', ')}.`,
|
||||
}
|
||||
return anomaly
|
||||
}
|
||||
|
||||
export function regionLabelSubject(code: string): string {
|
||||
return `vertebral_config.${code}`
|
||||
}
|
||||
|
||||
export function authoredLabelAnomalies(
|
||||
document: AnatomicalSheetDocumentInput,
|
||||
): Anomaly[] {
|
||||
return [
|
||||
authored('name', document.name),
|
||||
authored('description', document.description),
|
||||
...document.views.map((v) => authored(`views.${v.id}`, v.name)),
|
||||
...document.vertebral_config.regions.map((r) =>
|
||||
authored(regionLabelSubject(r.code), r.name),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import type { LegacyCatalog, LegacyNode } from './catalog'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* Catalog-wide findings that need a business decision or an explanation.
|
||||
* Nothing here alters the data: the importer copies the catalog verbatim
|
||||
* and these checks only describe what a reviewer must know.
|
||||
*/
|
||||
|
||||
const PREFIXED = /^(.+)-(dysfunctions|observations)$/
|
||||
|
||||
/** A prefixed category id that names another zone (sphenoid → ssb-…). */
|
||||
function foreignPrefixAnomalies(catalog: LegacyCatalog): Anomaly[] {
|
||||
const zoneIds = Object.keys(catalog.zones)
|
||||
const out: Anomaly[] = []
|
||||
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
|
||||
for (const category of zone.categories) {
|
||||
const match = PREFIXED.exec(category.id)
|
||||
if (!match || match[1] === zoneId || !zoneIds.includes(match[1]!))
|
||||
continue
|
||||
out.push({
|
||||
code: 'finding.category.foreign_prefix',
|
||||
level: 'a_valider',
|
||||
subject: `${zoneId}/${category.id}`,
|
||||
message:
|
||||
`Identifiant de catégorie dupliqué entre ${zoneId} et ${match[1]} ; ` +
|
||||
`${zoneId}-${match[2]} attendu ; décision ostéopathe requise. ` +
|
||||
'Importé tel quel (non renommé).',
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function childIds(category: LegacyNode): string {
|
||||
return (category.children ?? []).map((c) => c.id).join(', ')
|
||||
}
|
||||
|
||||
/** Same 'anamnesis' id everywhere, different content per zone family. */
|
||||
function anamnesisVariants(catalog: LegacyCatalog): Anomaly[] {
|
||||
const variants = new Map<string, string[]>()
|
||||
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
|
||||
const category = zone.categories.find((c) => c.id === 'anamnesis')
|
||||
if (!category) continue
|
||||
const key = childIds(category)
|
||||
variants.set(key, [...(variants.get(key) ?? []), zoneId])
|
||||
}
|
||||
return [...variants.entries()].map(([children, zones], index) => ({
|
||||
code: 'finding.anamnesis.variant',
|
||||
level: 'informatif',
|
||||
subject: `anamnesis variante ${index + 1}/${variants.size}`,
|
||||
message: `Zones ${zones.join(', ')} : ${children}.`,
|
||||
}))
|
||||
}
|
||||
|
||||
function collectIds(nodes: readonly LegacyNode[], into: Set<string>): void {
|
||||
for (const node of nodes) {
|
||||
into.add(node.id)
|
||||
collectIds(node.children ?? [], into)
|
||||
}
|
||||
}
|
||||
|
||||
/** Locale-independent order: artifacts must not vary with the process. */
|
||||
function byCodePoint(a: string, b: string): number {
|
||||
if (a === b) return 0
|
||||
return a < b ? -1 : 1
|
||||
}
|
||||
|
||||
/** Node ids are unique among siblings only; a finding is (zone, path). */
|
||||
function crossZoneDuplicates(catalog: LegacyCatalog): Anomaly[] {
|
||||
const zonesById = new Map<string, number>()
|
||||
for (const zone of Object.values(catalog.zones)) {
|
||||
const ids = new Set<string>()
|
||||
collectIds(zone.categories, ids)
|
||||
for (const id of ids) zonesById.set(id, (zonesById.get(id) ?? 0) + 1)
|
||||
}
|
||||
const shared = [...zonesById.entries()].filter(([, n]) => n > 1)
|
||||
const top = [...shared].sort((a, b) => b[1] - a[1] || byCodePoint(a[0], b[0]))
|
||||
return [
|
||||
{
|
||||
code: 'finding.id.shared_across_zones',
|
||||
level: 'informatif',
|
||||
subject: `${shared.length} identifiants`,
|
||||
message:
|
||||
'Identifiants de nœuds réutilisés entre zones (unicité entre frères ' +
|
||||
'seulement, adressage par zone + chemin). Les plus fréquents : ' +
|
||||
top
|
||||
.slice(0, 8)
|
||||
.map(([id, n]) => `${id} (${n})`)
|
||||
.join(', ') +
|
||||
'.',
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
export function catalogAnomalies(catalog: LegacyCatalog): Anomaly[] {
|
||||
return [
|
||||
...foreignPrefixAnomalies(catalog),
|
||||
...anamnesisVariants(catalog),
|
||||
...crossZoneDuplicates(catalog),
|
||||
]
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
import type {
|
||||
FindingCategoryKind,
|
||||
FindingNodeInput,
|
||||
LocalizedOptionalText,
|
||||
} from '@faunosteo/domain'
|
||||
import { isStableId, slugify } from './ids'
|
||||
import type { Anomaly, ZoneStats } from './types'
|
||||
|
||||
/**
|
||||
* Legacy findings catalog (pathologies.json, schema 2.0) → canonical
|
||||
* finding zones in the lean authoring form: optional keys are written only
|
||||
* when the source carries them, so the document stays as small as the
|
||||
* catalog and the parser fills the defaults.
|
||||
*/
|
||||
|
||||
export interface LegacyNode {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
description_fr?: string
|
||||
description_en?: string
|
||||
requires_vet_referral?: boolean
|
||||
/** Inline citations of the legacy format; none exist, see importer guard. */
|
||||
sources?: unknown[]
|
||||
children?: LegacyNode[]
|
||||
}
|
||||
|
||||
export interface LegacyZone {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
categories: LegacyNode[]
|
||||
}
|
||||
|
||||
export interface LegacyCatalog {
|
||||
schema_version: string
|
||||
scope_disclaimer?: string
|
||||
species?: { id: string; name_fr: string; name_en: string }
|
||||
zones: Record<string, LegacyZone>
|
||||
}
|
||||
|
||||
export interface CategoryInput {
|
||||
id: string
|
||||
kind: FindingCategoryKind
|
||||
name: { fr: string; en: string }
|
||||
description?: LocalizedOptionalText
|
||||
children: FindingNodeInput[]
|
||||
}
|
||||
|
||||
export interface ZoneInput {
|
||||
id: string
|
||||
name: { fr: string; en: string }
|
||||
categories: CategoryInput[]
|
||||
}
|
||||
|
||||
export interface MappedCatalog {
|
||||
zones: ZoneInput[]
|
||||
zoneStats: ZoneStats[]
|
||||
nodeIdMap: Record<string, string>
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
/** Mutable tallies of one catalog walk; never shared between runs. */
|
||||
interface WalkState {
|
||||
nodeIdMap: Record<string, string>
|
||||
anomalies: Anomaly[]
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
}
|
||||
|
||||
export function parseLegacyCatalog(json: string): LegacyCatalog {
|
||||
const catalog = JSON.parse(json) as LegacyCatalog
|
||||
if (typeof catalog?.zones !== 'object' || catalog.zones === null) {
|
||||
throw new Error('pathologies.json: "zones" object missing')
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
|
||||
export function categoryKind(categoryId: string): FindingCategoryKind {
|
||||
if (categoryId.endsWith('-dysfunctions')) return 'dysfunction'
|
||||
if (categoryId.endsWith('-observations')) return 'consultation_reason'
|
||||
if (categoryId === 'anamnesis') return 'anamnesis'
|
||||
return 'custom'
|
||||
}
|
||||
|
||||
function description(node: LegacyNode): LocalizedOptionalText | undefined {
|
||||
if (node.description_fr === undefined && node.description_en === undefined) {
|
||||
return undefined
|
||||
}
|
||||
const text: LocalizedOptionalText = {}
|
||||
if (node.description_fr !== undefined) text.fr = node.description_fr
|
||||
if (node.description_en !== undefined) text.en = node.description_en
|
||||
return text
|
||||
}
|
||||
|
||||
function stableNodeId(id: string, path: string[], state: WalkState): string {
|
||||
if (isStableId(id)) return id
|
||||
const next = slugify(id) || 'node'
|
||||
const key = [...path, id].join('/')
|
||||
state.nodeIdMap[key] = next
|
||||
state.anomalies.push({
|
||||
code: 'finding.id.slugified',
|
||||
level: 'a_valider',
|
||||
subject: key,
|
||||
message: `Identifiant hors motif stable, remplacé par « ${next} ».`,
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
function tallyNode(node: LegacyNode, state: WalkState): void {
|
||||
if (node.description_fr !== undefined && node.description_en === undefined) {
|
||||
state.missingDescriptionEn += 1
|
||||
}
|
||||
state.sources += node.sources?.length ?? 0
|
||||
}
|
||||
|
||||
function mapNode(
|
||||
node: LegacyNode,
|
||||
path: string[],
|
||||
state: WalkState,
|
||||
): FindingNodeInput {
|
||||
tallyNode(node, state)
|
||||
const id = stableNodeId(node.id, path, state)
|
||||
const out: FindingNodeInput = {
|
||||
id,
|
||||
name: { fr: node.name_fr, en: node.name_en },
|
||||
}
|
||||
const text = description(node)
|
||||
if (text) out.description = text
|
||||
if (node.requires_vet_referral === true) out.requires_vet_referral = true
|
||||
if (node.children) {
|
||||
out.children = node.children.map((c) =>
|
||||
mapNode(c, [...path, node.id], state),
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function mapCategory(
|
||||
zoneId: string,
|
||||
category: LegacyNode,
|
||||
state: WalkState,
|
||||
): CategoryInput {
|
||||
tallyNode(category, state)
|
||||
const kind = categoryKind(category.id)
|
||||
if (kind === 'custom') {
|
||||
state.anomalies.push({
|
||||
code: 'finding.category.kind_unknown',
|
||||
level: 'a_valider',
|
||||
subject: `${zoneId}/${category.id}`,
|
||||
message: 'Type de catégorie non reconnu, importé en « custom ».',
|
||||
})
|
||||
}
|
||||
const path = [zoneId, category.id]
|
||||
const out: CategoryInput = {
|
||||
id: stableNodeId(category.id, [zoneId], state),
|
||||
kind,
|
||||
name: { fr: category.name_fr, en: category.name_en },
|
||||
children: (category.children ?? []).map((c) => mapNode(c, path, state)),
|
||||
}
|
||||
const text = description(category)
|
||||
if (text) out.description = text
|
||||
return out
|
||||
}
|
||||
|
||||
/** Counts categories as nodes, as the audit does (792 = 78 + 714). */
|
||||
export function countTree(
|
||||
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
|
||||
): TreeCounts {
|
||||
let total = { nodes: 0, leaves: 0, vetReferrals: 0 }
|
||||
for (const node of nodes) {
|
||||
const children = node.children ?? []
|
||||
const sub = countTree(children)
|
||||
total = {
|
||||
nodes: total.nodes + 1 + sub.nodes,
|
||||
leaves: total.leaves + sub.leaves + (children.length === 0 ? 1 : 0),
|
||||
vetReferrals:
|
||||
total.vetReferrals +
|
||||
sub.vetReferrals +
|
||||
(node.requires_vet_referral ? 1 : 0),
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
function zoneStatsOf(zone: LegacyZone): ZoneStats {
|
||||
const counts = countTree(zone.categories)
|
||||
const categoryLeaves = zone.categories.filter((c) => !c.children?.length)
|
||||
return {
|
||||
zoneId: zone.id,
|
||||
nodes: counts.nodes,
|
||||
leaves: counts.leaves - categoryLeaves.length,
|
||||
vetReferrals: counts.vetReferrals,
|
||||
}
|
||||
}
|
||||
|
||||
export interface TreeCounts {
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
}
|
||||
|
||||
/** Throws when the output tree does not hold exactly the input tree. */
|
||||
export function assertNothingDropped(
|
||||
zoneId: string,
|
||||
before: TreeCounts,
|
||||
after: TreeCounts,
|
||||
): void {
|
||||
const keys = ['nodes', 'leaves', 'vetReferrals'] as const
|
||||
const diff = keys.filter((key) => before[key] !== after[key])
|
||||
if (diff.length === 0) return
|
||||
const detail = diff.map((k) => `${k} ${before[k]} in, ${after[k]} out`)
|
||||
throw new Error(`zone ${zoneId}: ${detail.join('; ')}`)
|
||||
}
|
||||
|
||||
function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput {
|
||||
if (zone.id !== key) throw new Error(`zone key ${key} ≠ id ${zone.id}`)
|
||||
const mapped: ZoneInput = {
|
||||
id: key,
|
||||
name: { fr: zone.name_fr, en: zone.name_en },
|
||||
categories: zone.categories.map((c) => mapCategory(key, c, state)),
|
||||
}
|
||||
assertNothingDropped(
|
||||
key,
|
||||
countTree(zone.categories),
|
||||
countTree(mapped.categories),
|
||||
)
|
||||
return mapped
|
||||
}
|
||||
|
||||
export function mapCatalog(catalog: LegacyCatalog): MappedCatalog {
|
||||
const state: WalkState = {
|
||||
nodeIdMap: {},
|
||||
anomalies: [],
|
||||
missingDescriptionEn: 0,
|
||||
sources: 0,
|
||||
}
|
||||
const entries = Object.entries(catalog.zones)
|
||||
return {
|
||||
zones: entries.map(([key, zone]) => mapZone(key, zone, state)),
|
||||
zoneStats: entries.map(([, zone]) => zoneStatsOf(zone)),
|
||||
nodeIdMap: state.nodeIdMap,
|
||||
missingDescriptionEn: state.missingDescriptionEn,
|
||||
sources: state.sources,
|
||||
anomalies: state.anomalies,
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import type { AnnotationCategory } from '@faunosteo/domain'
|
||||
import type { LegacyAnnotation } from './svg'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* SVG annotation categories → canonical categories. The legacy editor
|
||||
* slugified labels byte-wise, so accented letters became '-'
|
||||
* ("Charnières vertébrales" → charni-res-vert-brales). Those technical
|
||||
* slugs are normalised here and every change is reported; labels the
|
||||
* importer had to write are reported as "to validate".
|
||||
*/
|
||||
|
||||
/** Degraded legacy slug → real slug. Other slugs are kept as they are. */
|
||||
const SLUG_FIXES: Readonly<Record<string, string>> = {
|
||||
'charni-res-vert-brales': 'charnieres-vertebrales',
|
||||
'cadrans-du-cr-ne': 'cadrans-du-crane',
|
||||
}
|
||||
|
||||
/** Labels authored by the importer, keyed by normalised slug. */
|
||||
const LABELS: Readonly<Record<string, { fr: string; en: string }>> = {
|
||||
articulations: { fr: 'Articulations', en: 'Joints' },
|
||||
os: { fr: 'Os', en: 'Bones' },
|
||||
'zone-colonne': { fr: 'Zone colonne', en: 'Spine' },
|
||||
'charnieres-vertebrales': {
|
||||
fr: 'Charnières vertébrales',
|
||||
en: 'Vertebral hinges',
|
||||
},
|
||||
'cadrans-du-crane': { fr: 'Cadrans du crâne', en: 'Skull quadrants' },
|
||||
}
|
||||
|
||||
export interface MappedCategories {
|
||||
categories: AnnotationCategory[]
|
||||
idMap: Record<string, string>
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
export function normaliseCategoryId(legacy: string): string {
|
||||
return SLUG_FIXES[legacy] ?? legacy
|
||||
}
|
||||
|
||||
/**
|
||||
* data-anno-category-name is used only when it is a real label: in the
|
||||
* equine SVGs it repeats the slug ("articulations", "os"), so the readable
|
||||
* label of the table wins and the report says so.
|
||||
*/
|
||||
function frenchName(legacy: string, categoryName: string | null): string {
|
||||
const id = normaliseCategoryId(legacy)
|
||||
if (categoryName && categoryName !== legacy) return categoryName
|
||||
return LABELS[id]?.fr ?? id
|
||||
}
|
||||
|
||||
function labelAnomaly(id: string, fr: string, en: string): Anomaly {
|
||||
return {
|
||||
code: 'category.label.authored',
|
||||
level: 'a_valider',
|
||||
subject: id,
|
||||
message: `Libellé écrit par l'importateur : FR « ${fr} », EN « ${en} ».`,
|
||||
}
|
||||
}
|
||||
|
||||
function slugAnomaly(legacy: string, id: string): Anomaly {
|
||||
return {
|
||||
code: 'category.slug.normalised',
|
||||
level: 'a_valider',
|
||||
subject: legacy,
|
||||
message: `Slug technique dégradé (accents perdus) normalisé en « ${id} ».`,
|
||||
}
|
||||
}
|
||||
|
||||
function firstSeen(annotations: readonly LegacyAnnotation[]) {
|
||||
const seen = new Map<string, string | null>()
|
||||
for (const a of annotations) {
|
||||
if (a.category === null) continue
|
||||
if (!seen.has(a.category) || seen.get(a.category) === null) {
|
||||
seen.set(a.category, a.categoryName)
|
||||
}
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
/** Categories in order of first appearance across the SVGs. */
|
||||
export function mapCategories(
|
||||
annotations: readonly LegacyAnnotation[],
|
||||
): MappedCategories {
|
||||
const result: MappedCategories = { categories: [], idMap: {}, anomalies: [] }
|
||||
for (const [legacy, categoryName] of firstSeen(annotations)) {
|
||||
const id = normaliseCategoryId(legacy)
|
||||
const name = {
|
||||
fr: frenchName(legacy, categoryName),
|
||||
en: LABELS[id]?.en ?? id,
|
||||
}
|
||||
result.categories.push({ id, name, color: null })
|
||||
result.idMap[legacy] = id
|
||||
if (id !== legacy) result.anomalies.push(slugAnomaly(legacy, id))
|
||||
result.anomalies.push(labelAnomaly(id, name.fr, name.en))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { STABLE_ID_PATTERN } from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Deterministic identifiers. The importer must produce byte-identical
|
||||
* output across runs, so nothing here is random or time-based.
|
||||
*
|
||||
* UUIDs are name-based in the RFC 4122 version 5 style, with SHA-256 in
|
||||
* place of SHA-1: the first 16 bytes of sha256(<namespace string>), the
|
||||
* version nibble forced to 5 and the variant bits to 10xx. Assets use
|
||||
* 'faunosteo:asset:' + the file's sha256 (same bytes, same id), the sheet
|
||||
* uses 'faunosteo:sheet:<species>:v<n>'.
|
||||
*/
|
||||
|
||||
export function sha256Hex(data: Uint8Array | string): string {
|
||||
return createHash('sha256').update(data).digest('hex')
|
||||
}
|
||||
|
||||
export function deterministicUuid(name: string): string {
|
||||
const bytes = createHash('sha256').update(name).digest().subarray(0, 16)
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x50
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
const hex = bytes.toString('hex')
|
||||
return [
|
||||
hex.slice(0, 8),
|
||||
hex.slice(8, 12),
|
||||
hex.slice(12, 16),
|
||||
hex.slice(16, 20),
|
||||
hex.slice(20, 32),
|
||||
].join('-')
|
||||
}
|
||||
|
||||
export function assetIdFromSha256(fileSha256: string): string {
|
||||
return deterministicUuid(`faunosteo:asset:${fileSha256}`)
|
||||
}
|
||||
|
||||
export function sheetIdFor(speciesId: string, version: number): string {
|
||||
return deterministicUuid(`faunosteo:sheet:${speciesId}:v${version}`)
|
||||
}
|
||||
|
||||
/** Lowercase, accents stripped (NFD), every other run of chars → '-'. */
|
||||
export function slugify(label: string): string {
|
||||
return label
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 64)
|
||||
}
|
||||
|
||||
export function isStableId(id: string): boolean {
|
||||
return STABLE_ID_PATTERN.test(id)
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||
validateSheetDocument,
|
||||
type AnatomicalSheetDocumentInput,
|
||||
type SheetView,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
mapAnnotation,
|
||||
zoneNameKey,
|
||||
type AnnotationInput,
|
||||
type MappedAnnotation,
|
||||
} from './annotations'
|
||||
import {
|
||||
mapCatalog,
|
||||
parseLegacyCatalog,
|
||||
type LegacyCatalog,
|
||||
type MappedCatalog,
|
||||
} from './catalog'
|
||||
import { authoredLabelAnomalies } from './authored-labels'
|
||||
import { catalogAnomalies } from './catalog-checks'
|
||||
import { mapCategories, type MappedCategories } from './categories'
|
||||
import { assetIdFromSha256, sha256Hex, sheetIdFor } from './ids'
|
||||
import { parseAnnotatedSvg, type ParsedSvg } from './svg'
|
||||
import type {
|
||||
Anomaly,
|
||||
AssetRecord,
|
||||
EquineLegacyInput,
|
||||
ImportResult,
|
||||
ImportStats,
|
||||
LegacyIdMap,
|
||||
SourceDigest,
|
||||
SvgSource,
|
||||
} from './types'
|
||||
import {
|
||||
parseVertebralFormula,
|
||||
vertebralRegions,
|
||||
type LegacyVertebralFormula,
|
||||
} from './vertebrae'
|
||||
|
||||
/**
|
||||
* One-off, deterministic import of the historical equine assets into the
|
||||
* first canonical anatomical sheet document (Step 4b). The result is a
|
||||
* DRAFT for business review: every correction is listed in `anomalies`,
|
||||
* nothing is published.
|
||||
*/
|
||||
|
||||
export const EQUINE_SPECIES_ID = 'equine'
|
||||
export const EQUINE_SHEET_VERSION = 1
|
||||
export const MAIN_VIEW_ID = 'main'
|
||||
export const HEAD_VIEW_ID = 'head'
|
||||
|
||||
interface ParsedSources {
|
||||
assets: AssetRecord[]
|
||||
main: ParsedSvg
|
||||
head: ParsedSvg
|
||||
catalog: LegacyCatalog
|
||||
formula: LegacyVertebralFormula
|
||||
}
|
||||
|
||||
interface Mapped {
|
||||
annotations: MappedAnnotation[]
|
||||
categories: MappedCategories
|
||||
catalog: MappedCatalog
|
||||
}
|
||||
|
||||
function assetRecord(source: SvgSource): AssetRecord {
|
||||
const sha256 = sha256Hex(source.bytes)
|
||||
return {
|
||||
file: source.fileName,
|
||||
sha256,
|
||||
byte_size: source.bytes.byteLength,
|
||||
svg_asset_id: assetIdFromSha256(sha256),
|
||||
}
|
||||
}
|
||||
|
||||
function textDigest(file: string, text: string): SourceDigest {
|
||||
const bytes = new TextEncoder().encode(text)
|
||||
return { file, sha256: sha256Hex(bytes), byte_size: bytes.byteLength }
|
||||
}
|
||||
|
||||
function svgText(source: SvgSource): string {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(source.bytes)
|
||||
}
|
||||
|
||||
function parseSources(input: EquineLegacyInput): ParsedSources {
|
||||
return {
|
||||
assets: [assetRecord(input.mainSvg), assetRecord(input.headSvg)],
|
||||
main: parseAnnotatedSvg(svgText(input.mainSvg), input.mainSvg.fileName),
|
||||
head: parseAnnotatedSvg(svgText(input.headSvg), input.headSvg.fileName),
|
||||
catalog: parseLegacyCatalog(input.catalogJson),
|
||||
formula: parseVertebralFormula(input.vertebraeSource),
|
||||
}
|
||||
}
|
||||
|
||||
function mapSources(sources: ParsedSources): Mapped {
|
||||
const catalog = mapCatalog(sources.catalog)
|
||||
const zoneByNames = new Map(
|
||||
catalog.zones.map((z) => [zoneNameKey(z.name.fr, z.name.en), z.id]),
|
||||
)
|
||||
const views = [
|
||||
{ viewId: MAIN_VIEW_ID, svg: sources.main, file: sources.assets[0]! },
|
||||
{ viewId: HEAD_VIEW_ID, svg: sources.head, file: sources.assets[1]! },
|
||||
]
|
||||
const annotations = views.flatMap(({ viewId, svg, file }) =>
|
||||
svg.annotations.map((a) =>
|
||||
mapAnnotation(a, { viewId, fileName: file.file, zoneByNames }),
|
||||
),
|
||||
)
|
||||
const legacy = [...sources.main.annotations, ...sources.head.annotations]
|
||||
return { annotations, categories: mapCategories(legacy), catalog }
|
||||
}
|
||||
|
||||
function buildViews(assets: AssetRecord[]): SheetView[] {
|
||||
return [
|
||||
{
|
||||
id: MAIN_VIEW_ID,
|
||||
kind: 'main',
|
||||
name: { fr: 'Vue générale', en: 'Overview' },
|
||||
svg_asset_id: assets[0]!.svg_asset_id,
|
||||
view_box: null,
|
||||
},
|
||||
{
|
||||
id: HEAD_VIEW_ID,
|
||||
kind: 'detail',
|
||||
parent_view_id: MAIN_VIEW_ID,
|
||||
name: { fr: 'Tête', en: 'Head' },
|
||||
svg_asset_id: assets[1]!.svg_asset_id,
|
||||
view_box: null,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildDocument(
|
||||
sources: ParsedSources,
|
||||
mapped: Mapped,
|
||||
): AnatomicalSheetDocumentInput {
|
||||
const disclaimer = sources.catalog.scope_disclaimer
|
||||
return {
|
||||
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||
species_id: EQUINE_SPECIES_ID,
|
||||
name: { fr: 'Cheval', en: 'Horse' },
|
||||
description: {
|
||||
fr: 'Fiche anatomique officielle Faunosteo',
|
||||
en: 'Official Faunosteo anatomical sheet',
|
||||
},
|
||||
scope_disclaimer: disclaimer === undefined ? {} : { fr: disclaimer },
|
||||
attribution: {
|
||||
authors: ['Faunosteo'],
|
||||
license: null,
|
||||
notes:
|
||||
'Import des données historiques: Horse.svg, Horse_head.svg, ' +
|
||||
`pathologies.json (schema ${sources.catalog.schema_version})`,
|
||||
},
|
||||
vertebral_config: { regions: vertebralRegions(sources.formula) },
|
||||
references: [],
|
||||
categories: mapped.categories.categories,
|
||||
views: buildViews(sources.assets),
|
||||
annotations: mapped.annotations.map((m) => m.annotation),
|
||||
finding_zones: mapped.catalog.zones,
|
||||
}
|
||||
}
|
||||
|
||||
function buildIdMap(sources: ParsedSources, mapped: Mapped): LegacyIdMap {
|
||||
return {
|
||||
views: { [HEAD_VIEW_ID]: HEAD_VIEW_ID },
|
||||
annotations: Object.fromEntries(
|
||||
mapped.annotations.map((m) => [m.row.legacyId, m.row.newId]),
|
||||
),
|
||||
categories: mapped.categories.idMap,
|
||||
finding_nodes: mapped.catalog.nodeIdMap,
|
||||
assets: Object.fromEntries(
|
||||
sources.assets.map((a) => [a.file, a.svg_asset_id]),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function countBy(
|
||||
annotations: readonly AnnotationInput[],
|
||||
test: (a: AnnotationInput) => boolean,
|
||||
) {
|
||||
return annotations.filter(test).length
|
||||
}
|
||||
|
||||
function buildStats(
|
||||
sources: ParsedSources,
|
||||
document: AnatomicalSheetDocumentInput,
|
||||
mapped: Mapped,
|
||||
): ImportStats {
|
||||
const annotations = document.annotations
|
||||
const totals = mapped.catalog.zoneStats
|
||||
const sum = (key: 'nodes' | 'leaves' | 'vetReferrals') =>
|
||||
totals.reduce((acc, zone) => acc + zone[key], 0)
|
||||
return {
|
||||
legacyAnnotations:
|
||||
sources.main.annotations.length + sources.head.annotations.length,
|
||||
annotations: annotations.length,
|
||||
annotationsByView: {
|
||||
[MAIN_VIEW_ID]: countBy(annotations, (a) => a.view_id === MAIN_VIEW_ID),
|
||||
[HEAD_VIEW_ID]: countBy(annotations, (a) => a.view_id === HEAD_VIEW_ID),
|
||||
},
|
||||
linkedAnnotations: countBy(
|
||||
annotations,
|
||||
(a) => a.kind !== 'detail_trigger' && a.finding_zone_id !== null,
|
||||
),
|
||||
triggers: countBy(annotations, (a) => a.kind === 'detail_trigger'),
|
||||
views: document.views.length,
|
||||
vertebralAnnotations: countBy(
|
||||
annotations,
|
||||
(a) => a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
|
||||
),
|
||||
bilateral: countBy(annotations, (a) => a.laterality === 'bilateral'),
|
||||
findingZones: document.finding_zones.length,
|
||||
nodes: sum('nodes'),
|
||||
leaves: sum('leaves'),
|
||||
vetReferrals: sum('vetReferrals'),
|
||||
missingDescriptionEn: mapped.catalog.missingDescriptionEn,
|
||||
sources: mapped.catalog.sources,
|
||||
}
|
||||
}
|
||||
|
||||
/** Every data-anno-id read from the SVGs must be written once. */
|
||||
function assertAnnotationsKept(stats: ImportStats): void {
|
||||
if (stats.legacyAnnotations === stats.annotations) return
|
||||
throw new Error(
|
||||
`${stats.legacyAnnotations} annotations read, ${stats.annotations} written`,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The canonical document cites a shared references registry; the legacy
|
||||
* inline `sources` are not mapped. None exist today: refuse to drop any.
|
||||
*/
|
||||
function assertNoInlineSources(stats: ImportStats): void {
|
||||
if (stats.sources === 0) return
|
||||
throw new Error(
|
||||
`${stats.sources} inline legacy sources found: map them to references`,
|
||||
)
|
||||
}
|
||||
|
||||
function sourceAnomalies(
|
||||
sources: ParsedSources,
|
||||
stats: ImportStats,
|
||||
): Anomaly[] {
|
||||
const out: Anomaly[] = []
|
||||
const add = (code: string, subject: string, message: string) =>
|
||||
out.push({ code, level: 'a_valider', subject, message })
|
||||
if (stats.missingDescriptionEn > 0) {
|
||||
add(
|
||||
'finding.description_en.missing',
|
||||
'pathologies.json',
|
||||
`${stats.missingDescriptionEn} descriptions sans traduction anglaise ` +
|
||||
`(clé « en » absente, rien d'inventé).`,
|
||||
)
|
||||
}
|
||||
if (sources.catalog.scope_disclaimer !== undefined) {
|
||||
add(
|
||||
'document.scope_disclaimer.no_en',
|
||||
'scope_disclaimer',
|
||||
'Texte de périmètre légal en français seulement : traduction anglaise à rédiger.',
|
||||
)
|
||||
}
|
||||
const range = sources.formula.variesRange ?? 'non précisée'
|
||||
add(
|
||||
'vertebral.cd.capped',
|
||||
'Cd',
|
||||
`Caudales plafonnées à ${sources.formula.counts.Cd} pour le sélecteur, ` +
|
||||
`alors que l'espèce varie (${range}) selon le commentaire source.`,
|
||||
)
|
||||
if (stats.sources === 0) {
|
||||
add(
|
||||
'finding.sources.none',
|
||||
'pathologies.json',
|
||||
'Aucune source bibliographique sur les nœuds, alors que la règle ' +
|
||||
'projet en demande au moins une par entrée.',
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function informativeNotes(): Anomaly[] {
|
||||
return [
|
||||
{
|
||||
code: 'annotation.geometry.hitbox',
|
||||
level: 'informatif',
|
||||
subject: 'géométrie',
|
||||
message:
|
||||
'Géométrie lue sur le premier élément de chaque annotation (zone ' +
|
||||
"de clic), le marqueur visuel n'est pas importé.",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function collectAnomalies(
|
||||
sources: ParsedSources,
|
||||
mapped: Mapped,
|
||||
stats: ImportStats,
|
||||
document: AnatomicalSheetDocumentInput,
|
||||
): Anomaly[] {
|
||||
return [
|
||||
...authoredLabelAnomalies(document),
|
||||
...sources.main.anomalies,
|
||||
...sources.head.anomalies,
|
||||
...mapped.annotations.flatMap((m) => m.anomalies),
|
||||
...mapped.categories.anomalies,
|
||||
...mapped.catalog.anomalies,
|
||||
...catalogAnomalies(sources.catalog),
|
||||
...sourceAnomalies(sources, stats),
|
||||
...informativeNotes(),
|
||||
]
|
||||
}
|
||||
|
||||
export function importEquineLegacy(input: EquineLegacyInput): ImportResult {
|
||||
const sources = parseSources(input)
|
||||
const mapped = mapSources(sources)
|
||||
const document = buildDocument(sources, mapped)
|
||||
const parsed = AnatomicalSheetDocumentSchema.parse(document)
|
||||
const stats = buildStats(sources, document, mapped)
|
||||
assertAnnotationsKept(stats)
|
||||
assertNoInlineSources(stats)
|
||||
return {
|
||||
document,
|
||||
legacyIdMap: buildIdMap(sources, mapped),
|
||||
assets: sources.assets,
|
||||
sourceDigests: [
|
||||
textDigest('pathologies.json', input.catalogJson),
|
||||
textDigest('vertebrae.ts', input.vertebraeSource),
|
||||
],
|
||||
sheetId: sheetIdFor(EQUINE_SPECIES_ID, EQUINE_SHEET_VERSION),
|
||||
viewBoxes: {
|
||||
[MAIN_VIEW_ID]: sources.main.viewBox,
|
||||
[HEAD_VIEW_ID]: sources.head.viewBox,
|
||||
},
|
||||
annotationRows: mapped.annotations.map((m) => m.row),
|
||||
regionInferences: mapped.annotations.flatMap((m) =>
|
||||
m.region ? [m.region] : [],
|
||||
),
|
||||
zoneStats: mapped.catalog.zoneStats,
|
||||
stats,
|
||||
anomalies: collectAnomalies(sources, mapped, stats, document),
|
||||
issues: validateSheetDocument(parsed),
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
export { importEquineLegacy, HEAD_VIEW_ID, MAIN_VIEW_ID } from './importer'
|
||||
export { renderArtifacts } from './artifacts'
|
||||
export { renderImportReport } from './report'
|
||||
export {
|
||||
readEquineSources,
|
||||
EQUINE_CURATION_DIR,
|
||||
EQUINE_DRAFT_DIR,
|
||||
EQUINE_LEGACY_IMPORT_DIR,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
} from './sources'
|
||||
export {
|
||||
assetIdFromSha256,
|
||||
deterministicUuid,
|
||||
sha256Hex,
|
||||
sheetIdFor,
|
||||
slugify,
|
||||
} from './ids'
|
||||
export { inferRegionCode } from './regions'
|
||||
export type * from './types'
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Spine region inference from legacy labels, kept in the importer only
|
||||
* (ANATOMICAL_SHEET_MODEL.md §2: no label parsing at runtime). Same roots
|
||||
* and order as the legacy regionFromLabel (audit 07 §2): FR label first,
|
||||
* then EN, first root in test order wins.
|
||||
*/
|
||||
|
||||
const REGION_ROOTS: ReadonlyArray<{ code: string; roots: string[] }> = [
|
||||
{ code: 'C', roots: ['cervic'] },
|
||||
{ code: 'T', roots: ['thorac', 'dors'] },
|
||||
{ code: 'L', roots: ['lombair', 'lumbar'] },
|
||||
{ code: 'S', roots: ['sacral', 'sacre'] },
|
||||
{ code: 'Cd', roots: ['caudal', 'coccyg'] },
|
||||
]
|
||||
|
||||
export interface RegionMatch {
|
||||
code: string
|
||||
root: string
|
||||
label: string
|
||||
}
|
||||
|
||||
function normalise(label: string): string {
|
||||
return label.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||
}
|
||||
|
||||
function matchLabel(label: string): RegionMatch | null {
|
||||
const text = normalise(label)
|
||||
for (const { code, roots } of REGION_ROOTS) {
|
||||
const root = roots.find((candidate) => text.includes(candidate))
|
||||
if (root) return { code, root, label }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Null when neither label carries a known root: the caller reports it. */
|
||||
export function inferRegionCode(
|
||||
nameFr: string | null,
|
||||
nameEn: string | null,
|
||||
): RegionMatch | null {
|
||||
const labels = [nameFr, nameEn].filter((l): l is string => Boolean(l))
|
||||
for (const label of labels) {
|
||||
const match = matchLabel(label)
|
||||
if (match) return match
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
import { SHEET_DOCUMENT_SCHEMA_VERSION } from '@faunosteo/domain'
|
||||
import { AUTHORED_LABEL_CODE, regionLabelSubject } from './authored-labels'
|
||||
import { countTree } from './catalog'
|
||||
import { code, table } from '../markdown'
|
||||
import type { Anomaly, ImportResult } from './types'
|
||||
|
||||
/**
|
||||
* French Markdown import report, written for an osteopath (what to
|
||||
* validate) and for the developer (what was mapped and how). No dates and
|
||||
* no environment data: the report is a committed, byte-stable artifact.
|
||||
*/
|
||||
|
||||
function intro(result: ImportResult): string {
|
||||
return [
|
||||
"# Rapport d'import : fiche anatomique équine v1",
|
||||
'',
|
||||
'Généré par `pnpm import:equine` à partir des données historiques. ' +
|
||||
'Ne pas modifier à la main : relancer la commande.',
|
||||
'',
|
||||
`Statut : **brouillon** (version 1 en \`draft\`), jamais publié par ` +
|
||||
`le seed. Fiche \`${result.sheetId}\`, espèce \`${result.document.species_id}\`.`,
|
||||
'',
|
||||
'Les éléments de la section « Anomalies à valider » demandent une ' +
|
||||
'décision métier avant toute publication.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function sourcesSection(result: ImportResult): string {
|
||||
const assetRows = result.assets.map((a) => [
|
||||
code(a.file),
|
||||
a.byte_size,
|
||||
code(a.sha256),
|
||||
code(a.svg_asset_id),
|
||||
])
|
||||
const otherRows = result.sourceDigests.map((d) => [
|
||||
code(d.file),
|
||||
d.byte_size,
|
||||
code(d.sha256),
|
||||
'-',
|
||||
])
|
||||
const viewBoxes = Object.entries(result.viewBoxes).map(
|
||||
([view, box]) =>
|
||||
`- vue \`${view}\` : viewBox \`${box ?? 'absent'}\` (view_box du ` +
|
||||
`document laissé à null, le SVG porte le sien)`,
|
||||
)
|
||||
return [
|
||||
'## 1. Sources et empreintes',
|
||||
'',
|
||||
table(
|
||||
['Fichier', 'Octets', 'sha256', "Id d'asset"],
|
||||
[...assetRows, ...otherRows],
|
||||
),
|
||||
'',
|
||||
"Les ids d'asset sont dérivés du sha256 du fichier (UUID déterministe), " +
|
||||
"les deux SVG sont copiés à l'identique dans `assets/`.",
|
||||
'',
|
||||
...viewBoxes,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function volumesSection(result: ImportResult): string {
|
||||
const s = result.stats
|
||||
const out = countTree(
|
||||
result.document.finding_zones.flatMap((z) => z.categories),
|
||||
)
|
||||
const rows: Array<[string, number]> = [
|
||||
['Annotations', s.annotations],
|
||||
['dont vue `main` (Horse.svg)', s.annotationsByView.main ?? 0],
|
||||
['dont vue `head` (Horse_head.svg)', s.annotationsByView.head ?? 0],
|
||||
['Annotations reliées à une zone de constats', s.linkedAnnotations],
|
||||
['Déclencheurs de vue détail', s.triggers],
|
||||
['Vues', s.views],
|
||||
['Zones vertébrales avec code de région', s.vertebralAnnotations],
|
||||
['Annotations bilatérales', s.bilateral],
|
||||
['Zones de constats (catalogue)', s.findingZones],
|
||||
['Nœuds (catégories incluses)', s.nodes],
|
||||
['Feuilles', s.leaves],
|
||||
['Orientations vétérinaires', s.vetReferrals],
|
||||
]
|
||||
return [
|
||||
'## 2. Volumes',
|
||||
'',
|
||||
table(['Mesure', 'Valeur'], rows),
|
||||
'',
|
||||
'Contrôle entrée = sortie, compté des deux côtés (sources lues, ' +
|
||||
"document écrit). L'importateur s'arrête au moindre écart :",
|
||||
'',
|
||||
table(
|
||||
['Contrôle', 'Lu (sources)', 'Écrit (document)'],
|
||||
[
|
||||
[
|
||||
'Annotations (data-anno-id distincts)',
|
||||
s.legacyAnnotations,
|
||||
s.annotations,
|
||||
],
|
||||
['Nœuds (catégories incluses)', s.nodes, out.nodes],
|
||||
['Feuilles', s.leaves, out.leaves],
|
||||
['Orientations vétérinaires', s.vetReferrals, out.vetReferrals],
|
||||
],
|
||||
),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function annotationsSection(result: ImportResult): string {
|
||||
const rows = result.annotationRows.map((r) => [
|
||||
code(r.legacyId),
|
||||
code(r.newId),
|
||||
r.viewId,
|
||||
r.kind,
|
||||
r.laterality,
|
||||
r.regionCode,
|
||||
r.findingZoneId === null ? '-' : code(r.findingZoneId),
|
||||
r.geometry,
|
||||
])
|
||||
return [
|
||||
'## 3. Annotations',
|
||||
'',
|
||||
table(
|
||||
[
|
||||
'Id historique',
|
||||
'Nouvel id',
|
||||
'Vue',
|
||||
'Type',
|
||||
'Latéralité',
|
||||
'Région',
|
||||
'Zone de constats',
|
||||
'Géométrie',
|
||||
],
|
||||
rows,
|
||||
),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function categoriesSection(result: ImportResult): string {
|
||||
const legacyOf = Object.fromEntries(
|
||||
Object.entries(result.legacyIdMap.categories).map(([legacy, id]) => [
|
||||
id,
|
||||
legacy,
|
||||
]),
|
||||
)
|
||||
const authored = new Set(
|
||||
result.anomalies
|
||||
.filter((a) => a.code === 'category.label.authored')
|
||||
.map((a) => a.subject),
|
||||
)
|
||||
const rows = result.document.categories.map((c) => [
|
||||
code(legacyOf[c.id] ?? c.id),
|
||||
code(c.id),
|
||||
c.name.fr,
|
||||
c.name.en,
|
||||
authored.has(c.id) ? 'importateur, à valider' : 'SVG',
|
||||
])
|
||||
return [
|
||||
"## 4. Catégories d'annotation",
|
||||
'',
|
||||
table(
|
||||
['Id SVG', 'Id', 'Libellé FR', 'Libellé EN', 'Origine du libellé'],
|
||||
rows,
|
||||
),
|
||||
'',
|
||||
"Couleur : `null` partout (les couleurs du SVG restent dans l'asset). " +
|
||||
'Dans les SVG, `data-anno-category-name` répète le slug (`articulations`, ' +
|
||||
"`os`) : ce n'est pas un libellé, le libellé lisible de la table " +
|
||||
"de l'importateur est utilisé.",
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function vertebralSection(result: ImportResult): string {
|
||||
const authored = new Set(
|
||||
result.anomalies
|
||||
.filter((a) => a.code === AUTHORED_LABEL_CODE)
|
||||
.map((a) => a.subject),
|
||||
)
|
||||
const regions = result.document.vertebral_config.regions.map((r) => [
|
||||
code(r.code),
|
||||
r.name.fr,
|
||||
r.name.en,
|
||||
r.count,
|
||||
authored.has(regionLabelSubject(r.code))
|
||||
? 'importateur, à valider'
|
||||
: 'source',
|
||||
])
|
||||
const inferences = result.regionInferences.map((i) => [
|
||||
code(result.legacyIdMap.annotations[i.annotationId] ?? i.annotationId),
|
||||
i.label,
|
||||
i.root === null ? '-' : code(i.root),
|
||||
code(i.code),
|
||||
])
|
||||
return [
|
||||
'## 5. Configuration vertébrale',
|
||||
'',
|
||||
table(
|
||||
['Code', 'Nom FR', 'Nom EN', 'Vertèbres', 'Origine du libellé'],
|
||||
regions,
|
||||
),
|
||||
'',
|
||||
'Nombres de vertèbres : `vertebrae.ts`. Noms de région : écrits par ' +
|
||||
"l'importateur (aucune source ne les porte).",
|
||||
'',
|
||||
'Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, ' +
|
||||
'`lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis ' +
|
||||
'EN). Déduction faite une fois ici, le document porte le code :',
|
||||
'',
|
||||
table(['Annotation', 'Libellé lu', 'Racine', 'Code'], inferences),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function findingsSection(result: ImportResult): string {
|
||||
const names = new Map(
|
||||
result.document.finding_zones.map((z) => [z.id, z.name.fr]),
|
||||
)
|
||||
const rows = result.zoneStats.map((z) => [
|
||||
code(z.zoneId),
|
||||
names.get(z.zoneId) ?? '-',
|
||||
z.nodes,
|
||||
z.leaves,
|
||||
z.vetReferrals,
|
||||
])
|
||||
const s = result.stats
|
||||
rows.push(['**Total**', '', s.nodes, s.leaves, s.vetReferrals])
|
||||
return [
|
||||
'## 6. Arbre de constats par zone',
|
||||
'',
|
||||
'Copie fidèle du catalogue : ids, libellés, descriptions présentes, ' +
|
||||
'orientations vétérinaires et sources. Ordre des zones et des catégories ' +
|
||||
'conservé. Nœuds = catégories incluses.',
|
||||
'',
|
||||
table(['Zone', 'Nom', 'Nœuds', 'Feuilles', 'Orientations vét.'], rows),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function anomalyRows(anomalies: readonly Anomaly[]) {
|
||||
return anomalies.map((a) => [code(a.code), a.subject, a.message])
|
||||
}
|
||||
|
||||
function anomaliesSection(result: ImportResult): string {
|
||||
const toValidate = result.anomalies.filter((a) => a.level === 'a_valider')
|
||||
const informative = result.anomalies.filter((a) => a.level === 'informatif')
|
||||
return [
|
||||
'## 7. Anomalies à valider',
|
||||
'',
|
||||
`${toValidate.length} points demandent une décision, ${informative.length} sont informatifs.`,
|
||||
'',
|
||||
'### À valider',
|
||||
'',
|
||||
table(['Code', 'Objet', 'Détail'], anomalyRows(toValidate)),
|
||||
'',
|
||||
'### Informatif',
|
||||
'',
|
||||
table(['Code', 'Objet', 'Détail'], anomalyRows(informative)),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** Source keys the document does not carry, and where they live now. */
|
||||
const NOT_CARRIED_OVER = [
|
||||
'`schema_version` du catalogue (`2.0`) : version du format historique, ' +
|
||||
`remplacée par \`schema_version: ${SHEET_DOCUMENT_SCHEMA_VERSION}\` du document canonique ; la valeur ` +
|
||||
"d'origine est citée dans `attribution.notes`.",
|
||||
'bloc `species` du catalogue (`equine`, Cheval / Horse) : porté par ' +
|
||||
'`species_id` du document et par la table `public.species` ; le nom ' +
|
||||
'de la fiche est écrit séparément (voir anomalies `label.authored`).',
|
||||
'second élément graphique de chaque annotation (marqueur visuel) : ' +
|
||||
"reste dans l'asset SVG copié à l'identique, le document ne garde que " +
|
||||
'la zone de clic.',
|
||||
'`data-anno-category-name` : répète le slug technique (`articulations`, ' +
|
||||
"`os`), ce n'est pas un libellé ; le libellé de catégorie vient de la " +
|
||||
"table de l'importateur (section 4).",
|
||||
]
|
||||
|
||||
function notImportedSection(result: ImportResult): string {
|
||||
const dropped = result.annotationRows.filter((r) => r.geometry === 'aucune')
|
||||
const lines =
|
||||
dropped.length === 0
|
||||
? ['Aucune donnée métier écartée.']
|
||||
: dropped.map(
|
||||
(r) => `- géométrie de \`${r.legacyId}\` (forme non prise en charge)`,
|
||||
)
|
||||
return [
|
||||
'## 8. Données non importées',
|
||||
'',
|
||||
...lines,
|
||||
'',
|
||||
'Non repris par construction :',
|
||||
'',
|
||||
...NOT_CARRIED_OVER.map((line) => `- ${line}`),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function validationSection(result: ImportResult): string {
|
||||
const errors = result.issues.filter((i) => i.severity === 'error')
|
||||
const warnings = result.issues.filter((i) => i.severity === 'warning')
|
||||
const rows = result.issues.map((i) => [
|
||||
i.severity,
|
||||
code(i.code),
|
||||
code(i.path),
|
||||
i.message,
|
||||
])
|
||||
return [
|
||||
'## 9. Résultat de validation',
|
||||
'',
|
||||
'- Forme (`AnatomicalSheetDocumentSchema`) : conforme.',
|
||||
`- Intégrité (\`validateSheetDocument\`) : ${errors.length} erreur(s), ` +
|
||||
`${warnings.length} avertissement(s).`,
|
||||
...(rows.length
|
||||
? ['', table(['Gravité', 'Code', 'Chemin', 'Message'], rows)]
|
||||
: []),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function renderImportReport(result: ImportResult): string {
|
||||
return (
|
||||
[
|
||||
intro(result),
|
||||
sourcesSection(result),
|
||||
volumesSection(result),
|
||||
annotationsSection(result),
|
||||
categoriesSection(result),
|
||||
vertebralSection(result),
|
||||
findingsSection(result),
|
||||
anomaliesSection(result),
|
||||
notImportedSection(result),
|
||||
validationSection(result),
|
||||
].join('\n\n') + '\n'
|
||||
)
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import type { EquineLegacyInput } from './types'
|
||||
|
||||
/**
|
||||
* Locations of the legacy equine sources and of the seed folders, all
|
||||
* relative to the repository root. Shared by the CLI and the golden tests.
|
||||
*/
|
||||
|
||||
export const EQUINE_SOURCE_PATHS = {
|
||||
mainSvg: 'supabase/seed/anatomical-sheets/equine/legacy-sources/Horse.svg',
|
||||
headSvg: 'supabase/seed/anatomical-sheets/equine/legacy-sources/Horse_head.svg',
|
||||
catalog: 'supabase/seed/anatomical-sheets/equine/legacy-sources/pathologies.json',
|
||||
vertebrae: 'supabase/seed/anatomical-sheets/equine/legacy-sources/vertebrae.ts',
|
||||
} as const
|
||||
|
||||
const EQUINE_SEED_ROOT = 'supabase/seed/anatomical-sheets/equine'
|
||||
|
||||
/** GENERATED baseline: the legacy import, untouched by curation. */
|
||||
export const EQUINE_LEGACY_IMPORT_DIR = `${EQUINE_SEED_ROOT}/legacy-import`
|
||||
|
||||
/** AUTHORED inputs: changes.json and references.json, never generated. */
|
||||
export const EQUINE_CURATION_DIR = `${EQUINE_SEED_ROOT}/curation`
|
||||
|
||||
/** GENERATED working revision: curated document, cleaned asset, seed. */
|
||||
export const EQUINE_DRAFT_DIR = `${EQUINE_SEED_ROOT}/draft`
|
||||
|
||||
function fileName(path: string): string {
|
||||
return path.slice(path.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
export async function readEquineSources(
|
||||
repoRoot: string,
|
||||
): Promise<EquineLegacyInput> {
|
||||
const read = (path: string) => readFile(join(repoRoot, path))
|
||||
const [main, head, catalog, vertebrae] = await Promise.all([
|
||||
read(EQUINE_SOURCE_PATHS.mainSvg),
|
||||
read(EQUINE_SOURCE_PATHS.headSvg),
|
||||
read(EQUINE_SOURCE_PATHS.catalog),
|
||||
read(EQUINE_SOURCE_PATHS.vertebrae),
|
||||
])
|
||||
return {
|
||||
mainSvg: {
|
||||
fileName: fileName(EQUINE_SOURCE_PATHS.mainSvg),
|
||||
bytes: new Uint8Array(main),
|
||||
},
|
||||
headSvg: {
|
||||
fileName: fileName(EQUINE_SOURCE_PATHS.headSvg),
|
||||
bytes: new Uint8Array(head),
|
||||
},
|
||||
catalogJson: catalog.toString('utf8'),
|
||||
vertebraeSource: vertebrae.toString('utf8'),
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { DOMParser, type Element } from '@xmldom/xmldom'
|
||||
import type { Geometry } from '@faunosteo/domain'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* Reads the annotation layer of a legacy SVG (data-anno-* attributes of the
|
||||
* historical files under supabase/seed/anatomical-sheets/equine/legacy-sources).
|
||||
* Each annotation is drawn by one or two elements sharing a data-anno-id
|
||||
* (hitbox first, visual marker second); the importer keeps one record per
|
||||
* id, attributes and geometry taken from the first element.
|
||||
*/
|
||||
|
||||
export interface LegacyAnnotation {
|
||||
id: string
|
||||
tagName: string
|
||||
elementCount: number
|
||||
nameFr: string | null
|
||||
nameEn: string | null
|
||||
category: string | null
|
||||
categoryName: string | null
|
||||
lateral: string | null
|
||||
special: string | null
|
||||
opensDetail: string | null
|
||||
geometry: Geometry | null
|
||||
}
|
||||
|
||||
export interface ParsedSvg {
|
||||
viewBox: string | null
|
||||
annotations: LegacyAnnotation[]
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
function attr(element: Element, name: string): string | null {
|
||||
return element.hasAttribute(name) ? element.getAttribute(name) : null
|
||||
}
|
||||
|
||||
function parsePoints(raw: string): Array<[number, number]> {
|
||||
const numbers = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const pairs: Array<[number, number]> = []
|
||||
for (let i = 0; i + 1 < numbers.length; i += 2) {
|
||||
pairs.push([numbers[i]!, numbers[i + 1]!])
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
/** Circle and polygon are the only shapes the legacy editor produces. */
|
||||
function readGeometry(element: Element): Geometry | null {
|
||||
if (element.tagName === 'circle') {
|
||||
return {
|
||||
type: 'circle',
|
||||
cx: Number(attr(element, 'cx')),
|
||||
cy: Number(attr(element, 'cy')),
|
||||
r: Number(attr(element, 'r')),
|
||||
}
|
||||
}
|
||||
if (element.tagName === 'polygon') {
|
||||
return {
|
||||
type: 'polygon',
|
||||
points: parsePoints(attr(element, 'points') ?? ''),
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function readAnnotation(element: Element, id: string): LegacyAnnotation {
|
||||
return {
|
||||
id,
|
||||
tagName: element.tagName,
|
||||
elementCount: 1,
|
||||
nameFr: attr(element, 'data-anno-name-fr'),
|
||||
nameEn: attr(element, 'data-anno-name-en'),
|
||||
category: attr(element, 'data-anno-category'),
|
||||
categoryName: attr(element, 'data-anno-category-name'),
|
||||
lateral: attr(element, 'data-anno-lateral'),
|
||||
special: attr(element, 'data-anno-special'),
|
||||
opensDetail: attr(element, 'data-anno-opens-detail'),
|
||||
geometry: readGeometry(element),
|
||||
}
|
||||
}
|
||||
|
||||
function geometryAnomaly(fileName: string, a: LegacyAnnotation): Anomaly {
|
||||
return {
|
||||
code: 'svg.geometry.unsupported',
|
||||
level: 'a_valider',
|
||||
subject: `${fileName} ${a.id}`,
|
||||
message: `Élément <${a.tagName}> non pris en charge : géométrie non importée (null).`,
|
||||
}
|
||||
}
|
||||
|
||||
/** Document order is kept: it is the order of the annotations table. */
|
||||
export function parseAnnotatedSvg(text: string, fileName: string): ParsedSvg {
|
||||
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
const byId = new Map<string, LegacyAnnotation>()
|
||||
const elements = doc.getElementsByTagName('*')
|
||||
for (let i = 0; i < elements.length; i += 1) {
|
||||
const element = elements.item(i)!
|
||||
const id = attr(element, 'data-anno-id')
|
||||
if (id === null) continue
|
||||
const known = byId.get(id)
|
||||
if (known) known.elementCount += 1
|
||||
else byId.set(id, readAnnotation(element, id))
|
||||
}
|
||||
const annotations = [...byId.values()]
|
||||
const anomalies = annotations
|
||||
.filter((a) => a.geometry === null)
|
||||
.map((a) => geometryAnomaly(fileName, a))
|
||||
return {
|
||||
viewBox: root ? attr(root, 'viewBox') : null,
|
||||
annotations,
|
||||
anomalies,
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
SheetIssue,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Shared shapes of the legacy importer. Anomalies are never silent: every
|
||||
* correction or gap the importer meets lands in the import report so an
|
||||
* osteopath can validate it before the draft is published.
|
||||
*/
|
||||
|
||||
/** 'a_valider' needs a business decision; 'informatif' only explains. */
|
||||
export type AnomalyLevel = 'a_valider' | 'informatif'
|
||||
|
||||
export interface Anomaly {
|
||||
code: string
|
||||
level: AnomalyLevel
|
||||
subject: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** One SVG file handed to the importer, bytes untouched. */
|
||||
export interface SvgSource {
|
||||
fileName: string
|
||||
bytes: Uint8Array
|
||||
}
|
||||
|
||||
/** The four legacy sources, read by the caller (CLI or tests). */
|
||||
export interface EquineLegacyInput {
|
||||
mainSvg: SvgSource
|
||||
headSvg: SvgSource
|
||||
catalogJson: string
|
||||
vertebraeSource: string
|
||||
}
|
||||
|
||||
export interface AssetRecord {
|
||||
file: string
|
||||
sha256: string
|
||||
byte_size: number
|
||||
svg_asset_id: string
|
||||
}
|
||||
|
||||
export interface LegacyIdMap {
|
||||
views: Record<string, string>
|
||||
annotations: Record<string, string>
|
||||
categories: Record<string, string>
|
||||
finding_nodes: Record<string, string>
|
||||
assets: Record<string, string>
|
||||
}
|
||||
|
||||
/** How the region code of a spine annotation was inferred from labels. */
|
||||
export interface RegionInference {
|
||||
annotationId: string
|
||||
label: string
|
||||
root: string | null
|
||||
code: string | null
|
||||
}
|
||||
|
||||
export interface AnnotationRow {
|
||||
legacyId: string
|
||||
newId: string
|
||||
viewId: string
|
||||
kind: string
|
||||
laterality: string
|
||||
regionCode: string | null
|
||||
findingZoneId: string | null
|
||||
geometry: string
|
||||
}
|
||||
|
||||
export interface ZoneStats {
|
||||
zoneId: string
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
}
|
||||
|
||||
/** Digest of a non-asset source, shown in the report. */
|
||||
export interface SourceDigest {
|
||||
file: string
|
||||
sha256: string
|
||||
byte_size: number
|
||||
}
|
||||
|
||||
export interface ImportStats {
|
||||
legacyAnnotations: number
|
||||
annotations: number
|
||||
annotationsByView: Record<string, number>
|
||||
linkedAnnotations: number
|
||||
triggers: number
|
||||
views: number
|
||||
vertebralAnnotations: number
|
||||
bilateral: number
|
||||
findingZones: number
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
}
|
||||
|
||||
/** Everything the report and the seed need, computed once. */
|
||||
export interface ImportResult {
|
||||
document: AnatomicalSheetDocumentInput
|
||||
legacyIdMap: LegacyIdMap
|
||||
assets: AssetRecord[]
|
||||
sourceDigests: SourceDigest[]
|
||||
sheetId: string
|
||||
viewBoxes: Record<string, string | null>
|
||||
annotationRows: AnnotationRow[]
|
||||
regionInferences: RegionInference[]
|
||||
zoneStats: ZoneStats[]
|
||||
stats: ImportStats
|
||||
anomalies: Anomaly[]
|
||||
issues: SheetIssue[]
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Reads the legacy vertebral formula from the source text of
|
||||
* apps/app/src/domain/species/equine/vertebrae.ts. The file is parsed as
|
||||
* text, not imported: it depends on the app's '@/…' alias, which this
|
||||
* package does not resolve.
|
||||
*/
|
||||
|
||||
export interface LegacyVertebralFormula {
|
||||
counts: Record<string, number>
|
||||
/** "varies A–B" range from the source comment, when stated. */
|
||||
variesRange: string | null
|
||||
}
|
||||
|
||||
const REGION_ORDER = ['C', 'T', 'L', 'S', 'Cd'] as const
|
||||
|
||||
export function parseVertebralFormula(source: string): LegacyVertebralFormula {
|
||||
const body = /=\s*\{([^}]*)\}/.exec(source)?.[1]
|
||||
if (!body) throw new Error('vertebrae.ts: formula object not found')
|
||||
const counts: Record<string, number> = {}
|
||||
for (const match of body.matchAll(/(\w+)\s*:\s*(\d+)/g)) {
|
||||
counts[match[1]!] = Number(match[2])
|
||||
}
|
||||
for (const code of REGION_ORDER) {
|
||||
if (!(code in counts))
|
||||
throw new Error(`vertebrae.ts: region ${code} missing`)
|
||||
}
|
||||
const range = /varies\s+(\d+)\s*[–-]\s*(\d+)/.exec(source)
|
||||
return {
|
||||
counts,
|
||||
variesRange: range ? `${range[1]}–${range[2]}` : null,
|
||||
}
|
||||
}
|
||||
|
||||
export const VERTEBRAL_REGION_ORDER = REGION_ORDER
|
||||
|
||||
const REGION_NAMES: Readonly<Record<string, { fr: string; en: string }>> = {
|
||||
C: { fr: 'Cervicales', en: 'Cervical' },
|
||||
T: { fr: 'Thoraciques', en: 'Thoracic' },
|
||||
L: { fr: 'Lombaires', en: 'Lumbar' },
|
||||
S: { fr: 'Sacrales', en: 'Sacral' },
|
||||
Cd: { fr: 'Caudales', en: 'Caudal' },
|
||||
}
|
||||
|
||||
/** Ordered C → Cd, the order of the legacy picker tabs. */
|
||||
export function vertebralRegions(formula: LegacyVertebralFormula) {
|
||||
return REGION_ORDER.map((code) => ({
|
||||
code,
|
||||
name: { ...REGION_NAMES[code]! },
|
||||
count: formula.counts[code]!,
|
||||
}))
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/**
|
||||
* Markdown building blocks of the generated French reports. Cells are
|
||||
* escaped so a pipe or a newline in data never breaks a table.
|
||||
*/
|
||||
|
||||
export function cell(value: string | number | null): string {
|
||||
if (value === null) return '-'
|
||||
return String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ')
|
||||
}
|
||||
|
||||
export function table(
|
||||
head: string[],
|
||||
rows: Array<Array<string | number | null>>,
|
||||
): string {
|
||||
const lines = [head, head.map(() => '---'), ...rows.map((r) => r.map(cell))]
|
||||
return lines.map((line) => `| ${line.join(' | ')} |`).join('\n')
|
||||
}
|
||||
|
||||
export function code(value: string | null): string {
|
||||
return value === null ? '-' : `\`${value}\``
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
|
||||
import {
|
||||
createLayerElement,
|
||||
SVG_NS,
|
||||
type MinimalDocument,
|
||||
type MinimalElement,
|
||||
type MinimalNode,
|
||||
} from './dom'
|
||||
import { renderAnnotationLayer, viewBoxOf, type LayerElement } from './layer'
|
||||
|
||||
/**
|
||||
* Composes the drawing of one view: the parsed asset framed on the view's
|
||||
* box plus the annotation layer rendered from the document. With a
|
||||
* `highlight`, the layer keeps only the selected annotations, styled for
|
||||
* print (legacy picture: accent fill, halo on the main view, no data
|
||||
* attributes). Works on any DOM Level 2 implementation (a Node parser or
|
||||
* the browser DOM): the caller parses and serialises.
|
||||
*/
|
||||
|
||||
export const HALO_FILTER_ID = 'osteo-halo'
|
||||
export const HIGHLIGHT_FILL = '#b85a3f'
|
||||
export const HIGHLIGHT_FILL_OPACITY = '0.85'
|
||||
|
||||
/** DOM Level 2 surface the composer needs on the `<svg>` root. */
|
||||
export interface ComposeElement extends MinimalElement {
|
||||
readonly ownerDocument: MinimalDocument | null
|
||||
readonly firstChild: MinimalNode | null
|
||||
getAttribute(name: string): string | null
|
||||
removeAttribute(name: string): void
|
||||
insertBefore(node: MinimalNode, reference: MinimalNode | null): unknown
|
||||
getElementsByTagName(tag: string): ComposeElementList
|
||||
}
|
||||
|
||||
export interface ComposeElementList {
|
||||
readonly length: number
|
||||
item(index: number): ComposeElement | null
|
||||
}
|
||||
|
||||
export interface ComposeHighlight {
|
||||
/** Annotation ids kept on the layer; every other marker is dropped. */
|
||||
annotationIds: ReadonlySet<string>
|
||||
/** Wrap the kept markers in the `osteo-halo` filter (main view). */
|
||||
halo: boolean
|
||||
}
|
||||
|
||||
export interface ComposeInput<Root extends ComposeElement = ComposeElement> {
|
||||
root: Root
|
||||
document: AnatomicalSheetDocumentInput
|
||||
viewId: string
|
||||
highlight?: ComposeHighlight
|
||||
}
|
||||
|
||||
/** Frames `root` on the view, appends the layer `<g>` last, returns `root`. */
|
||||
export function composeViewSvg<Root extends ComposeElement>(
|
||||
input: ComposeInput<Root>,
|
||||
): Root {
|
||||
const { root, document, viewId, highlight } = input
|
||||
const view = document.views.find((v) => v.id === viewId)
|
||||
if (!view) throw new Error(`unknown view "${viewId}"`)
|
||||
const box = viewBoxOf(view)
|
||||
if (box) root.setAttribute('viewBox', box)
|
||||
root.removeAttribute('width')
|
||||
root.removeAttribute('height')
|
||||
if (highlight?.halo) ensureHaloFilter(root)
|
||||
const rendered = renderAnnotationLayer({ document, viewId })
|
||||
const layer = highlight ? highlightLayer(rendered, highlight) : rendered
|
||||
root.appendChild(createLayerElement(documentOf(root), layer))
|
||||
return root
|
||||
}
|
||||
|
||||
/** Typed nullable by the DOM; an element taken from a parsed document has one. */
|
||||
function documentOf(root: ComposeElement): MinimalDocument {
|
||||
if (!root.ownerDocument) throw new Error('root has no owner document')
|
||||
return root.ownerDocument
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer reduced to the selected annotations (both elements of a point),
|
||||
* each with the accent fill and, when asked, the halo filter. No `data-*`
|
||||
* attribute survives: the result is a picture, not an interactive layer.
|
||||
*/
|
||||
export function highlightLayer(
|
||||
layer: LayerElement,
|
||||
highlight: ComposeHighlight,
|
||||
): LayerElement {
|
||||
const children = layer.children
|
||||
.filter((child) =>
|
||||
highlight.annotationIds.has(child.attrs['data-anno-id'] ?? ''),
|
||||
)
|
||||
.map((child) => highlightElement(child, highlight.halo))
|
||||
return { ...layer, attrs: withoutDataAttrs(layer.attrs), children }
|
||||
}
|
||||
|
||||
function highlightElement(node: LayerElement, halo: boolean): LayerElement {
|
||||
const attrs: Record<string, string> = {
|
||||
...withoutDataAttrs(node.attrs),
|
||||
fill: HIGHLIGHT_FILL,
|
||||
'fill-opacity': HIGHLIGHT_FILL_OPACITY,
|
||||
}
|
||||
if (halo) attrs.filter = `url(#${HALO_FILTER_ID})`
|
||||
return { ...node, attrs }
|
||||
}
|
||||
|
||||
function withoutDataAttrs(
|
||||
attrs: Record<string, string>,
|
||||
): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(attrs).filter(([name]) => !name.startsWith('data-')),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the Gaussian-blur "halo" filter so the highlighted markers stay
|
||||
* visible on the whole-animal view once rasterised at print scale. One
|
||||
* filter per root: a second call finds it and leaves the tree alone.
|
||||
*/
|
||||
function ensureHaloFilter(root: ComposeElement): void {
|
||||
if (hasElementWithId(root, 'filter', HALO_FILTER_ID)) return
|
||||
const defs = root.getElementsByTagName('defs').item(0) ?? createDefs(root)
|
||||
defs.appendChild(haloFilter(documentOf(root)))
|
||||
}
|
||||
|
||||
function hasElementWithId(
|
||||
root: ComposeElement,
|
||||
tag: string,
|
||||
id: string,
|
||||
): boolean {
|
||||
const list = root.getElementsByTagName(tag)
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (list.item(i)?.getAttribute('id') === id) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** `<defs>` as the first child: the asset's own filters sit at the root. */
|
||||
function createDefs(root: ComposeElement): MinimalElement {
|
||||
const defs = documentOf(root).createElementNS(SVG_NS, 'defs')
|
||||
root.insertBefore(defs, root.firstChild)
|
||||
return defs
|
||||
}
|
||||
|
||||
function svgElement(
|
||||
doc: MinimalDocument,
|
||||
tag: string,
|
||||
attrs: Record<string, string>,
|
||||
): MinimalElement {
|
||||
const element = doc.createElementNS(SVG_NS, tag)
|
||||
for (const [name, value] of Object.entries(attrs)) {
|
||||
element.setAttribute(name, value)
|
||||
}
|
||||
return element
|
||||
}
|
||||
|
||||
function haloFilter(doc: MinimalDocument): MinimalElement {
|
||||
const filter = svgElement(doc, 'filter', {
|
||||
id: HALO_FILTER_ID,
|
||||
x: '-100%',
|
||||
y: '-100%',
|
||||
width: '300%',
|
||||
height: '300%',
|
||||
filterUnits: 'userSpaceOnUse',
|
||||
})
|
||||
filter.appendChild(gaussianBlur(doc, '18', 'haloWide'))
|
||||
filter.appendChild(gaussianBlur(doc, '8', 'haloTight'))
|
||||
filter.appendChild(haloMerge(doc))
|
||||
return filter
|
||||
}
|
||||
|
||||
function gaussianBlur(
|
||||
doc: MinimalDocument,
|
||||
stdDeviation: string,
|
||||
result: string,
|
||||
): MinimalElement {
|
||||
return svgElement(doc, 'feGaussianBlur', {
|
||||
in: 'SourceGraphic',
|
||||
stdDeviation,
|
||||
result,
|
||||
})
|
||||
}
|
||||
|
||||
/** Three wide blurs, two tight ones, then the marker itself on top. */
|
||||
function haloMerge(doc: MinimalDocument): MinimalElement {
|
||||
const merge = svgElement(doc, 'feMerge', {})
|
||||
const inputs = [
|
||||
'haloWide',
|
||||
'haloWide',
|
||||
'haloWide',
|
||||
'haloTight',
|
||||
'haloTight',
|
||||
'SourceGraphic',
|
||||
]
|
||||
for (const input of inputs) {
|
||||
merge.appendChild(svgElement(doc, 'feMergeNode', { in: input }))
|
||||
}
|
||||
return merge
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { LayerElement } from './layer'
|
||||
|
||||
/**
|
||||
* Materialises a layer tree with any DOM implementation (browser document,
|
||||
* xmldom in the pipeline). Only the handful of methods used are required,
|
||||
* so this module compiles without the DOM lib.
|
||||
*/
|
||||
|
||||
export const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
|
||||
export interface MinimalNode {
|
||||
appendChild(child: MinimalNode): unknown
|
||||
}
|
||||
|
||||
export interface MinimalElement extends MinimalNode {
|
||||
setAttribute(name: string, value: string): void
|
||||
}
|
||||
|
||||
export interface MinimalDocument {
|
||||
createElementNS(ns: string, tag: string): MinimalElement
|
||||
createTextNode(text: string): MinimalNode
|
||||
}
|
||||
|
||||
export function createLayerElement(
|
||||
doc: MinimalDocument,
|
||||
node: LayerElement,
|
||||
): MinimalElement {
|
||||
const element = doc.createElementNS(SVG_NS, node.tag)
|
||||
for (const [name, value] of Object.entries(node.attrs)) {
|
||||
element.setAttribute(name, value)
|
||||
}
|
||||
if (node.text !== undefined)
|
||||
element.appendChild(doc.createTextNode(node.text))
|
||||
for (const child of node.children) {
|
||||
element.appendChild(createLayerElement(doc, child))
|
||||
}
|
||||
return element
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
export {
|
||||
DETAIL_VIEW_STYLE,
|
||||
FALLBACK_COLOR,
|
||||
LAYER_ATTRIBUTE,
|
||||
LAYER_NAME,
|
||||
MAIN_VIEW_STYLE,
|
||||
renderAnnotationLayer,
|
||||
styleForView,
|
||||
viewBoxOf,
|
||||
type AnnotationState,
|
||||
type LayerElement,
|
||||
type LayerInput,
|
||||
type MarkerStyle,
|
||||
} from './layer'
|
||||
export {
|
||||
createLayerElement,
|
||||
SVG_NS,
|
||||
type MinimalDocument,
|
||||
type MinimalElement,
|
||||
type MinimalNode,
|
||||
} from './dom'
|
||||
export { serializeLayer } from './serialize'
|
||||
export {
|
||||
composeViewSvg,
|
||||
HALO_FILTER_ID,
|
||||
HIGHLIGHT_FILL,
|
||||
HIGHLIGHT_FILL_OPACITY,
|
||||
highlightLayer,
|
||||
type ComposeElement,
|
||||
type ComposeElementList,
|
||||
type ComposeHighlight,
|
||||
type ComposeInput,
|
||||
} from './compose'
|
||||
@@ -1,261 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
Geometry,
|
||||
SheetView,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Annotation layer of one view, as pure data: the SVG elements the
|
||||
* application draws over the sheet's drawing, reproducing the legacy
|
||||
* markers (transparent hitbox + visible twin per point, filled polygon per
|
||||
* spine zone, dashed outline per detail trigger). The elements carry the
|
||||
* `data-anno-*` attributes the click delegation, the tooltip and the CSS
|
||||
* states read, so the drawing itself needs no annotation element at all.
|
||||
* No DOM here: `dom.ts` materialises the tree, `serialize.ts` prints it.
|
||||
*/
|
||||
|
||||
export interface LayerElement {
|
||||
tag: 'g' | 'circle' | 'polygon' | 'path' | 'title'
|
||||
attrs: Record<string, string>
|
||||
children: LayerElement[]
|
||||
text?: string
|
||||
}
|
||||
|
||||
/** Visual constants of the legacy markers, per view kind. */
|
||||
export interface MarkerStyle {
|
||||
/** Visible circle radius = hitbox radius − inset (34→22, 30→18, 27→15). */
|
||||
visibleInset: number
|
||||
visibleFillOpacity: number
|
||||
visibleStroke: string
|
||||
visibleStrokeWidth: number
|
||||
zoneFillOpacity: number
|
||||
zoneStrokeWidth: number
|
||||
triggerFillOpacity: number
|
||||
triggerStrokeWidth: number
|
||||
triggerDash: string
|
||||
}
|
||||
|
||||
const BASE_STYLE: Omit<MarkerStyle, 'visibleFillOpacity'> = {
|
||||
visibleInset: 12,
|
||||
visibleStroke: '#000',
|
||||
visibleStrokeWidth: 1.5,
|
||||
zoneFillOpacity: 0.3,
|
||||
zoneStrokeWidth: 2,
|
||||
triggerFillOpacity: 0.06,
|
||||
triggerStrokeWidth: 2,
|
||||
triggerDash: '8,4',
|
||||
}
|
||||
|
||||
export const MAIN_VIEW_STYLE: MarkerStyle = {
|
||||
...BASE_STYLE,
|
||||
visibleFillOpacity: 0.65,
|
||||
}
|
||||
export const DETAIL_VIEW_STYLE: MarkerStyle = {
|
||||
...BASE_STYLE,
|
||||
visibleFillOpacity: 0.5,
|
||||
}
|
||||
|
||||
/** When neither the annotation nor its category names a colour. */
|
||||
export const FALLBACK_COLOR = '#888888'
|
||||
|
||||
export const LAYER_ATTRIBUTE = 'data-layer'
|
||||
export const LAYER_NAME = 'annotations'
|
||||
|
||||
export type AnnotationState = 'current'
|
||||
|
||||
export interface LayerInput {
|
||||
document: AnatomicalSheetDocumentInput
|
||||
viewId: string
|
||||
/** Annotation id → state, applied as `data-state`. */
|
||||
states?: ReadonlyMap<string, AnnotationState>
|
||||
}
|
||||
|
||||
type Annotation = AnatomicalSheetDocumentInput['annotations'][number]
|
||||
|
||||
export function styleForView(view: Pick<SheetView, 'kind'>): MarkerStyle {
|
||||
return view.kind === 'main' ? MAIN_VIEW_STYLE : DETAIL_VIEW_STYLE
|
||||
}
|
||||
|
||||
function el(
|
||||
tag: LayerElement['tag'],
|
||||
attrs: Record<string, string>,
|
||||
children: LayerElement[] = [],
|
||||
): LayerElement {
|
||||
return { tag, attrs, children }
|
||||
}
|
||||
|
||||
function title(text: string): LayerElement {
|
||||
return { tag: 'title', attrs: {}, children: [], text }
|
||||
}
|
||||
|
||||
function geometryAttrs(
|
||||
geometry: Geometry,
|
||||
): [LayerElement['tag'], Record<string, string>] {
|
||||
switch (geometry.type) {
|
||||
case 'circle':
|
||||
return [
|
||||
'circle',
|
||||
{
|
||||
cx: String(geometry.cx),
|
||||
cy: String(geometry.cy),
|
||||
r: String(geometry.r),
|
||||
},
|
||||
]
|
||||
case 'polygon':
|
||||
return [
|
||||
'polygon',
|
||||
{ points: geometry.points.map(([x, y]) => `${x},${y}`).join(' ') },
|
||||
]
|
||||
case 'path':
|
||||
return ['path', { d: geometry.d }]
|
||||
}
|
||||
}
|
||||
|
||||
function colorOf(
|
||||
a: Annotation,
|
||||
categories: Map<string, string | null>,
|
||||
): string {
|
||||
return a.color ?? categories.get(a.category_id) ?? FALLBACK_COLOR
|
||||
}
|
||||
|
||||
/** Attributes shared by every element of one annotation. */
|
||||
function dataAttrs(
|
||||
a: Annotation,
|
||||
input: LayerInput,
|
||||
viewName: string,
|
||||
): Record<string, string> {
|
||||
const attrs: Record<string, string> = {
|
||||
'data-anno-id': a.id,
|
||||
'data-anno-kind': a.kind,
|
||||
'data-anno-lateral': a.laterality,
|
||||
}
|
||||
if (a.kind === 'detail_trigger') {
|
||||
attrs['data-anno-opens-view'] = a.opens_view_id
|
||||
attrs['data-anno-name-fr'] = a.name?.fr ?? viewName
|
||||
attrs['data-anno-name-en'] = a.name?.en ?? viewName
|
||||
} else {
|
||||
attrs['data-anno-name-fr'] = a.name.fr
|
||||
attrs['data-anno-name-en'] = a.name.en
|
||||
if (a.finding_zone_id) attrs['data-anno-zone'] = a.finding_zone_id
|
||||
if (a.vertebral_region_code)
|
||||
attrs['data-anno-region'] = a.vertebral_region_code
|
||||
}
|
||||
const state = input.states?.get(a.id)
|
||||
if (state) attrs['data-state'] = state
|
||||
return attrs
|
||||
}
|
||||
|
||||
function pointElements(
|
||||
geometry: Extract<Geometry, { type: 'circle' }>,
|
||||
color: string,
|
||||
style: MarkerStyle,
|
||||
data: Record<string, string>,
|
||||
label: string,
|
||||
): LayerElement[] {
|
||||
const hitbox = el(
|
||||
'circle',
|
||||
{
|
||||
...geometryAttrs(geometry)[1],
|
||||
fill: 'transparent',
|
||||
'pointer-events': 'all',
|
||||
style: 'cursor:pointer',
|
||||
...data,
|
||||
},
|
||||
[title(label)],
|
||||
)
|
||||
const visible = el(
|
||||
'circle',
|
||||
{
|
||||
cx: String(geometry.cx),
|
||||
cy: String(geometry.cy),
|
||||
r: String(Math.max(2, geometry.r - style.visibleInset)),
|
||||
fill: color,
|
||||
'fill-opacity': String(style.visibleFillOpacity),
|
||||
stroke: style.visibleStroke,
|
||||
'stroke-width': String(style.visibleStrokeWidth),
|
||||
'pointer-events': 'none',
|
||||
...data,
|
||||
},
|
||||
[title(label)],
|
||||
)
|
||||
return [hitbox, visible]
|
||||
}
|
||||
|
||||
function shapeElement(
|
||||
geometry: Geometry,
|
||||
color: string,
|
||||
visual: Record<string, string>,
|
||||
data: Record<string, string>,
|
||||
label: string,
|
||||
): LayerElement {
|
||||
const [tag, attrs] = geometryAttrs(geometry)
|
||||
return el(tag, { ...attrs, fill: color, stroke: color, ...visual, ...data }, [
|
||||
title(label),
|
||||
])
|
||||
}
|
||||
|
||||
function annotationElements(
|
||||
a: Annotation,
|
||||
input: LayerInput,
|
||||
style: MarkerStyle,
|
||||
categories: Map<string, string | null>,
|
||||
viewName: string,
|
||||
): LayerElement[] {
|
||||
if (!a.geometry) return []
|
||||
const color = colorOf(a, categories)
|
||||
const data = dataAttrs(a, input, viewName)
|
||||
const label = `${data['data-anno-name-fr']} / ${data['data-anno-name-en']}`
|
||||
if (a.kind === 'detail_trigger') {
|
||||
const visual = {
|
||||
'fill-opacity': String(style.triggerFillOpacity),
|
||||
'stroke-width': String(style.triggerStrokeWidth),
|
||||
'stroke-dasharray': style.triggerDash,
|
||||
'pointer-events': 'all',
|
||||
style: 'cursor:pointer',
|
||||
class: 'detail-zone',
|
||||
}
|
||||
return [shapeElement(a.geometry, color, visual, data, label)]
|
||||
}
|
||||
if (a.geometry.type === 'circle') {
|
||||
return pointElements(a.geometry, color, style, data, label)
|
||||
}
|
||||
const visual = {
|
||||
'fill-opacity': String(style.zoneFillOpacity),
|
||||
'stroke-width': String(style.zoneStrokeWidth),
|
||||
'pointer-events': 'all',
|
||||
style: 'cursor:pointer',
|
||||
}
|
||||
return [shapeElement(a.geometry, color, visual, data, label)]
|
||||
}
|
||||
|
||||
/** The layer `<g>` of one view: every annotation of that view, in document order. */
|
||||
export function renderAnnotationLayer(input: LayerInput): LayerElement {
|
||||
const { document, viewId } = input
|
||||
const view = document.views.find((v) => v.id === viewId)
|
||||
if (!view) throw new Error(`unknown view "${viewId}"`)
|
||||
const style = styleForView(view)
|
||||
const categories = new Map(
|
||||
document.categories.map((c) => [c.id, c.color ?? null]),
|
||||
)
|
||||
const viewNames = new Map(document.views.map((v) => [v.id, v.name.fr]))
|
||||
const children = document.annotations
|
||||
.filter((a) => a.view_id === viewId)
|
||||
.flatMap((a) => {
|
||||
const opened =
|
||||
a.kind === 'detail_trigger'
|
||||
? (viewNames.get(a.opens_view_id) ?? '')
|
||||
: ''
|
||||
return annotationElements(a, input, style, categories, opened)
|
||||
})
|
||||
return el(
|
||||
'g',
|
||||
{ [LAYER_ATTRIBUTE]: LAYER_NAME, 'data-view-id': viewId },
|
||||
children,
|
||||
)
|
||||
}
|
||||
|
||||
/** `viewBox` attribute value the view renders with, or null for the asset's own. */
|
||||
export function viewBoxOf(view: SheetView): string | null {
|
||||
const box = view.view_box
|
||||
return box ? `${box.min_x} ${box.min_y} ${box.width} ${box.height}` : null
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { LayerElement } from './layer'
|
||||
|
||||
/** Serialises a layer tree to SVG text (review drawings, tests). */
|
||||
|
||||
function escape(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
export function serializeLayer(node: LayerElement, indent = ''): string {
|
||||
const attrs = Object.entries(node.attrs)
|
||||
.map(([k, v]) => ` ${k}="${escape(v)}"`)
|
||||
.join('')
|
||||
if (node.text !== undefined) {
|
||||
return `${indent}<${node.tag}${attrs}>${escape(node.text)}</${node.tag}>`
|
||||
}
|
||||
if (node.children.length === 0) return `${indent}<${node.tag}${attrs}/>`
|
||||
const inner = node.children
|
||||
.map((child) => serializeLayer(child, `${indent} `))
|
||||
.join('\n')
|
||||
return `${indent}<${node.tag}${attrs}>\n${inner}\n${indent}</${node.tag}>`
|
||||
}
|
||||
@@ -1,529 +0,0 @@
|
||||
import { applyChangeset, type CurationResult, type Op } from '../src'
|
||||
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
|
||||
|
||||
type Plain = Record<string, unknown>
|
||||
|
||||
function plain(value: unknown): Plain {
|
||||
return value as Plain
|
||||
}
|
||||
|
||||
function nodes(item: Plain): Plain[] {
|
||||
return (item.children ?? []) as Plain[]
|
||||
}
|
||||
|
||||
function run(ops: Op[]): CurationResult {
|
||||
return applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops))
|
||||
}
|
||||
|
||||
function zone(result: CurationResult, id: string): Plain {
|
||||
return plain(result.document.finding_zones.find((z) => z.id === id))
|
||||
}
|
||||
|
||||
function hipDysfunctions(result: CurationResult): Plain {
|
||||
return (zone(result, 'hip').categories as Plain[])[0]!
|
||||
}
|
||||
|
||||
function annotation(result: CurationResult, id: string): Plain {
|
||||
return plain(result.document.annotations.find((a) => a.id === id))
|
||||
}
|
||||
|
||||
function childIds(node: Plain): string[] {
|
||||
return nodes(node).map((child) => child.id as string)
|
||||
}
|
||||
|
||||
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
|
||||
|
||||
describe('applyChangeset: set', () => {
|
||||
it('sets a field and records before / after', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'set',
|
||||
target: 'region:C',
|
||||
field: 'count_range',
|
||||
value: { min: 6, max: 8 },
|
||||
},
|
||||
])
|
||||
expect(result.document.vertebral_config.regions[0]!.count_range).toEqual({
|
||||
min: 6,
|
||||
max: 8,
|
||||
})
|
||||
expect(result.records).toHaveLength(1)
|
||||
expect(result.records[0]).toMatchObject({
|
||||
target: 'region:C',
|
||||
field: 'count_range',
|
||||
before: null,
|
||||
after: { min: 6, max: 8 },
|
||||
})
|
||||
})
|
||||
|
||||
it('creates a missing nested object for a dot path', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'description.en',
|
||||
value: 'Mobility',
|
||||
},
|
||||
])
|
||||
expect(nodes(hipDysfunctions(result))[0]!.description).toEqual({
|
||||
en: 'Mobility',
|
||||
})
|
||||
})
|
||||
|
||||
it('applies a subtree set to the target and every descendant', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'set',
|
||||
target: 'finding:hip/hip-dysfunctions',
|
||||
field: 'review_status',
|
||||
value: 'to_confirm',
|
||||
scope: 'subtree',
|
||||
},
|
||||
])
|
||||
expect(result.records.map((r) => r.target)).toEqual([
|
||||
'finding:hip/hip-dysfunctions',
|
||||
MOBILITY,
|
||||
`${MOBILITY}/flexion`,
|
||||
`${MOBILITY}/extension`,
|
||||
'finding:hip/hip-dysfunctions/pain',
|
||||
])
|
||||
expect(nodes(nodes(hipDysfunctions(result))[0]!)[1]!.review_status).toBe(
|
||||
'to_confirm',
|
||||
)
|
||||
})
|
||||
|
||||
it('skips items without the field and items already at the value', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'set',
|
||||
target: 'finding:neck/neck-dysfunctions',
|
||||
field: 'requires_vet_referral',
|
||||
value: true,
|
||||
scope: 'subtree',
|
||||
},
|
||||
])
|
||||
expect(result.records.map((r) => r.target)).toEqual([
|
||||
'finding:neck/neck-dysfunctions/stiffness',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: rename', () => {
|
||||
it('renames a zone and the annotations follow, one record each', () => {
|
||||
const result = run([{ op: 'rename', target: 'zone:hip', id: 'hip-joint' }])
|
||||
expect(zone(result, 'hip-joint')).toBeDefined()
|
||||
const hip = annotation(result, 'hip')
|
||||
expect(hip.finding_zone_id).toBe('hip-joint')
|
||||
expect(result.records.map((r) => [r.target, r.field])).toEqual([
|
||||
['zone:hip', null],
|
||||
['annotation:hip', 'finding_zone_id'],
|
||||
])
|
||||
expect(plain(result.records[0]!.before).id).toBe('hip')
|
||||
})
|
||||
|
||||
it('renames a region code and the vertebral annotations follow', () => {
|
||||
const result = run([{ op: 'rename', target: 'region:C', id: 'Cv' }])
|
||||
expect(result.document.vertebral_config.regions[0]!.code).toBe('Cv')
|
||||
const neck = annotation(result, 'neck')
|
||||
expect(neck.vertebral_region_code).toBe('Cv')
|
||||
})
|
||||
|
||||
it('renames a view: parent links and trigger targets follow', () => {
|
||||
const result = run([{ op: 'rename', target: 'view:head', id: 'skull' }])
|
||||
const trigger = annotation(result, 'head-trigger')
|
||||
expect(trigger.opens_view_id).toBe('skull')
|
||||
expect(result.records.map((r) => r.field)).toEqual([null, 'opens_view_id'])
|
||||
})
|
||||
|
||||
it('renames a main view: parent_view_id and view_id follow', () => {
|
||||
const result = run([{ op: 'rename', target: 'view:main', id: 'overview' }])
|
||||
expect(plain(result.document.views[1]).parent_view_id).toBe('overview')
|
||||
expect(
|
||||
result.document.annotations.every((a) => a.view_id === 'overview'),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('renames an annotation category: annotations follow', () => {
|
||||
const result = run([
|
||||
{ op: 'rename', target: 'category:joints', id: 'articulations' },
|
||||
])
|
||||
const hip = result.document.annotations.find((a) => a.id === 'hip')!
|
||||
expect(hip.category_id).toBe('articulations')
|
||||
})
|
||||
|
||||
it('renames a reference: every citation follows', () => {
|
||||
const result = run([
|
||||
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
|
||||
{ op: 'rename', target: 'reference:atlas', id: 'atlas-2' },
|
||||
])
|
||||
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
|
||||
'atlas-2',
|
||||
])
|
||||
expect(result.records.at(-1)).toMatchObject({
|
||||
target: MOBILITY,
|
||||
field: 'reference_ids',
|
||||
before: ['atlas'],
|
||||
after: ['atlas-2'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: add, remove, move', () => {
|
||||
const node = (id: string) => ({ id, name: { fr: id, en: id } })
|
||||
|
||||
it.each([
|
||||
[{ after: 'flexion' }, ['flexion', 'new', 'extension']],
|
||||
[{ before: 'flexion' }, ['new', 'flexion', 'extension']],
|
||||
[1, ['flexion', 'new', 'extension']],
|
||||
[undefined, ['flexion', 'extension', 'new']],
|
||||
] as const)('adds a node at position %j', (position, expected) => {
|
||||
const op: Op = { op: 'add', target: MOBILITY, value: node('new') }
|
||||
if (position !== undefined) op.position = position
|
||||
const result = run([op])
|
||||
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual(expected)
|
||||
expect(result.records[0]).toMatchObject({
|
||||
target: `${MOBILITY}/new`,
|
||||
before: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('adds children under a lean leaf', () => {
|
||||
const result = run([
|
||||
{ op: 'add', target: `${MOBILITY}/flexion`, value: node('left') },
|
||||
])
|
||||
expect(childIds(nodes(nodes(hipDysfunctions(result))[0]!)[0]!)).toEqual([
|
||||
'left',
|
||||
])
|
||||
})
|
||||
|
||||
it('adds a zone, an annotation and a reference at document level', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'add',
|
||||
target: 'document',
|
||||
field: 'finding_zones',
|
||||
value: { id: 'back', name: { fr: 'Dos', en: 'Back' }, categories: [] },
|
||||
},
|
||||
{
|
||||
op: 'add',
|
||||
target: 'document',
|
||||
field: 'annotations',
|
||||
position: { after: 'neck' },
|
||||
value: {
|
||||
id: 'back',
|
||||
kind: 'zone',
|
||||
view_id: 'main',
|
||||
category_id: 'bones',
|
||||
laterality: 'unpaired',
|
||||
geometry: null,
|
||||
name: { fr: 'Dos', en: 'Back' },
|
||||
finding_zone_id: 'back',
|
||||
vertebral_region_code: 'T',
|
||||
},
|
||||
},
|
||||
{
|
||||
op: 'add',
|
||||
target: 'document',
|
||||
field: 'references',
|
||||
value: {
|
||||
id: 'book',
|
||||
type: 'book',
|
||||
citation: 'Book',
|
||||
url: null,
|
||||
doi: null,
|
||||
},
|
||||
},
|
||||
{ op: 'cite', target: 'finding:hip/anamnesis', reference_ids: ['book'] },
|
||||
])
|
||||
expect(result.document.annotations.map((a) => a.id)).toEqual([
|
||||
'hip',
|
||||
'neck',
|
||||
'back',
|
||||
'head-trigger',
|
||||
])
|
||||
expect(result.records.map((r) => r.target)).toEqual([
|
||||
'zone:back',
|
||||
'annotation:back',
|
||||
'reference:book',
|
||||
'finding:hip/anamnesis',
|
||||
])
|
||||
})
|
||||
|
||||
it('removes a node and records the whole item', () => {
|
||||
const result = run([{ op: 'remove', target: MOBILITY }])
|
||||
expect(childIds(hipDysfunctions(result))).toEqual(['pain'])
|
||||
expect(result.records[0]).toMatchObject({ target: MOBILITY, after: null })
|
||||
expect(childIds(plain(result.records[0]!.before))).toEqual([
|
||||
'flexion',
|
||||
'extension',
|
||||
])
|
||||
})
|
||||
|
||||
it('moves a node into a sibling, then across zones', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'move',
|
||||
target: 'finding:hip/hip-dysfunctions/pain',
|
||||
to: MOBILITY,
|
||||
position: { before: 'flexion' },
|
||||
},
|
||||
{
|
||||
op: 'move',
|
||||
target: 'finding:neck/neck-dysfunctions/stiffness',
|
||||
to: 'finding:hip/anamnesis',
|
||||
},
|
||||
])
|
||||
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual([
|
||||
'pain',
|
||||
'flexion',
|
||||
'extension',
|
||||
])
|
||||
expect(childIds((zone(result, 'hip').categories as Plain[])[1]!)).toEqual([
|
||||
'trauma',
|
||||
'stiffness',
|
||||
])
|
||||
expect(result.records.map((r) => r.after)).toEqual([
|
||||
`${MOBILITY}/pain`,
|
||||
'finding:hip/anamnesis/stiffness',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: cite', () => {
|
||||
it('cites one item without duplicates', () => {
|
||||
const result = run([
|
||||
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
|
||||
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas', 'paper'] },
|
||||
])
|
||||
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
|
||||
'atlas',
|
||||
'paper',
|
||||
])
|
||||
expect(
|
||||
nodes(nodes(hipDysfunctions(result))[0]!)[0]!.reference_ids,
|
||||
).toBeUndefined()
|
||||
expect(result.records).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('cites a subtree, and a zone stands for its categories', () => {
|
||||
const subtree = run([
|
||||
{
|
||||
op: 'cite',
|
||||
target: MOBILITY,
|
||||
reference_ids: ['atlas'],
|
||||
scope: 'subtree',
|
||||
},
|
||||
])
|
||||
expect(subtree.records.map((r) => r.target)).toEqual([
|
||||
MOBILITY,
|
||||
`${MOBILITY}/flexion`,
|
||||
`${MOBILITY}/extension`,
|
||||
])
|
||||
const own = run([
|
||||
{ op: 'cite', target: 'zone:hip', reference_ids: ['paper'] },
|
||||
])
|
||||
expect(own.records.map((r) => r.target)).toEqual([
|
||||
'finding:hip/hip-dysfunctions',
|
||||
'finding:hip/anamnesis',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: errors fail loud', () => {
|
||||
it.each([
|
||||
[
|
||||
[{ op: 'set', target: 'zone:nope', field: 'name', value: {} }],
|
||||
'unknown target',
|
||||
],
|
||||
[
|
||||
[{ op: 'set', target: 'finding:hip', field: 'name', value: {} }],
|
||||
'malformed target',
|
||||
],
|
||||
[
|
||||
[{ op: 'set', target: 'galaxy:x', field: 'name', value: {} }],
|
||||
'unknown target',
|
||||
],
|
||||
[
|
||||
[{ op: 'set', target: 'zone:hip', field: 'colour', value: 1 }],
|
||||
'unknown field',
|
||||
],
|
||||
[
|
||||
[{ op: 'set', target: 'zone:hip', field: 'id', value: 'x' }],
|
||||
'unknown field',
|
||||
],
|
||||
[
|
||||
[
|
||||
{
|
||||
op: 'add',
|
||||
target: MOBILITY,
|
||||
value: { id: 'flexion', name: { fr: 'a', en: 'a' } },
|
||||
},
|
||||
],
|
||||
'already exists',
|
||||
],
|
||||
[
|
||||
[
|
||||
{
|
||||
op: 'add',
|
||||
target: MOBILITY,
|
||||
value: { id: 'x', name: { fr: 'a', en: 'a' } },
|
||||
position: { after: 'nope' },
|
||||
},
|
||||
],
|
||||
'unknown sibling',
|
||||
],
|
||||
[[{ op: 'rename', target: 'zone:hip', id: 'neck' }], 'already exists'],
|
||||
[
|
||||
[{ op: 'cite', target: MOBILITY, reference_ids: ['ghost'] }],
|
||||
'undeclared reference',
|
||||
],
|
||||
[
|
||||
[{ op: 'move', target: MOBILITY, to: `${MOBILITY}/flexion` }],
|
||||
'into itself',
|
||||
],
|
||||
] as Array<[Op[], string]>)('%j → %s', (ops, message) => {
|
||||
expect(() => run(ops)).toThrow(message)
|
||||
expect(() => run(ops)).toThrow('CHG-001 op 0')
|
||||
})
|
||||
|
||||
it('rejects a change citing an undeclared reference', () => {
|
||||
const changeset = changesetOf(
|
||||
[{ op: 'remove', target: `${MOBILITY}/flexion` }],
|
||||
{
|
||||
reference_ids: ['ghost'],
|
||||
},
|
||||
)
|
||||
expect(() =>
|
||||
applyChangeset(miniSheet(), MINI_REFERENCES, changeset),
|
||||
).toThrow('CHG-001: undeclared reference(s): ghost')
|
||||
})
|
||||
|
||||
it('rejects an integrity error left after the ops', () => {
|
||||
const remove: Op[] = [{ op: 'remove', target: 'zone:hip' }]
|
||||
expect(() => run(remove)).toThrow('integrity errors')
|
||||
expect(() => run(remove)).toThrow('Finding zone "hip" does not exist')
|
||||
})
|
||||
|
||||
it('rejects a shape error left after the ops', () => {
|
||||
expect(() =>
|
||||
run([{ op: 'set', target: 'region:C', field: 'count', value: 'seven' }]),
|
||||
).toThrow('not shape-valid')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: purity', () => {
|
||||
const ops: Op[] = [
|
||||
{ op: 'rename', target: 'zone:hip', id: 'hip-joint' },
|
||||
{
|
||||
op: 'cite',
|
||||
target: 'zone:hip-joint',
|
||||
reference_ids: ['atlas'],
|
||||
scope: 'subtree',
|
||||
},
|
||||
]
|
||||
|
||||
it('is deterministic', () => {
|
||||
expect(run(ops)).toEqual(run(ops))
|
||||
})
|
||||
|
||||
it('never mutates its inputs', () => {
|
||||
const baseline = miniSheet()
|
||||
const references = structuredClone(MINI_REFERENCES)
|
||||
const changeset = changesetOf(ops)
|
||||
const copies = structuredClone({ baseline, references, changeset })
|
||||
const result = applyChangeset(baseline, references, changeset)
|
||||
expect({ baseline, references, changeset }).toEqual(copies)
|
||||
expect(result.document.references).toEqual(references)
|
||||
expect(result.document.references).not.toBe(references)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyChangeset: review rule of levels B and C', () => {
|
||||
const B = { level: 'B' } as const
|
||||
const withLevel = (ops: Op[], extra = B) =>
|
||||
applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops, extra))
|
||||
const status = (item: Plain) => item.review_status
|
||||
|
||||
it('marks a node set by a B change to_confirm, with a record', () => {
|
||||
const result = withLevel([
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'name',
|
||||
value: { fr: 'a', en: 'a' },
|
||||
},
|
||||
])
|
||||
const node = nodes(hipDysfunctions(result))[0]!
|
||||
expect(status(node)).toBe('to_confirm')
|
||||
const last = result.records[result.records.length - 1]!
|
||||
expect(last).toMatchObject({
|
||||
target: MOBILITY,
|
||||
field: 'review_status',
|
||||
before: 'inherited',
|
||||
after: 'to_confirm',
|
||||
})
|
||||
expect(last.change.id).toBe('CHG-001')
|
||||
})
|
||||
|
||||
it('marks every node of an added subtree', () => {
|
||||
const value = {
|
||||
id: 'new',
|
||||
name: { fr: 'n', en: 'n' },
|
||||
children: [{ id: 'leaf', name: { fr: 'l', en: 'l' } }],
|
||||
}
|
||||
const result = withLevel([
|
||||
{ op: 'add', target: 'finding:hip/hip-dysfunctions', value },
|
||||
])
|
||||
const added = nodes(hipDysfunctions(result)).find((n) => n.id === 'new')!
|
||||
expect(status(added)).toBe('to_confirm')
|
||||
expect(status(nodes(added)[0]!)).toBe('to_confirm')
|
||||
})
|
||||
|
||||
it('marks cited targets under a C change', () => {
|
||||
const result = withLevel(
|
||||
[{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] }],
|
||||
{ level: 'C', question: 'Q?' } as never,
|
||||
)
|
||||
expect(status(nodes(hipDysfunctions(result))[0]!)).toBe('to_confirm')
|
||||
})
|
||||
|
||||
it('marks an annotation set by a B change', () => {
|
||||
const result = withLevel([
|
||||
{
|
||||
op: 'set',
|
||||
target: 'annotation:hip',
|
||||
field: 'name',
|
||||
value: { fr: 'h', en: 'h' },
|
||||
},
|
||||
])
|
||||
expect(status(annotation(result, 'hip'))).toBe('to_confirm')
|
||||
})
|
||||
|
||||
it('leaves a level A change untouched', () => {
|
||||
const result = run([
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'name',
|
||||
value: { fr: 'a', en: 'a' },
|
||||
},
|
||||
])
|
||||
expect(status(nodes(hipDysfunctions(result))[0]!)).not.toBe('to_confirm')
|
||||
expect(result.records).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('throws when a B change sets review_status to reviewed', () => {
|
||||
expect(() =>
|
||||
withLevel([
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'review_status',
|
||||
value: 'reviewed',
|
||||
},
|
||||
]),
|
||||
).toThrow(
|
||||
/CHG-001 op 0: level B cannot set "finding:hip\/hip-dysfunctions\/mobility"/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,79 +0,0 @@
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
EQUINE_SOURCE_PATHS,
|
||||
assetIdFromSha256,
|
||||
cleanedAsset,
|
||||
parseViewBox,
|
||||
stripLegacyAnnotations,
|
||||
} from '../src'
|
||||
import { REPO_ROOT } from './helpers'
|
||||
|
||||
let source: string
|
||||
let cleaned: string
|
||||
|
||||
function count(text: string, pattern: RegExp): number {
|
||||
return [...text.matchAll(pattern)].length
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
source = await readFile(join(REPO_ROOT, EQUINE_SOURCE_PATHS.mainSvg), 'utf8')
|
||||
cleaned = stripLegacyAnnotations(source)
|
||||
})
|
||||
|
||||
describe('stripLegacyAnnotations on the real Horse.svg', () => {
|
||||
it('removes exactly the elements carrying data-anno-id', () => {
|
||||
const annotated = count(source, /<[a-z]+\b[^>]*\sdata-anno-id="/g)
|
||||
const elements = (text: string) => count(text, /<[a-zA-Z]+[\s/>]/g)
|
||||
expect(annotated).toBe(30) // 12 points × (hitbox + marker) + 6 polygons
|
||||
// each annotated element carries one <title> child, removed with it
|
||||
const titles = count(source, /data-anno-id="[^"]*"[^>]*><title>/g)
|
||||
expect(elements(source) - elements(cleaned)).toBe(annotated + titles)
|
||||
})
|
||||
|
||||
it('keeps the 270 drawing paths and every non-annotation byte', () => {
|
||||
expect(count(source, /<path\b/g)).toBe(270)
|
||||
expect(count(cleaned, /<path\b/g)).toBe(270)
|
||||
expect(cleaned).not.toContain('data-anno-')
|
||||
expect(cleaned.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(
|
||||
true,
|
||||
)
|
||||
expect(cleaned).not.toContain('max-width: 100%')
|
||||
})
|
||||
|
||||
it('is deterministic and parses as XML', () => {
|
||||
expect(stripLegacyAnnotations(source)).toBe(cleaned)
|
||||
const errors: string[] = []
|
||||
const doc = new DOMParser({
|
||||
onError: (level, message) => {
|
||||
if (level !== 'warning') errors.push(message)
|
||||
},
|
||||
}).parseFromString(cleaned, 'image/svg+xml')
|
||||
expect(errors).toEqual([])
|
||||
expect(doc.documentElement?.tagName).toBe('svg')
|
||||
})
|
||||
|
||||
it('describes the cleaned bytes with their sha256', () => {
|
||||
const bytes = new TextEncoder().encode(cleaned)
|
||||
const asset = cleanedAsset(bytes)
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
||||
expect(asset).toEqual({
|
||||
file: 'horse.svg',
|
||||
sha256,
|
||||
byte_size: bytes.byteLength,
|
||||
svg_asset_id: assetIdFromSha256(sha256),
|
||||
})
|
||||
})
|
||||
|
||||
it('reads a viewBox into a document view_box', () => {
|
||||
expect(parseViewBox('60 100 500 380')).toEqual({
|
||||
min_x: 60,
|
||||
min_y: 100,
|
||||
width: 500,
|
||||
height: 380,
|
||||
})
|
||||
expect(() => parseViewBox('1 2 3')).toThrow('invalid viewBox')
|
||||
})
|
||||
})
|
||||
@@ -1,271 +0,0 @@
|
||||
/**
|
||||
* Per-leaf adapter test over the committed seed: every leaf of the legacy
|
||||
* catalog (612) and every legacy annotation (27) travels through the real
|
||||
* Report v2 → v3 migration with the generated map, then is checked against
|
||||
* the curated draft document itself, not against the map alone.
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportMigrationMapSchema,
|
||||
ReportV2Schema,
|
||||
findingPathKey,
|
||||
migrateReportV2ToV3,
|
||||
readReportDocument,
|
||||
type AnatomicalSheetDocument,
|
||||
type Annotation,
|
||||
type Finding,
|
||||
type FindingCategory,
|
||||
type FindingNode,
|
||||
type ObservationV2,
|
||||
type ReportMigrationMap,
|
||||
type ReportV2,
|
||||
} from '@faunosteo/domain'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import { EQUINE_DRAFT_DIR, EQUINE_LEGACY_IMPORT_DIR } from '../src'
|
||||
import { REPO_ROOT } from './helpers'
|
||||
|
||||
interface LegacyLeaf {
|
||||
zoneId: string
|
||||
path: string[]
|
||||
name: { fr: string; en: string }
|
||||
vet: boolean
|
||||
}
|
||||
|
||||
/** Every leaf of a document's finding trees, in document order. */
|
||||
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
|
||||
const out: LegacyLeaf[] = []
|
||||
const walk = (
|
||||
zoneId: string,
|
||||
nodes: readonly (FindingCategory | FindingNode)[],
|
||||
prefix: string[],
|
||||
) => {
|
||||
for (const node of nodes) {
|
||||
const path = [...prefix, node.id]
|
||||
if (node.children.length > 0) walk(zoneId, node.children, path)
|
||||
else {
|
||||
const vet =
|
||||
'requires_vet_referral' in node && node.requires_vet_referral
|
||||
out.push({ zoneId, path, name: node.name, vet })
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
|
||||
return out
|
||||
}
|
||||
|
||||
/** One v2 observation per zone holding every leaf of that zone as a finding. */
|
||||
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||
const byZone = new Map<string, ObservationV2>()
|
||||
for (const leaf of leaves) {
|
||||
let obs = byZone.get(leaf.zoneId)
|
||||
if (!obs) {
|
||||
obs = {
|
||||
id: `obs-${leaf.zoneId}`,
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
}
|
||||
byZone.set(leaf.zoneId, obs)
|
||||
}
|
||||
obs.findings.push({
|
||||
zoneId: leaf.zoneId,
|
||||
path: leaf.path,
|
||||
labelFrSnapshot: leaf.name.fr,
|
||||
labelEnSnapshot: leaf.name.en || leaf.name.fr,
|
||||
...(leaf.vet ? { requiresVetReferral: true } : {}),
|
||||
})
|
||||
}
|
||||
return ReportV2Schema.parse({
|
||||
version: 2,
|
||||
id: 'all-leaves',
|
||||
createdAt: '2026-10-10T00:00:00Z',
|
||||
date: '2026-10-10',
|
||||
practitioner: { name: 'Synthetic' },
|
||||
animal: { speciesId: 'equine', name: 'Synthetic' },
|
||||
owner: { name: 'Synthetic' },
|
||||
observations: [...byZone.values()],
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
})
|
||||
}
|
||||
|
||||
function nodeAt(
|
||||
doc: AnatomicalSheetDocument,
|
||||
zoneId: string,
|
||||
path: readonly string[],
|
||||
): FindingCategory | FindingNode | undefined {
|
||||
const zone = doc.finding_zones.find((z) => z.id === zoneId)
|
||||
let node: FindingCategory | FindingNode | undefined = zone?.categories.find(
|
||||
(c) => c.id === path[0],
|
||||
)
|
||||
for (const segment of path.slice(1)) {
|
||||
node = node?.children.find((n) => n.id === segment)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
async function readJson(relative: string): Promise<unknown> {
|
||||
return JSON.parse(await readFile(join(REPO_ROOT, relative), 'utf8'))
|
||||
}
|
||||
|
||||
let baseline: AnatomicalSheetDocument
|
||||
let draft: AnatomicalSheetDocument
|
||||
let map: ReportMigrationMap
|
||||
let leaves: LegacyLeaf[]
|
||||
let findings: Finding[]
|
||||
|
||||
beforeAll(async () => {
|
||||
baseline = AnatomicalSheetDocumentSchema.parse(
|
||||
await readJson(`${EQUINE_LEGACY_IMPORT_DIR}/document.json`),
|
||||
)
|
||||
draft = AnatomicalSheetDocumentSchema.parse(
|
||||
await readJson(`${EQUINE_DRAFT_DIR}/document.json`),
|
||||
)
|
||||
map = ReportMigrationMapSchema.parse(
|
||||
await readJson(`${EQUINE_DRAFT_DIR}/report-migration-map.json`),
|
||||
)
|
||||
leaves = legacyLeaves(baseline)
|
||||
const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map)
|
||||
findings = report.observations.flatMap((o) => o.findings)
|
||||
})
|
||||
|
||||
describe('every legacy leaf through the v2 → v3 migration', () => {
|
||||
it('migrates the 612 leaves: 442 identical, 141 moved, 29 removed', () => {
|
||||
expect(leaves).toHaveLength(612)
|
||||
expect(findings).toHaveLength(612)
|
||||
const fates = { identical: 0, moved: 0, removed: 0 }
|
||||
leaves.forEach((leaf, i) => {
|
||||
const out = findings[i]!
|
||||
const same =
|
||||
out.findingZoneId === leaf.zoneId &&
|
||||
out.path.join('/') === leaf.path.join('/')
|
||||
if (out.unresolved) fates.removed += 1
|
||||
else if (same) fates.identical += 1
|
||||
else fates.moved += 1
|
||||
})
|
||||
expect(fates).toEqual({ identical: 442, moved: 141, removed: 29 })
|
||||
})
|
||||
|
||||
it('lands every resolved leaf on a leaf of the draft document', () => {
|
||||
for (const out of findings) {
|
||||
if (out.unresolved) continue
|
||||
const node = nodeAt(draft, out.findingZoneId, out.path)
|
||||
const where = `${out.findingZoneId}/${out.path.join('/')}`
|
||||
expect(node, where).toBeDefined()
|
||||
expect(node!.children, where).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the legacy snapshots and the vet flag verbatim on every finding', () => {
|
||||
leaves.forEach((leaf, i) => {
|
||||
const out = findings[i]!
|
||||
expect(out.labelFrSnapshot).toBe(leaf.name.fr)
|
||||
expect(out.labelEnSnapshot).toBe(leaf.name.en || leaf.name.fr)
|
||||
expect(out.requiresVetReferral ?? false).toBe(leaf.vet)
|
||||
})
|
||||
})
|
||||
|
||||
it('flags exactly the leaves the curation removed, with their legacy path kept', () => {
|
||||
const removed = leaves.filter(
|
||||
(leaf) =>
|
||||
map.finding_paths[findingPathKey(leaf.zoneId, leaf.path)] === null,
|
||||
)
|
||||
expect(removed).toHaveLength(29)
|
||||
const flagged = findings.filter((f) => f.unresolved)
|
||||
expect(
|
||||
flagged.map((f) => `${f.findingZoneId}/${f.path.join('/')}`),
|
||||
).toEqual(removed.map((leaf) => findingPathKey(leaf.zoneId, leaf.path)))
|
||||
for (const f of flagged) {
|
||||
expect(nodeAt(draft, f.findingZoneId, f.path)).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('moves the 141 relocated leaves inside their zone: 134 under a renamed category, 7 renamed leaves', () => {
|
||||
const fates = { category: 0, leaf: 0 }
|
||||
leaves.forEach((leaf, i) => {
|
||||
const out = findings[i]!
|
||||
if (out.unresolved || out.path.join('/') === leaf.path.join('/')) return
|
||||
expect(out.findingZoneId, leaf.path.join('/')).toBe(leaf.zoneId)
|
||||
if (out.path.at(-1) === leaf.path.at(-1)) fates.category += 1
|
||||
else fates.leaf += 1
|
||||
})
|
||||
expect(fates).toEqual({ category: 134, leaf: 7 })
|
||||
})
|
||||
|
||||
it('reads the migrated report back unchanged (v3 is stable)', () => {
|
||||
const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map)
|
||||
const again = readReportDocument(report, map)
|
||||
expect(again.report).toEqual(report)
|
||||
expect(again.unresolvedZones).toBe(0)
|
||||
expect(again.unresolvedFindings).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('every legacy annotation as a report zone', () => {
|
||||
it('maps the 26 observable legacy ids to annotations of the right view, names snapshotted', () => {
|
||||
const triggers = new Set(
|
||||
draft.annotations
|
||||
.filter((a) => a.kind === 'detail_trigger')
|
||||
.map((a) => a.id),
|
||||
)
|
||||
const legacyIds = Object.keys(map.annotations).filter(
|
||||
(id) => !triggers.has(map.annotations[id]!.id),
|
||||
)
|
||||
expect(legacyIds).toHaveLength(26)
|
||||
const headIds = new Set(
|
||||
draft.annotations.filter((a) => a.view_id === 'head').map((a) => a.id),
|
||||
)
|
||||
const v2 = leavesAsV2Report([])
|
||||
v2.observations = [
|
||||
{
|
||||
id: 'zones',
|
||||
zones: legacyIds.map((boneId) =>
|
||||
headIds.has(map.annotations[boneId]!.id)
|
||||
? { boneId, detailSourceId: 'head' }
|
||||
: { boneId },
|
||||
),
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
},
|
||||
]
|
||||
const out = migrateReportV2ToV3(v2, map)
|
||||
expect(out.unresolvedZones).toBe(0)
|
||||
out.report.observations[0]!.zones.forEach((zone, i) => {
|
||||
const anno = draft.annotations.find((a) => a.id === zone.annotationId)
|
||||
expect(anno, zone.annotationId).toBeDefined()
|
||||
expect(anno!.view_id).toBe(zone.viewId)
|
||||
expect(zone.labelFrSnapshot).toBe(map.annotations[legacyIds[i]!]!.name.fr)
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps vertebrae on the spine zones with region codes the draft defines', () => {
|
||||
const codes = new Set(draft.vertebral_config.regions.map((r) => r.code))
|
||||
const spine = draft.annotations.filter(
|
||||
(a): a is Extract<Annotation, { kind: 'point' | 'zone' }> =>
|
||||
a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
|
||||
)
|
||||
expect(spine).toHaveLength(5)
|
||||
for (const anno of spine)
|
||||
expect(codes.has(anno.vertebral_region_code!)).toBe(true)
|
||||
const legacyId = Object.keys(map.annotations).find(
|
||||
(id) => map.annotations[id]!.id === 'cervical',
|
||||
)!
|
||||
const v2 = leavesAsV2Report([])
|
||||
v2.observations = [
|
||||
{
|
||||
id: 'spine',
|
||||
zones: [{ boneId: legacyId, vertebrae: [{ region: 'C', index: 7 }] }],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
},
|
||||
]
|
||||
const zone = migrateReportV2ToV3(v2, map).report.observations[0]!.zones[0]!
|
||||
expect(zone.vertebrae).toEqual([{ region: 'C', index: 7 }])
|
||||
expect(codes.has(zone.vertebrae![0]!.region)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,183 +0,0 @@
|
||||
import { ReportMigrationMapSchema } from '@faunosteo/domain'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyChangeset,
|
||||
buildReportMigrationMap,
|
||||
type DraftResult,
|
||||
type ImportResult,
|
||||
} from '../src'
|
||||
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
|
||||
import { runDraft } from './helpers'
|
||||
|
||||
const SHEET = {
|
||||
sheetId: 'sheet',
|
||||
versionId: null,
|
||||
documentSha256: 'f'.repeat(64),
|
||||
}
|
||||
|
||||
describe('report migration map on the real draft', () => {
|
||||
let result: ImportResult
|
||||
let draft: DraftResult
|
||||
let map: ReturnType<typeof buildReportMigrationMap>['map']
|
||||
let stats: ReturnType<typeof buildReportMigrationMap>['stats']
|
||||
|
||||
beforeAll(async () => {
|
||||
;({ result, draft } = await runDraft())
|
||||
;({ map, stats } = buildReportMigrationMap({
|
||||
baseline: draft.baseline as Record<string, unknown>,
|
||||
final: draft.document as Record<string, unknown>,
|
||||
legacyIdMap: draft.legacyIdMap,
|
||||
records: draft.records,
|
||||
sheet: SHEET,
|
||||
mainViewId: 'main',
|
||||
}))
|
||||
})
|
||||
|
||||
it('is a valid map covering every legacy node, with the expected fates', () => {
|
||||
expect(ReportMigrationMapSchema.parse(map)).toBeTruthy()
|
||||
expect(stats).toEqual({
|
||||
nodes: 792,
|
||||
identical: 571,
|
||||
remapped: 180,
|
||||
rehomed: 7,
|
||||
removed: 34,
|
||||
})
|
||||
expect(Object.keys(map.finding_paths)).toHaveLength(792)
|
||||
})
|
||||
|
||||
it('maps every legacy annotation with its legacy labels and the views', () => {
|
||||
expect(Object.keys(map.annotations)).toHaveLength(27)
|
||||
expect(map.annotations['point-mpbwtst0']).toEqual({
|
||||
id: 'hip',
|
||||
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
|
||||
})
|
||||
expect(map.annotations['zone-mpby55kd']).toEqual({
|
||||
id: 'head-trigger',
|
||||
name: { fr: '', en: '' },
|
||||
})
|
||||
expect(map.views).toEqual({ head: 'head' })
|
||||
expect(map.main_view_id).toBe('main')
|
||||
expect(result.legacyIdMap.annotations['point-mpbwtst0']).toBe('hip')
|
||||
})
|
||||
|
||||
it('every target path exists in the draft; identical, renamed, re-homed and removed cases', () => {
|
||||
const final = new Set<string>()
|
||||
for (const zone of draft.document.finding_zones) {
|
||||
const walk = (
|
||||
nodes: readonly { id: string; children?: readonly unknown[] }[],
|
||||
prefix: string,
|
||||
) => {
|
||||
for (const n of nodes) {
|
||||
final.add(`${prefix}/${n.id}`)
|
||||
walk((n.children ?? []) as never, `${prefix}/${n.id}`)
|
||||
}
|
||||
}
|
||||
walk(zone.categories as never, zone.id)
|
||||
}
|
||||
for (const target of Object.values(map.finding_paths)) {
|
||||
if (target !== null) expect(final.has(target), target).toBe(true)
|
||||
}
|
||||
expect(
|
||||
map.finding_paths['hip/hip-dysfunctions/articular/restriction-flexion'],
|
||||
).toBe('hip/hip-dysfunctions/articular/restriction-flexion')
|
||||
expect(
|
||||
map.finding_paths[
|
||||
'cervical/cervical-observations/stumbling-proprioceptive'
|
||||
],
|
||||
).toBe('cervical/cervical-consultation-reasons/stumbling-proprioceptive')
|
||||
expect(
|
||||
map.finding_paths[
|
||||
'sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-tension'
|
||||
],
|
||||
).toBe('sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-ligament')
|
||||
expect(
|
||||
map.finding_paths['sphenoid/ssb-dysfunctions/sutures/sphenopetrosal'],
|
||||
).toBe('sphenoid/sphenoid-dysfunctions/sutures/sphenopetrosal')
|
||||
expect(
|
||||
map.finding_paths['ssb/ssb-dysfunctions/sutures/sphenozygomatic'],
|
||||
).toBeNull()
|
||||
expect(
|
||||
map.finding_paths['frontal/frontal-dysfunctions/sutures/frontozygomatic'],
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('report migration map replay on a synthetic changeset', () => {
|
||||
function mapOf(ops: Parameters<typeof changesetOf>[0]) {
|
||||
const baseline = miniSheet()
|
||||
const result = applyChangeset(baseline, MINI_REFERENCES, changesetOf(ops))
|
||||
return buildReportMigrationMap({
|
||||
baseline: miniSheet() as never,
|
||||
final: result.document as never,
|
||||
legacyIdMap: {
|
||||
views: { head: 'head' },
|
||||
annotations: { 'legacy-hip': 'hip' },
|
||||
categories: {},
|
||||
finding_nodes: {},
|
||||
assets: {},
|
||||
},
|
||||
records: result.records,
|
||||
sheet: SHEET,
|
||||
mainViewId: 'main',
|
||||
})
|
||||
}
|
||||
|
||||
it('follows a rename, a move and a removal, and a renamed annotation', () => {
|
||||
const { map, stats } = mapOf([
|
||||
{
|
||||
op: 'rename',
|
||||
target: 'finding:hip/hip-dysfunctions/mobility',
|
||||
id: 'motion',
|
||||
},
|
||||
{
|
||||
op: 'move',
|
||||
target: 'finding:hip/hip-dysfunctions/motion/flexion',
|
||||
to: 'finding:hip/anamnesis',
|
||||
},
|
||||
{ op: 'remove', target: 'finding:neck/neck-dysfunctions/vet' },
|
||||
{ op: 'rename', target: 'annotation:hip', id: 'coxofemoral' },
|
||||
])
|
||||
expect(map.finding_paths['hip/hip-dysfunctions/mobility/extension']).toBe(
|
||||
'hip/hip-dysfunctions/motion/extension',
|
||||
)
|
||||
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
|
||||
'hip/anamnesis/flexion',
|
||||
)
|
||||
expect(map.finding_paths['neck/neck-dysfunctions/vet']).toBeNull()
|
||||
expect(map.finding_paths['neck/neck-dysfunctions/stiffness']).toBe(
|
||||
'neck/neck-dysfunctions/stiffness',
|
||||
)
|
||||
expect(map.annotations['legacy-hip']!.id).toBe('coxofemoral')
|
||||
expect(stats.removed).toBe(1)
|
||||
})
|
||||
|
||||
it('re-homes a node whose category was replaced by another one holding the same path', () => {
|
||||
const { map, stats } = mapOf([
|
||||
{
|
||||
op: 'add',
|
||||
target: 'zone:hip',
|
||||
value: {
|
||||
id: 'hip-new',
|
||||
kind: 'dysfunction',
|
||||
name: { fr: 'N', en: 'N' },
|
||||
children: [
|
||||
{
|
||||
id: 'mobility',
|
||||
name: { fr: 'M', en: 'M' },
|
||||
children: [{ id: 'flexion', name: { fr: 'F', en: 'F' } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{ op: 'remove', target: 'finding:hip/hip-dysfunctions' },
|
||||
])
|
||||
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
|
||||
'hip/hip-new/mobility/flexion',
|
||||
)
|
||||
expect(
|
||||
map.finding_paths['hip/hip-dysfunctions/mobility/extension'],
|
||||
).toBeNull()
|
||||
expect(map.finding_paths['hip/hip-dysfunctions']).toBeNull()
|
||||
expect(stats.rehomed).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { overlayMarkers, renderReviewOverlay } from '../src'
|
||||
import { miniSheet } from './fixtures/mini-sheet'
|
||||
|
||||
const DRAWING =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="10">' +
|
||||
'<path d="M0 0h10"/></svg>'
|
||||
|
||||
function moved() {
|
||||
const after = miniSheet()
|
||||
const hip = after.annotations.find((a) => a.id === 'hip')!
|
||||
hip.geometry = { type: 'circle', cx: 50, cy: 60, r: 3 }
|
||||
after.annotations.push({
|
||||
...hip,
|
||||
id: 'knee',
|
||||
geometry: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 0],
|
||||
[5, 5],
|
||||
],
|
||||
},
|
||||
})
|
||||
return after
|
||||
}
|
||||
|
||||
describe('review overlay', () => {
|
||||
it('marks moved annotations with their previous position', () => {
|
||||
const markers = overlayMarkers(miniSheet(), moved(), 'main')
|
||||
const byId = (id: string) => markers.filter((m) => m.id === id)
|
||||
expect(byId('hip').map((m) => m.status)).toEqual(['moved', 'removed'])
|
||||
expect(byId('knee').map((m) => m.status)).toEqual(['added'])
|
||||
expect(markers.every((m) => m.geometry !== null)).toBe(true)
|
||||
})
|
||||
|
||||
it('reports an annotation dropped by the changeset', () => {
|
||||
const after = miniSheet()
|
||||
after.annotations = after.annotations.filter((a) => a.id !== 'hip')
|
||||
const markers = overlayMarkers(miniSheet(), after, 'main')
|
||||
expect(markers.find((m) => m.id === 'hip')?.status).toBe('removed')
|
||||
})
|
||||
|
||||
it('renders a framed SVG with one group per marker and a legend', () => {
|
||||
const svg = renderReviewOverlay({
|
||||
cleanedSvg: DRAWING,
|
||||
before: miniSheet(),
|
||||
after: moved(),
|
||||
viewId: 'main',
|
||||
})
|
||||
const root = new DOMParser().parseFromString(
|
||||
svg,
|
||||
'image/svg+xml',
|
||||
).documentElement!
|
||||
expect(root.getAttribute('width')).toBeNull()
|
||||
const groups = Array.from(root.getElementsByTagName('g')).filter((g) =>
|
||||
g.hasAttribute('data-review-id'),
|
||||
)
|
||||
expect(groups.map((g) => g.getAttribute('data-review-status'))).toEqual([
|
||||
'moved',
|
||||
'removed',
|
||||
'added',
|
||||
])
|
||||
expect(svg).toContain('stroke-dasharray')
|
||||
expect(svg).toContain('inchangé')
|
||||
expect(svg).toContain('<path d="M0 0h10"/>')
|
||||
})
|
||||
|
||||
it('frames a detail view on its view box', () => {
|
||||
const after = moved()
|
||||
const svg = renderReviewOverlay({
|
||||
cleanedSvg: DRAWING,
|
||||
before: miniSheet(),
|
||||
after,
|
||||
viewId: after.views[1]!.id,
|
||||
})
|
||||
const box = after.views[1]!.view_box!
|
||||
expect(svg).toContain(
|
||||
`viewBox="${box.min_x} ${box.min_y} ${box.width} ${box.height}"`,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,110 +0,0 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
validateSheetDocument,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
buildEquineDraft,
|
||||
DRAFT_SEED_SQL_FILE,
|
||||
renderDraftArtifacts,
|
||||
type DraftResult,
|
||||
type ImportResult,
|
||||
} from '../src'
|
||||
import { changesetOf } from './fixtures/mini-sheet'
|
||||
import { runDraft } from './helpers'
|
||||
|
||||
const VIEW_BOX = { min_x: 0, min_y: 0, width: 1, height: 1 }
|
||||
|
||||
let result: ImportResult
|
||||
let draft: DraftResult
|
||||
let artifacts: Record<string, string>
|
||||
|
||||
beforeAll(async () => {
|
||||
;({ result, draft } = await runDraft())
|
||||
artifacts = await renderDraftArtifacts(draft, result.anomalies)
|
||||
})
|
||||
|
||||
const REVIEW_HEADINGS = [
|
||||
'1. Qualité des données initiales',
|
||||
'2. Principales erreurs anatomiques et ostéopathiques',
|
||||
'3. Corrections effectuées',
|
||||
'4. Ajouts',
|
||||
'5. Réorganisations du catalogue',
|
||||
'6. Éléments incertains',
|
||||
'7. Traductions',
|
||||
'8. Points de vigilance clinique',
|
||||
'9. Bibliographie',
|
||||
'10. Décisions réservées au professionnel',
|
||||
]
|
||||
|
||||
describe('equine working draft (real sources + committed curation)', () => {
|
||||
it('validates with zero integrity error', () => {
|
||||
const parsed = AnatomicalSheetDocumentSchema.parse(draft.document)
|
||||
const errors = validateSheetDocument(parsed).filter(
|
||||
(i) => i.severity === 'error',
|
||||
)
|
||||
expect(errors).toEqual([])
|
||||
expect(draft.sheetId).toBe(result.sheetId)
|
||||
})
|
||||
|
||||
it('carries one drawing and the curated content', () => {
|
||||
expect(draft.statsBefore.assets).toBe(2)
|
||||
expect(draft.statsAfter.assets).toBe(1)
|
||||
expect(draft.assets).toHaveLength(1)
|
||||
const [main, head] = draft.document.views
|
||||
expect(main!.svg_asset_id).toBe(draft.assets[0]!.svg_asset_id)
|
||||
expect(head).toMatchObject({
|
||||
svg_asset_id: null,
|
||||
view_box: { min_x: 60, min_y: 100, width: 500, height: 380 },
|
||||
})
|
||||
const cd = draft.document.vertebral_config.regions.find(
|
||||
(r) => r.code === 'Cd',
|
||||
)
|
||||
expect(cd!.count_range).toEqual({ min: 15, max: 21 })
|
||||
// Carpus zone added, linked from its annotation (CHG carpus_zone).
|
||||
const carpus = draft.document.annotations.find((a) => a.id === 'carpus')
|
||||
expect(carpus).toMatchObject({ finding_zone_id: 'carpus', kind: 'point' })
|
||||
expect(draft.document.finding_zones.some((z) => z.id === 'carpus')).toBe(
|
||||
true,
|
||||
)
|
||||
// Node volume: 792 legacy − SSB duplicates − absent sutures + carpus & flags.
|
||||
expect(draft.statsAfter.nodes).toBe(811)
|
||||
expect(draft.statsAfter.descriptionsFrOnly).toBe(0)
|
||||
})
|
||||
|
||||
it('lists CHG-000 and the Cd range change in the CHANGELOG', () => {
|
||||
const changelog = artifacts['CHANGELOG.md']!
|
||||
expect(changelog).toContain('## Comparaison quantitative')
|
||||
expect(changelog).toMatch(/\| `CHG-000` .*`view:head\.view_box`/)
|
||||
expect(changelog).toMatch(/\| `CHG-\d{3}` .*`region:Cd\.count_range`/)
|
||||
})
|
||||
|
||||
it('writes the ten review sections in order', () => {
|
||||
const headings = [
|
||||
...artifacts['REVIEW-REPORT.md']!.matchAll(/^## (.+)$/gm),
|
||||
].map((m) => m[1])
|
||||
expect(headings).toEqual(REVIEW_HEADINGS)
|
||||
})
|
||||
|
||||
it('seeds a converging draft and never publishes', () => {
|
||||
const sql = artifacts[DRAFT_SEED_SQL_FILE]!
|
||||
expect(sql).toContain('private.insert_sheet_draft')
|
||||
expect(sql).toMatch(
|
||||
/update public\.anatomical_sheet_versions[\s\S]*status = 'draft'/,
|
||||
)
|
||||
expect(sql).not.toContain('publish_sheet_version')
|
||||
})
|
||||
|
||||
it('refuses a changeset that reuses the reserved CHG-000', () => {
|
||||
const [own] = changesetOf([{ op: 'remove', target: 'zone:hip' }]).changes
|
||||
const changeset = { changes: [{ ...own!, id: 'CHG-000' }] }
|
||||
const input = { importResult: result, legacyMainSvgBytes: new Uint8Array() }
|
||||
expect(() =>
|
||||
buildEquineDraft({
|
||||
...input,
|
||||
headViewBox: VIEW_BOX,
|
||||
references: [],
|
||||
changeset,
|
||||
}),
|
||||
).toThrow('CHG-000 is reserved')
|
||||
})
|
||||
})
|
||||
@@ -1,85 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
ChangesetSchema,
|
||||
EQUINE_CURATION_DIR,
|
||||
ReferencesFileSchema,
|
||||
needsConfirmation,
|
||||
} from '../src'
|
||||
import { REPO_ROOT } from './helpers'
|
||||
|
||||
async function committed(file: string): Promise<unknown> {
|
||||
return JSON.parse(
|
||||
await readFile(join(REPO_ROOT, EQUINE_CURATION_DIR, file), 'utf8'),
|
||||
)
|
||||
}
|
||||
|
||||
const CHANGE = {
|
||||
id: 'CHG-002',
|
||||
level: 'B',
|
||||
kind: 'terminology',
|
||||
title: { fr: 'Titre', en: 'Title' },
|
||||
rationale: 'Raison',
|
||||
reference_ids: [],
|
||||
ops: [{ op: 'remove', target: 'zone:x' }],
|
||||
}
|
||||
|
||||
describe('curation schemas', () => {
|
||||
it('parse the committed curation files', async () => {
|
||||
const changeset = ChangesetSchema.parse(await committed('changes.json'))
|
||||
const ids = changeset.changes.map((c) => c.id)
|
||||
expect(ids[0]).toBe('CHG-001')
|
||||
expect(ids).toEqual([...ids].sort())
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(changeset.changes.every((c) => c.level !== 'C' || c.question)).toBe(
|
||||
true,
|
||||
)
|
||||
const refs = ReferencesFileSchema.parse(await committed('references.json'))
|
||||
const refIds = refs.references.map((r) => r.id)
|
||||
expect(refIds).toContain('legacy-catalog')
|
||||
expect(new Set(refIds).size).toBe(refIds.length)
|
||||
const cited = new Set(changeset.changes.flatMap((c) => c.reference_ids))
|
||||
for (const id of cited) expect(refIds).toContain(id)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'an unknown op',
|
||||
{ ...CHANGE, ops: [{ op: 'replace', target: 'zone:x' }] },
|
||||
],
|
||||
['a level C change without question', { ...CHANGE, level: 'C' }],
|
||||
['a bad change id', { ...CHANGE, id: 'CHANGE-1' }],
|
||||
['a change without ops', { ...CHANGE, ops: [] }],
|
||||
['an unknown key', { ...CHANGE, needs_confirmation: true }],
|
||||
])('rejects %s', (_label, change) => {
|
||||
expect(ChangesetSchema.safeParse({ changes: [change] }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts a level C change with its question', () => {
|
||||
const change = {
|
||||
...CHANGE,
|
||||
level: 'C',
|
||||
question: 'Faut-il ?',
|
||||
priority: 'high',
|
||||
}
|
||||
expect(ChangesetSchema.safeParse({ changes: [change] }).success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects duplicate change ids and duplicate reference ids', () => {
|
||||
expect(
|
||||
ChangesetSchema.safeParse({ changes: [CHANGE, CHANGE] }).success,
|
||||
).toBe(false)
|
||||
const ref = { id: 'a', type: 'web', citation: 'A', url: null, doi: null }
|
||||
expect(
|
||||
ReferencesFileSchema.safeParse({ references: [ref, ref] }).success,
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('derives needs_confirmation from the level', () => {
|
||||
expect(['A', 'B', 'C'].map((l) => needsConfirmation(l as 'A'))).toEqual([
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,23 +0,0 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
validateSheetDocument,
|
||||
} from '@faunosteo/domain'
|
||||
import { importEquineLegacy, renderArtifacts } from '../src'
|
||||
import { loadInput, runImport } from './helpers'
|
||||
|
||||
describe('equine document', () => {
|
||||
it('parses and validates with no error and no warning', async () => {
|
||||
const { document, issues } = await runImport()
|
||||
const parsed = AnatomicalSheetDocumentSchema.parse(document)
|
||||
expect(validateSheetDocument(parsed)).toEqual([])
|
||||
expect(issues).toEqual([])
|
||||
})
|
||||
|
||||
it('is deterministic: same result and same bytes on two runs', async () => {
|
||||
const input = await loadInput()
|
||||
const first = importEquineLegacy(input)
|
||||
const second = importEquineLegacy(input)
|
||||
expect(second).toEqual(first)
|
||||
expect(await renderArtifacts(second)).toEqual(await renderArtifacts(first))
|
||||
})
|
||||
})
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
FindingNodeInput,
|
||||
Reference,
|
||||
} from '@faunosteo/domain'
|
||||
import type { ChangeInput, Changeset, Op } from '../../src'
|
||||
import { ChangesetSchema } from '../../src'
|
||||
|
||||
/**
|
||||
* Small synthetic sheet for the curation unit tests: two finding zones with
|
||||
* nested nodes, two observable annotations, one detail view opened by a
|
||||
* trigger. Lean input form, zero integrity issue as written.
|
||||
*/
|
||||
|
||||
function leaf(
|
||||
id: string,
|
||||
extra: Partial<FindingNodeInput> = {},
|
||||
): FindingNodeInput {
|
||||
return { id, name: { fr: `${id} fr`, en: `${id} en` }, ...extra }
|
||||
}
|
||||
|
||||
export const MINI_REFERENCES: Reference[] = [
|
||||
{
|
||||
id: 'atlas',
|
||||
type: 'book',
|
||||
citation: 'Atlas of anatomy',
|
||||
url: null,
|
||||
doi: null,
|
||||
},
|
||||
{
|
||||
id: 'paper',
|
||||
type: 'journal',
|
||||
citation: 'A paper',
|
||||
url: null,
|
||||
doi: '10.1/x',
|
||||
},
|
||||
]
|
||||
|
||||
export function miniSheet(): AnatomicalSheetDocumentInput {
|
||||
return {
|
||||
schema_version: 2,
|
||||
species_id: 'equine',
|
||||
name: { fr: 'Mini', en: 'Mini' },
|
||||
description: {},
|
||||
scope_disclaimer: {},
|
||||
attribution: { authors: [], license: null, notes: null },
|
||||
vertebral_config: {
|
||||
regions: [
|
||||
{ code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 },
|
||||
{ code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 },
|
||||
],
|
||||
},
|
||||
references: [],
|
||||
categories: [
|
||||
{
|
||||
id: 'joints',
|
||||
name: { fr: 'Articulations', en: 'Joints' },
|
||||
color: null,
|
||||
},
|
||||
{ id: 'bones', name: { fr: 'Os', en: 'Bones' }, color: null },
|
||||
],
|
||||
views: [
|
||||
{
|
||||
id: 'main',
|
||||
kind: 'main',
|
||||
name: { fr: 'Vue', en: 'View' },
|
||||
svg_asset_id: '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8',
|
||||
view_box: null,
|
||||
},
|
||||
{
|
||||
id: 'head',
|
||||
kind: 'detail',
|
||||
parent_view_id: 'main',
|
||||
name: { fr: 'Tête', en: 'Head' },
|
||||
svg_asset_id: null,
|
||||
view_box: { min_x: 0, min_y: 0, width: 10, height: 10 },
|
||||
},
|
||||
],
|
||||
annotations: [
|
||||
{
|
||||
id: 'hip',
|
||||
kind: 'point',
|
||||
view_id: 'main',
|
||||
category_id: 'joints',
|
||||
laterality: 'bilateral',
|
||||
geometry: { type: 'circle', cx: 1, cy: 2, r: 3 },
|
||||
name: { fr: 'Hanche', en: 'Hip' },
|
||||
finding_zone_id: 'hip',
|
||||
vertebral_region_code: null,
|
||||
},
|
||||
{
|
||||
id: 'neck',
|
||||
kind: 'zone',
|
||||
view_id: 'main',
|
||||
category_id: 'bones',
|
||||
laterality: 'unpaired',
|
||||
geometry: null,
|
||||
name: { fr: 'Cou', en: 'Neck' },
|
||||
finding_zone_id: 'neck',
|
||||
vertebral_region_code: 'C',
|
||||
},
|
||||
{
|
||||
id: 'head-trigger',
|
||||
kind: 'detail_trigger',
|
||||
view_id: 'main',
|
||||
category_id: 'bones',
|
||||
laterality: 'unpaired',
|
||||
geometry: null,
|
||||
name: null,
|
||||
opens_view_id: 'head',
|
||||
},
|
||||
],
|
||||
finding_zones: [
|
||||
{
|
||||
id: 'hip',
|
||||
name: { fr: 'Hanche', en: 'Hip' },
|
||||
categories: [
|
||||
{
|
||||
id: 'hip-dysfunctions',
|
||||
kind: 'dysfunction',
|
||||
name: { fr: 'Dysfonctions', en: 'Dysfunctions' },
|
||||
children: [
|
||||
leaf('mobility', {
|
||||
children: [leaf('flexion'), leaf('extension')],
|
||||
}),
|
||||
leaf('pain'),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'anamnesis',
|
||||
kind: 'anamnesis',
|
||||
name: { fr: 'Anamnèse', en: 'Anamnesis' },
|
||||
children: [leaf('trauma')],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'neck',
|
||||
name: { fr: 'Cou', en: 'Neck' },
|
||||
categories: [
|
||||
{
|
||||
id: 'neck-dysfunctions',
|
||||
kind: 'dysfunction',
|
||||
name: { fr: 'Dysfonctions', en: 'Dysfunctions' },
|
||||
children: [
|
||||
leaf('stiffness'),
|
||||
leaf('vet', { requires_vet_referral: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/** One level A change carrying the given ops, parsed like changes.json. */
|
||||
export function changesetOf(
|
||||
ops: Op[],
|
||||
extra: Partial<ChangeInput> = {},
|
||||
): Changeset {
|
||||
return ChangesetSchema.parse({
|
||||
changes: [
|
||||
{
|
||||
id: 'CHG-001',
|
||||
level: 'A',
|
||||
kind: 'technical',
|
||||
title: { fr: 'Essai', en: 'Test' },
|
||||
rationale: 'Essai',
|
||||
reference_ids: [],
|
||||
ops,
|
||||
...extra,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
buildEquineDraft,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
HEAD_VIEW_ID,
|
||||
importEquineLegacy,
|
||||
parseViewBox,
|
||||
readEquineCuration,
|
||||
readEquineSources,
|
||||
type DraftResult,
|
||||
type EquineLegacyInput,
|
||||
type ImportResult,
|
||||
} from '../src'
|
||||
import type { LegacyCatalog } from '../src/legacy/catalog'
|
||||
|
||||
/** Tests run on the real legacy sources, never on copies. */
|
||||
export const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url))
|
||||
|
||||
export function loadInput(): Promise<EquineLegacyInput> {
|
||||
return readEquineSources(REPO_ROOT)
|
||||
}
|
||||
|
||||
export async function runImport(): Promise<ImportResult> {
|
||||
return importEquineLegacy(await loadInput())
|
||||
}
|
||||
|
||||
export async function loadCatalog(): Promise<LegacyCatalog> {
|
||||
const text = await readFile(
|
||||
join(REPO_ROOT, EQUINE_SOURCE_PATHS.catalog),
|
||||
'utf8',
|
||||
)
|
||||
return JSON.parse(text) as LegacyCatalog
|
||||
}
|
||||
|
||||
export async function legacyAnnoIds(path: string): Promise<string[]> {
|
||||
const text = await readFile(join(REPO_ROOT, path), 'utf8')
|
||||
const ids = [...text.matchAll(/data-anno-id="([^"]+)"/g)].map((m) => m[1]!)
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
/** Legacy import + committed curation files → the working draft. */
|
||||
export async function runDraft(): Promise<{
|
||||
result: ImportResult
|
||||
draft: DraftResult
|
||||
}> {
|
||||
const input = await loadInput()
|
||||
const result = importEquineLegacy(input)
|
||||
const draft = buildEquineDraft({
|
||||
importResult: result,
|
||||
legacyMainSvgBytes: input.mainSvg.bytes,
|
||||
headViewBox: parseViewBox(result.viewBoxes[HEAD_VIEW_ID] ?? null),
|
||||
...(await readEquineCuration(REPO_ROOT)),
|
||||
})
|
||||
return { result, draft }
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import type { FindingNodeInput } from '@faunosteo/domain'
|
||||
import { EQUINE_SOURCE_PATHS, type ImportResult } from '../src'
|
||||
import { legacyAnnoIds, runImport } from './helpers'
|
||||
|
||||
let result: ImportResult
|
||||
|
||||
beforeAll(async () => {
|
||||
result = await runImport()
|
||||
})
|
||||
|
||||
describe('equine import volumes', () => {
|
||||
it('imports 27 annotations, 26 linked to a finding zone', () => {
|
||||
const annotations = result.document.annotations
|
||||
expect(annotations).toHaveLength(27)
|
||||
const linked = annotations.filter(
|
||||
(a) => a.kind !== 'detail_trigger' && a.finding_zone_id !== null,
|
||||
)
|
||||
expect(linked).toHaveLength(26)
|
||||
})
|
||||
|
||||
it('has two views and one trigger opening head from main', () => {
|
||||
expect(result.document.views.map((v) => v.id)).toEqual(['main', 'head'])
|
||||
const triggers = result.document.annotations.filter(
|
||||
(a) => a.kind === 'detail_trigger',
|
||||
)
|
||||
expect(triggers).toHaveLength(1)
|
||||
expect(triggers[0]).toMatchObject({
|
||||
view_id: 'main',
|
||||
opens_view_id: 'head',
|
||||
})
|
||||
})
|
||||
|
||||
it('codes exactly the five zone-colonne polygons with C, T, L, S, Cd', () => {
|
||||
const coded = result.document.annotations.filter(
|
||||
(a) => a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
|
||||
)
|
||||
expect(coded).toHaveLength(5)
|
||||
expect(new Set(coded.map((a) => a.kind))).toEqual(new Set(['zone']))
|
||||
expect(new Set(coded.map((a) => a.category_id))).toEqual(
|
||||
new Set(['zone-colonne']),
|
||||
)
|
||||
const codes = coded.map((a) =>
|
||||
a.kind === 'detail_trigger' ? null : a.vertebral_region_code,
|
||||
)
|
||||
expect(new Set(codes)).toEqual(new Set(['C', 'T', 'L', 'S', 'Cd']))
|
||||
})
|
||||
|
||||
it('counts 9 bilateral annotations', () => {
|
||||
const bilateral = result.document.annotations.filter(
|
||||
(a) => a.laterality === 'bilateral',
|
||||
)
|
||||
expect(bilateral).toHaveLength(9)
|
||||
})
|
||||
|
||||
it('writes 792 nodes, 612 leaves, 41 vet referrals in the document', () => {
|
||||
const counts = { nodes: 0, leaves: 0, vet: 0 }
|
||||
const walk = (nodes: readonly FindingNodeInput[]): void => {
|
||||
for (const node of nodes) {
|
||||
counts.nodes += 1
|
||||
if (!node.children?.length) counts.leaves += 1
|
||||
if (node.requires_vet_referral === true) counts.vet += 1
|
||||
walk(node.children ?? [])
|
||||
}
|
||||
}
|
||||
for (const zone of result.document.finding_zones) {
|
||||
counts.nodes += zone.categories.length
|
||||
for (const category of zone.categories) walk(category.children)
|
||||
}
|
||||
expect(counts).toEqual({ nodes: 792, leaves: 612, vet: 41 })
|
||||
})
|
||||
|
||||
it('reports the input side from the sources: 27 ids, 26 zones, 792/612/41', () => {
|
||||
expect(result.document.finding_zones).toHaveLength(26)
|
||||
expect(result.stats).toMatchObject({
|
||||
legacyAnnotations: 27,
|
||||
findingZones: 26,
|
||||
nodes: 792,
|
||||
leaves: 612,
|
||||
vetReferrals: 41,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps every data-anno-id of both SVGs', async () => {
|
||||
const ids = [
|
||||
...(await legacyAnnoIds(EQUINE_SOURCE_PATHS.mainSvg)),
|
||||
...(await legacyAnnoIds(EQUINE_SOURCE_PATHS.headSvg)),
|
||||
]
|
||||
expect(ids).toHaveLength(27)
|
||||
expect(Object.keys(result.legacyIdMap.annotations).sort()).toEqual(
|
||||
ids.sort(),
|
||||
)
|
||||
})
|
||||
|
||||
it('places the nine head annotations in view head', async () => {
|
||||
const headIds = await legacyAnnoIds(EQUINE_SOURCE_PATHS.headSvg)
|
||||
const newIds = new Set(
|
||||
headIds.map((id) => result.legacyIdMap.annotations[id]),
|
||||
)
|
||||
const inHead = result.document.annotations.filter((a) => newIds.has(a.id))
|
||||
expect(inHead).toHaveLength(9)
|
||||
expect(inHead.every((a) => a.view_id === 'head')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
import { DOCUMENT_DOLLAR_TAG, renderDraftSeedSql } from '../src'
|
||||
import { mapAnnotation } from '../src/legacy/annotations'
|
||||
import { assertNothingDropped } from '../src/legacy/catalog'
|
||||
import { parseAnnotatedSvg } from '../src/legacy/svg'
|
||||
import { runImport } from './helpers'
|
||||
|
||||
/** Guards that never fire on today's data, proven on synthetic inputs. */
|
||||
|
||||
const SVG_WITHOUT_EN = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">
|
||||
<circle cx="1" cy="2" r="3" data-anno-id="point-x"
|
||||
data-anno-name-fr="Garrot" data-anno-category="os"/>
|
||||
</svg>`
|
||||
|
||||
describe('importer guards', () => {
|
||||
it('throws when a zone loses a vet referral', () => {
|
||||
const before = { nodes: 10, leaves: 7, vetReferrals: 2 }
|
||||
const after = { nodes: 10, leaves: 7, vetReferrals: 1 }
|
||||
expect(() => assertNothingDropped('hip', before, after)).toThrow(
|
||||
'zone hip: vetReferrals 2 in, 1 out',
|
||||
)
|
||||
expect(() => assertNothingDropped('hip', before, before)).not.toThrow()
|
||||
})
|
||||
|
||||
it('copies FR into EN when data-anno-name-en is absent, and says so', () => {
|
||||
const [legacy] = parseAnnotatedSvg(SVG_WITHOUT_EN, 'x.svg').annotations
|
||||
const mapped = mapAnnotation(legacy!, {
|
||||
viewId: 'main',
|
||||
fileName: 'x.svg',
|
||||
zoneByNames: new Map(),
|
||||
})
|
||||
expect(mapped.annotation.name).toEqual({ fr: 'Garrot', en: 'Garrot' })
|
||||
expect(mapped.anomalies.map((a) => [a.code, a.level])).toContainEqual([
|
||||
'annotation.name_en.missing',
|
||||
'a_valider',
|
||||
])
|
||||
})
|
||||
|
||||
it('refuses a document that contains the dollar-quote tag', async () => {
|
||||
const result = await runImport()
|
||||
const documentJson = JSON.stringify({ note: DOCUMENT_DOLLAR_TAG })
|
||||
const params = { sheetId: result.sheetId, assets: [], changeNote: 'x' }
|
||||
expect(() => renderDraftSeedSql({ ...params, documentJson })).toThrow(
|
||||
DOCUMENT_DOLLAR_TAG,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,128 +0,0 @@
|
||||
import type { FindingNodeInput } from '@faunosteo/domain'
|
||||
import { renderImportReport, type ImportResult } from '../src'
|
||||
import type { LegacyCatalog, LegacyNode } from '../src/legacy/catalog'
|
||||
import { loadCatalog, runImport } from './helpers'
|
||||
|
||||
let result: ImportResult
|
||||
let catalog: LegacyCatalog
|
||||
|
||||
beforeAll(async () => {
|
||||
;[result, catalog] = await Promise.all([runImport(), loadCatalog()])
|
||||
})
|
||||
|
||||
function annotation(id: string) {
|
||||
const found = result.document.annotations.find((a) => a.id === id)
|
||||
if (!found) throw new Error(`annotation ${id} missing`)
|
||||
return found
|
||||
}
|
||||
|
||||
function zone(id: string) {
|
||||
const found = result.document.finding_zones.find((z) => z.id === id)
|
||||
if (!found) throw new Error(`zone ${id} missing`)
|
||||
return found
|
||||
}
|
||||
|
||||
/** Id skeleton of a tree: same shape whatever the label language. */
|
||||
function idTree(
|
||||
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
|
||||
): unknown[] {
|
||||
return nodes.map((n) => [n.id, idTree(n.children ?? [])])
|
||||
}
|
||||
|
||||
describe('equine import special cases', () => {
|
||||
it('turns vertebral-precision into a region code', () => {
|
||||
expect(annotation('lumbar')).toMatchObject({
|
||||
kind: 'zone',
|
||||
vertebral_region_code: 'L',
|
||||
finding_zone_id: 'lumbar',
|
||||
})
|
||||
expect(annotation('caudal')).toMatchObject({ vertebral_region_code: 'Cd' })
|
||||
})
|
||||
|
||||
it('makes data-anno-lateral explicit', () => {
|
||||
expect(annotation('hip').laterality).toBe('bilateral')
|
||||
expect(annotation('c7-t1').laterality).toBe('unpaired')
|
||||
})
|
||||
|
||||
it('imports the trigger without name and without finding zone', () => {
|
||||
const trigger = annotation('head-trigger')
|
||||
expect(trigger.kind).toBe('detail_trigger')
|
||||
expect(trigger.name).toBeNull()
|
||||
expect(trigger).not.toHaveProperty('finding_zone_id')
|
||||
})
|
||||
|
||||
it('keeps ssb-dysfunctions under sphenoid and names it in the report', () => {
|
||||
expect(zone('sphenoid').categories[0]!.id).toBe('ssb-dysfunctions')
|
||||
expect(zone('ssb').categories[0]!.id).toBe('ssb-dysfunctions')
|
||||
const report = renderImportReport(result)
|
||||
expect(report).toContain('sphenoid/ssb-dysfunctions')
|
||||
expect(report).toContain('sphenoid-dysfunctions attendu')
|
||||
})
|
||||
|
||||
it('keeps the anamnesis category in all zones with its three variants', () => {
|
||||
const imported = result.document.finding_zones.map((z) => {
|
||||
const category = z.categories.find((c) => c.id === 'anamnesis')
|
||||
expect(category?.kind).toBe('anamnesis')
|
||||
return idTree(category?.children ?? []).join('|')
|
||||
})
|
||||
const legacy = Object.values(catalog.zones).map((z) =>
|
||||
idTree(
|
||||
z.categories.find((c) => c.id === 'anamnesis')!.children ?? [],
|
||||
).join('|'),
|
||||
)
|
||||
expect(imported).toHaveLength(26)
|
||||
expect(imported).toEqual(legacy)
|
||||
expect(new Set(imported).size).toBe(3)
|
||||
})
|
||||
|
||||
it('writes no en key where description_en is absent', () => {
|
||||
const category = zone('parietal').categories.find(
|
||||
(c) => c.id === 'anamnesis',
|
||||
)!
|
||||
expect(category.description).toEqual({
|
||||
fr: catalog.zones.parietal!.categories[2]!.description_fr,
|
||||
})
|
||||
const mobility = zone('parietal').categories[0]!.children[0]!
|
||||
expect(mobility.description).toBeDefined()
|
||||
expect(mobility.description).not.toHaveProperty('en')
|
||||
})
|
||||
|
||||
it('maps category kinds from their ids', () => {
|
||||
const kinds = zone('hip').categories.map((c) => [c.id, c.kind])
|
||||
expect(kinds).toEqual([
|
||||
['hip-dysfunctions', 'dysfunction'],
|
||||
['hip-observations', 'consultation_reason'],
|
||||
['anamnesis', 'anamnesis'],
|
||||
])
|
||||
})
|
||||
|
||||
it('preserves node ids at every level of every zone', () => {
|
||||
for (const [key, legacy] of Object.entries(catalog.zones)) {
|
||||
expect(idTree(zone(key).categories)).toEqual(idTree(legacy.categories))
|
||||
}
|
||||
})
|
||||
|
||||
it('writes the lean form: no default keys on plain leaves', () => {
|
||||
const leaf = zone('parietal').categories[0]!.children[0]!.children![0]!
|
||||
expect(Object.keys(leaf).sort()).toEqual(['id', 'name'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('importer-authored labels', () => {
|
||||
it('declares every label written without a source', () => {
|
||||
const subjects = result.anomalies
|
||||
.filter((a) => a.code === 'label.authored' && a.level === 'a_valider')
|
||||
.map((a) => a.subject)
|
||||
expect(subjects).toEqual([
|
||||
'name',
|
||||
'description',
|
||||
'views.main',
|
||||
'views.head',
|
||||
'vertebral_config.C',
|
||||
'vertebral_config.T',
|
||||
'vertebral_config.L',
|
||||
'vertebral_config.S',
|
||||
'vertebral_config.Cd',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inferRegionCode } from '../src/legacy/regions'
|
||||
|
||||
const code = (fr: string | null, en: string | null = null) =>
|
||||
inferRegionCode(fr, en)?.code
|
||||
|
||||
describe('inferRegionCode', () => {
|
||||
it('matches FR roots, with and without accents', () => {
|
||||
expect(code('Vertèbres cervicales')).toBe('C')
|
||||
expect(code('Vertebres cervicales')).toBe('C')
|
||||
expect(code('Vertèbres thoraciques')).toBe('T')
|
||||
expect(code('Vertebres thoraciques')).toBe('T')
|
||||
expect(code('Vertèbres lombaires')).toBe('L')
|
||||
expect(code('Vertèbres sacrales')).toBe('S')
|
||||
expect(code('Vertèbres sacrées')).toBe('S')
|
||||
expect(code('Vertèbres caudales')).toBe('Cd')
|
||||
expect(code('Vertèbres coccygiennes')).toBe('Cd')
|
||||
expect(code('Région dorsale')).toBe('T')
|
||||
})
|
||||
|
||||
it('matches EN roots when the FR label is absent', () => {
|
||||
expect(code(null, 'Cervical Vertebrae')).toBe('C')
|
||||
expect(code(null, 'Thoracic Vertebrae')).toBe('T')
|
||||
expect(code(null, 'Lumbar Vertebrae')).toBe('L')
|
||||
expect(code(null, 'Sacral Vertebrae')).toBe('S')
|
||||
expect(code(null, 'Coccygeal Vertebrae')).toBe('Cd')
|
||||
})
|
||||
|
||||
it('returns null when no root matches', () => {
|
||||
expect(inferRegionCode('Épaule', 'Shoulder')).toBeNull()
|
||||
expect(inferRegionCode('', '')).toBeNull()
|
||||
expect(inferRegionCode(null, null)).toBeNull()
|
||||
})
|
||||
|
||||
it('reports the matched root and label, FR before EN', () => {
|
||||
expect(inferRegionCode('Vertèbres lombaires', 'Cervical')).toEqual({
|
||||
code: 'L',
|
||||
root: 'lombair',
|
||||
label: 'Vertèbres lombaires',
|
||||
})
|
||||
expect(code('Épaule', 'Cervical Vertebrae')).toBe('C')
|
||||
})
|
||||
})
|
||||
@@ -1,162 +0,0 @@
|
||||
/**
|
||||
* R3 freeze O2 (plan 2026-10-14 §3): the annotation layer as the TypeScript
|
||||
* renderer builds it, attribute order kept, for the Rust layer to reproduce
|
||||
* exactly. Cases: the curated draft (main, head; no state, a state set,
|
||||
* every annotation) and an edge document covering what the draft lacks
|
||||
* (shape by geometry type, twin radius floor, exponent numbers, path
|
||||
* geometry, a circle trigger without a name, colour fallback, laterality).
|
||||
* `MAKE_R3_ORACLES=1` writes `crates/core/tests/oracles/r3/layer.json`;
|
||||
* otherwise the TypeScript still matches its own freeze (it is frozen too).
|
||||
*/
|
||||
import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
type AnatomicalSheetDocument,
|
||||
type AnatomicalSheetDocumentInput,
|
||||
} from '@faunosteo/domain'
|
||||
import { renderAnnotationLayer, type AnnotationState } from '../src/render'
|
||||
import { miniSheet } from './fixtures/mini-sheet'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const ORACLES = resolve(HERE, '../../../crates/core/tests/oracles')
|
||||
const OUT = resolve(ORACLES, 'r3/layer.json')
|
||||
const MAKE = process.env.MAKE_R3_ORACLES === '1'
|
||||
|
||||
function draft(): AnatomicalSheetDocument {
|
||||
const file = JSON.parse(readFileSync(resolve(ORACLES, 'sheet.draft.json'), 'utf8'))
|
||||
return file.output as AnatomicalSheetDocument
|
||||
}
|
||||
|
||||
const observable = {
|
||||
category_id: 'joints',
|
||||
laterality: 'unpaired' as const,
|
||||
finding_zone_id: 'hip',
|
||||
vertebral_region_code: null,
|
||||
}
|
||||
|
||||
/** The mini sheet plus one annotation per behaviour the draft never exercises. */
|
||||
export function edgeDocument(): AnatomicalSheetDocument {
|
||||
const base = miniSheet()
|
||||
const doc: AnatomicalSheetDocumentInput = {
|
||||
...base,
|
||||
categories: [
|
||||
{ id: 'joints', name: { fr: 'Articulations', en: 'Joints' }, color: '#ff9500' },
|
||||
{ id: 'bones', name: { fr: 'Os', en: 'Bones' }, color: null },
|
||||
],
|
||||
annotations: [
|
||||
...base.annotations,
|
||||
{
|
||||
...observable,
|
||||
id: 'point-polygon',
|
||||
kind: 'point',
|
||||
view_id: 'main',
|
||||
laterality: 'left',
|
||||
geometry: { type: 'polygon', points: [[0.1, 0.2], [1.5e-7, 3], [2, 1e21]] },
|
||||
name: { fr: 'Polygone « point »', en: 'Point & <polygon>' },
|
||||
},
|
||||
{
|
||||
...observable,
|
||||
id: 'zone-circle',
|
||||
kind: 'zone',
|
||||
view_id: 'main',
|
||||
laterality: 'right',
|
||||
geometry: { type: 'circle', cx: 743.0451049804688, cy: 0.30000000000000004, r: 12.5 },
|
||||
name: { fr: 'Zone ronde', en: 'Round zone' },
|
||||
color: '#123456',
|
||||
},
|
||||
{
|
||||
...observable,
|
||||
id: 'zone-path',
|
||||
kind: 'zone',
|
||||
view_id: 'main',
|
||||
category_id: 'bones',
|
||||
geometry: { type: 'path', d: 'M0 0 L10 10 Z' },
|
||||
name: { fr: 'Chemin', en: 'Path' },
|
||||
finding_zone_id: null,
|
||||
vertebral_region_code: 'T',
|
||||
},
|
||||
{
|
||||
id: 'trigger-circle',
|
||||
kind: 'detail_trigger',
|
||||
view_id: 'main',
|
||||
category_id: 'missing-category',
|
||||
laterality: 'unpaired',
|
||||
geometry: { type: 'circle', cx: 5, cy: 5, r: 40 },
|
||||
name: null,
|
||||
opens_view_id: 'head',
|
||||
},
|
||||
{
|
||||
id: 'trigger-named',
|
||||
kind: 'detail_trigger',
|
||||
view_id: 'main',
|
||||
category_id: 'bones',
|
||||
laterality: 'unpaired',
|
||||
geometry: { type: 'polygon', points: [[0, 0], [1, 0], [1, 1]] },
|
||||
name: { fr: 'Ouvrir', en: 'Open' },
|
||||
opens_view_id: 'head',
|
||||
},
|
||||
{
|
||||
...observable,
|
||||
id: 'head-point',
|
||||
kind: 'point',
|
||||
view_id: 'head',
|
||||
laterality: 'bilateral',
|
||||
geometry: { type: 'circle', cx: 1, cy: 1, r: 27.5 },
|
||||
name: { fr: 'Tête', en: 'Head' },
|
||||
},
|
||||
],
|
||||
}
|
||||
return AnatomicalSheetDocumentSchema.parse(doc)
|
||||
}
|
||||
|
||||
interface LayerCase {
|
||||
doc: 'draft' | 'edge'
|
||||
viewId: string
|
||||
states: string[]
|
||||
layer: unknown
|
||||
}
|
||||
|
||||
function layerCase(
|
||||
name: LayerCase['doc'],
|
||||
document: AnatomicalSheetDocument,
|
||||
viewId: string,
|
||||
states: string[],
|
||||
): LayerCase {
|
||||
const map = new Map<string, AnnotationState>(states.map((id) => [id, 'current']))
|
||||
return { doc: name, viewId, states, layer: renderAnnotationLayer({ document, viewId, states: map }) }
|
||||
}
|
||||
|
||||
function cases(): { edge: AnatomicalSheetDocument; cases: LayerCase[] } {
|
||||
const d = draft()
|
||||
const e = edgeDocument()
|
||||
const allDraft = d.annotations.map((a) => a.id)
|
||||
const allEdge = e.annotations.map((a) => a.id)
|
||||
return {
|
||||
edge: e,
|
||||
cases: [
|
||||
layerCase('draft', d, 'main', []),
|
||||
layerCase('draft', d, 'main', ['hip', 'cervical', 'head-trigger', 'atm']),
|
||||
layerCase('draft', d, 'main', allDraft),
|
||||
layerCase('draft', d, 'head', []),
|
||||
layerCase('draft', d, 'head', ['atm', 'frontal', 'hip']),
|
||||
layerCase('edge', e, 'main', []),
|
||||
layerCase('edge', e, 'main', allEdge),
|
||||
layerCase('edge', e, 'head', ['head-point']),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
describe('R3 layer oracles (TypeScript freeze)', () => {
|
||||
it('matches the frozen layer trees', () => {
|
||||
const actual = cases()
|
||||
if (MAKE) {
|
||||
mkdirSync(dirname(OUT), { recursive: true })
|
||||
writeFileSync(OUT, `${JSON.stringify(actual, null, 1)}\n`)
|
||||
return
|
||||
}
|
||||
expect(actual).toEqual(JSON.parse(readFileSync(OUT, 'utf8')))
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,391 +0,0 @@
|
||||
/**
|
||||
* R5.2 freeze (owner brief 2026-10-22 §9): the formatting and JavaScript
|
||||
* semantics the Rust pipeline must reproduce, recorded from the tools
|
||||
* themselves on generic inputs, not only on the equine data. Three oracles
|
||||
* under crates/core/tests/oracles/r5/:
|
||||
*
|
||||
* - prettier-json.json: `formatJson` (Prettier 3, parser json, the
|
||||
* repository options) over synthetic values probing the layout rules:
|
||||
* short arrays collapsed, number arrays filled, the 80-column boundary at
|
||||
* several depths and key widths, nested arrays, objects, empty
|
||||
* containers, Unicode widths.
|
||||
* - markdown-tables.json: `formatMarkdown` over raw tables as
|
||||
* `markdown.ts` writes them (alignment, padding, Unicode widths, escaped
|
||||
* pipes, empty cells).
|
||||
* - js-semantics.json: `slugify`, `deterministicUuid`, `inferRegionCode`,
|
||||
* `Number()`, the points split of the SVG reader, `Math.round`,
|
||||
* `Object.entries` key order of `JSON.parse`, `toLowerCase`, NFD.
|
||||
*
|
||||
* `MAKE_R5_ORACLES=1` writes the files; otherwise the tools still match the
|
||||
* freeze.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatJson, formatMarkdown } from '../src/format'
|
||||
import { table } from '../src/markdown'
|
||||
import { deterministicUuid, inferRegionCode, slugify } from '../src'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
|
||||
const MAKE = process.env.MAKE_R5_ORACLES === '1'
|
||||
|
||||
/** Numbers of `digits` characters each, deterministic. */
|
||||
function numbers(count: number, digits: number): number[] {
|
||||
return Array.from({ length: count }, (_, i) =>
|
||||
Number(String((i * 7919 + 13) % 10 ** digits).padStart(1, '0')),
|
||||
)
|
||||
}
|
||||
|
||||
function strings(count: number, width: number): string[] {
|
||||
return Array.from({ length: count }, (_, i) =>
|
||||
`${String.fromCharCode(97 + (i % 26))}`.repeat(width),
|
||||
)
|
||||
}
|
||||
|
||||
/** One value per layout rule, each nested so the boundary moves. */
|
||||
function jsonCases(): unknown[] {
|
||||
const cases: unknown[] = [
|
||||
{},
|
||||
[],
|
||||
{ a: {} },
|
||||
{ a: [] },
|
||||
{ a: [{}] },
|
||||
{ a: [[]] },
|
||||
{ a: [null, true, false] },
|
||||
{ a: [1e21, -0, 1e-7, -5, 0.5, 123456789012345680000] },
|
||||
{ a: [-1, -2, -3] },
|
||||
{ a: [1, 'b', null] },
|
||||
{ a: [[1, 2], [3]] },
|
||||
{ a: [[1], [2]] },
|
||||
{
|
||||
a: [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
},
|
||||
{ a: [[1, 2], { b: 1 }] },
|
||||
{ a: [{ b: 1 }, { c: 2 }] },
|
||||
{
|
||||
a: [
|
||||
{ b: 1, c: 2 },
|
||||
{ d: 3, e: 4 },
|
||||
],
|
||||
},
|
||||
{
|
||||
a: [
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
[[5, 6]],
|
||||
],
|
||||
},
|
||||
{
|
||||
a: [
|
||||
['x', 'y'],
|
||||
['z', 'w'],
|
||||
],
|
||||
},
|
||||
{ a: [['x'], ['y', 'z']] },
|
||||
{ 'clé é': ['é', 'à', '«»'], 漢字: ['漢字漢字', '😀'] },
|
||||
{ a: ['é', 'full', ''] },
|
||||
{ a: 'x'.repeat(200), b: ['y'.repeat(100)] },
|
||||
{ 'a"b': ['\\', '"', '\n', '\u0001'] },
|
||||
]
|
||||
for (const depth of [0, 1, 3, 6]) {
|
||||
for (const key of ['k', 'key_of_twenty_chars_', 'k'.repeat(40)]) {
|
||||
for (const count of [1, 2, 3, 8, 12, 13, 14, 15, 16, 30]) {
|
||||
for (const digits of [1, 3, 4, 6]) {
|
||||
let value: unknown = { [key]: numbers(count, digits) }
|
||||
for (let d = 0; d < depth; d++) value = { n: value }
|
||||
cases.push(value)
|
||||
}
|
||||
for (const width of [1, 5, 12]) {
|
||||
let value: unknown = { [key]: strings(count, width), z: 1 }
|
||||
for (let d = 0; d < depth; d++) value = { n: [value] }
|
||||
cases.push(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let total = 70; total <= 90; total++) {
|
||||
const pad = 'p'.repeat(total - 20)
|
||||
cases.push({ [pad]: [1, 2] }, { [pad]: [1, 2], last: true })
|
||||
cases.push({ [pad]: ['ab', 'cd'] }, [{ [pad]: [1, 2, 3] }])
|
||||
cases.push({ x: [[Number('1'.repeat(Math.max(1, total - 70))), 2]] })
|
||||
}
|
||||
return cases
|
||||
}
|
||||
|
||||
type Row = Array<string | number | null>
|
||||
|
||||
function tableCases(): Array<{ head: string[]; rows: Row[] }> {
|
||||
return [
|
||||
{ head: ['A', 'B'], rows: [['1', '2']] },
|
||||
{
|
||||
head: ['Mesure', 'Valeur'],
|
||||
rows: [
|
||||
['Nœuds', 792],
|
||||
['x', null],
|
||||
],
|
||||
},
|
||||
{ head: ['a'], rows: [['']] },
|
||||
{
|
||||
head: ['Code', 'Objet'],
|
||||
rows: [
|
||||
['`a|b`', 'x | y'],
|
||||
['ligne\nsuite', ''],
|
||||
],
|
||||
},
|
||||
{
|
||||
head: ['é', 'é'],
|
||||
rows: [
|
||||
['àéîõü', 'ç'],
|
||||
['–—', '«»'],
|
||||
],
|
||||
},
|
||||
{
|
||||
head: ['漢字', 'emoji'],
|
||||
rows: [
|
||||
['漢字漢字', '😀'],
|
||||
['full', '👍🏽'],
|
||||
],
|
||||
},
|
||||
{
|
||||
head: ['ctl', 'zw'],
|
||||
rows: [
|
||||
['a\u0001b', 'ab'],
|
||||
['️', 'x'],
|
||||
],
|
||||
},
|
||||
{
|
||||
head: ['Long', 'Court'],
|
||||
rows: [
|
||||
['x'.repeat(150), 'y'],
|
||||
['`code`', '**gras**'],
|
||||
],
|
||||
},
|
||||
{ head: ['Total'], rows: [['**Total**'], ['']] },
|
||||
{
|
||||
head: ['n', 'm', 'o'],
|
||||
rows: [
|
||||
[1, 22, 333],
|
||||
[4444, 5, 66],
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/** IEEE 754 bits in hex: `String(-0)` is `"0"`, the bits keep the sign. */
|
||||
function bitsOf(value: number): string {
|
||||
const view = new DataView(new ArrayBuffer(8))
|
||||
view.setFloat64(0, value)
|
||||
return view.getBigUint64(0).toString(16).padStart(16, '0')
|
||||
}
|
||||
|
||||
const SPACES = [' ', '\t', '\n', ' ', '', '
', ' ', '']
|
||||
|
||||
function semantics() {
|
||||
const slugInputs = [
|
||||
'Cheval',
|
||||
'Épaule',
|
||||
'İstanbul',
|
||||
'KK',
|
||||
'ΣΑΣ ΟΔΟΣ',
|
||||
'Straße',
|
||||
'fin',
|
||||
'full',
|
||||
'Džemal',
|
||||
'Ⅻ',
|
||||
'x̧́y',
|
||||
'①②',
|
||||
'a—b–c',
|
||||
'__a__',
|
||||
'œuvre Æther',
|
||||
'Ünïcödé',
|
||||
'😀 smile',
|
||||
'한국어',
|
||||
'ğ ş ı',
|
||||
'1/2 et 3/4',
|
||||
'a'.repeat(63) + 'é' + 'b',
|
||||
'-'.repeat(70) + 'z',
|
||||
]
|
||||
const uuidNames = [
|
||||
'faunosteo:sheet:canine:v1',
|
||||
'faunosteo:sheet:feline:v12',
|
||||
'faunosteo:asset:' + 'f'.repeat(64),
|
||||
'x'.repeat(1000),
|
||||
'é',
|
||||
'😀',
|
||||
'\u0000',
|
||||
]
|
||||
const regionLabels: Array<[string | null, string | null]> = [
|
||||
['Cervicales', null],
|
||||
[null, 'Thoracic'],
|
||||
['DORSALES', 'Lumbar'],
|
||||
['Région sacrée', 'Sacral'],
|
||||
['Coccygiennes', null],
|
||||
['Lombaires', 'x'],
|
||||
['Épaule', 'Shoulder'],
|
||||
[null, null],
|
||||
['', 'caudal'],
|
||||
['Thoracolombaire', ''],
|
||||
['CERVICALES', 'CERVICAL'],
|
||||
['Sacrum', 'Sacrum'],
|
||||
]
|
||||
const numberTexts = [
|
||||
'',
|
||||
' ',
|
||||
'12',
|
||||
' 12 ',
|
||||
'0x1A',
|
||||
'0X1a',
|
||||
'0b11',
|
||||
'0o17',
|
||||
'1e3',
|
||||
'1E-3',
|
||||
'.5',
|
||||
'5.',
|
||||
'+5',
|
||||
'-5',
|
||||
'Infinity',
|
||||
'-Infinity',
|
||||
'+Infinity',
|
||||
'infinity',
|
||||
'NaN',
|
||||
'abc',
|
||||
'1,5',
|
||||
' 12 ',
|
||||
'7',
|
||||
'12px',
|
||||
'1_000',
|
||||
'00012',
|
||||
'-0',
|
||||
'0x',
|
||||
'1e',
|
||||
'1e+',
|
||||
' \n\t3 ',
|
||||
'
3',
|
||||
'1.7976931348623157e309',
|
||||
'5e-325',
|
||||
'0.1e1',
|
||||
'-.5',
|
||||
'--5',
|
||||
'+-5',
|
||||
'0x-1',
|
||||
]
|
||||
const pointTexts = [
|
||||
' 1,2 3,4 ',
|
||||
'1,,2',
|
||||
',1,2',
|
||||
'1 2 3',
|
||||
'',
|
||||
'1e3,2',
|
||||
' 1 2',
|
||||
'1.5,2.25 ',
|
||||
'1,2,3,4,5,6',
|
||||
'a,b',
|
||||
' ',
|
||||
'1\n2\t3 4',
|
||||
]
|
||||
const roundValues = [
|
||||
0.5, 1.5, 2.5, -0.5, -1.5, -2.5, 0.49999999999999994, -0.49999999999999994,
|
||||
4503599627370495.5, -4503599627370495.5, 1e21, -0.4, 3.7, -3.7, 0, -0,
|
||||
2.4999999999999996, 1.0000000000000002,
|
||||
]
|
||||
const keyTexts = [
|
||||
'{"b":1,"2":2,"a":3,"1":4,"01":5,"4294967295":6,"4294967294":7,"-1":8,"1.5":9}',
|
||||
'{"z":1,"y":2,"10":3,"9":4,"0":5}',
|
||||
'{"a":1,"a":2,"b":3}',
|
||||
]
|
||||
return {
|
||||
slugify: slugInputs.map((label) => ({ label, slug: slugify(label) })),
|
||||
deterministicUuid: uuidNames.map((name) => ({
|
||||
name,
|
||||
uuid: deterministicUuid(name),
|
||||
})),
|
||||
inferRegionCode: regionLabels.map(([fr, en]) => ({
|
||||
fr,
|
||||
en,
|
||||
match: inferRegionCode(fr, en),
|
||||
})),
|
||||
number: numberTexts.map((text) => {
|
||||
const value = Number(text)
|
||||
return { text, string: String(value), negativeZero: Object.is(value, -0) }
|
||||
}),
|
||||
points: pointTexts.map((text) => ({
|
||||
text,
|
||||
numbers: text
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map((n) => String(Number(n))),
|
||||
})),
|
||||
mathRound: roundValues.map((value) => {
|
||||
const r = Math.round(value)
|
||||
return {
|
||||
bits: bitsOf(value),
|
||||
value: String(value),
|
||||
round: String(r),
|
||||
negativeZero: Object.is(r, -0),
|
||||
}
|
||||
}),
|
||||
objectEntriesOrder: keyTexts.map((text) => ({
|
||||
text,
|
||||
keys: Object.keys(JSON.parse(text) as object),
|
||||
})),
|
||||
trim: SPACES.map((space) => ({
|
||||
text: `${space}x${space}`,
|
||||
trimmed: `${space}x${space}`.trim(),
|
||||
isSpace: /\s/.test(space),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async function prettierJson() {
|
||||
const cases = jsonCases()
|
||||
const out = []
|
||||
for (const value of cases) {
|
||||
out.push({ input: JSON.stringify(value), output: await formatJson(value) })
|
||||
}
|
||||
return {
|
||||
tool: 'prettier formatJson (packages/anatomy/src/format.ts)',
|
||||
cases: out,
|
||||
}
|
||||
}
|
||||
|
||||
async function markdownTables() {
|
||||
const out = []
|
||||
for (const { head, rows } of tableCases()) {
|
||||
const raw = `# T\n\n${table(head, rows)}\n`
|
||||
out.push({ raw, output: await formatMarkdown(raw) })
|
||||
}
|
||||
return {
|
||||
tool: 'prettier formatMarkdown (packages/anatomy/src/format.ts)',
|
||||
cases: out,
|
||||
}
|
||||
}
|
||||
|
||||
function check(name: string, value: unknown): void {
|
||||
const text = `${JSON.stringify(value)}\n`
|
||||
if (MAKE) {
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
writeFileSync(resolve(OUT, name), text)
|
||||
}
|
||||
expect(text).toBe(readFileSync(resolve(OUT, name), 'utf8'))
|
||||
}
|
||||
|
||||
describe('R5.2 format and semantics oracles', () => {
|
||||
it('prettier-json.json', async () => {
|
||||
check('prettier-json.json', await prettierJson())
|
||||
})
|
||||
|
||||
it('markdown-tables.json', async () => {
|
||||
check('markdown-tables.json', await markdownTables())
|
||||
})
|
||||
|
||||
it('js-semantics.json', () => {
|
||||
check('js-semantics.json', semantics())
|
||||
})
|
||||
})
|
||||
@@ -1,286 +0,0 @@
|
||||
/**
|
||||
* R5.2 freeze (owner brief 2026-10-22 §9): the TypeScript legacy importer on synthetic
|
||||
* inputs, so the Rust port is held to the generic contract and not only to the equine
|
||||
* files. Each case is a full importer input (two SVG texts, the catalog text, the
|
||||
* vertebrae text); the oracle records the four rendered files and the result's parts, or
|
||||
* the refusal. `MAKE_R5_ORACLES=1` writes crates/core/tests/oracles/r5/legacy-synthetic.json.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { importEquineLegacy, renderArtifacts } from '../src'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
|
||||
const MAKE = process.env.MAKE_R5_ORACLES === '1'
|
||||
|
||||
interface Case {
|
||||
name: string
|
||||
main: string
|
||||
head: string
|
||||
catalog: string
|
||||
vertebrae: string
|
||||
}
|
||||
|
||||
const SVG_HEAD = '<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
|
||||
function svg(viewBox: string | null, body: string): string {
|
||||
const box = viewBox === null ? '' : ` viewBox="${viewBox}"`
|
||||
return `${SVG_HEAD}<svg xmlns="http://www.w3.org/2000/svg"${box}>\n${body}\n</svg>\n`
|
||||
}
|
||||
|
||||
function anno(
|
||||
tag: string,
|
||||
attrs: Record<string, string>,
|
||||
geometry: string,
|
||||
): string {
|
||||
const data = Object.entries(attrs)
|
||||
.map(([k, v]) => ` data-anno-${k}="${v}"`)
|
||||
.join('')
|
||||
return ` <${tag}${geometry}${data}/>`
|
||||
}
|
||||
|
||||
const VERTEBRAE = `// varies 18 - 22 caudal
|
||||
export const FORMULA = { C: 7, T: 18, L: 6, S: 5, Cd: 18, Cd: 20 }
|
||||
`
|
||||
|
||||
function node(id: string, extra: Record<string, unknown> = {}) {
|
||||
return { id, name_fr: `${id} fr`, name_en: `${id} en`, ...extra }
|
||||
}
|
||||
|
||||
function zone(id: string, fr: string, en: string, categories: unknown[]) {
|
||||
return { id, name_fr: fr, name_en: en, categories }
|
||||
}
|
||||
|
||||
const CATALOG = {
|
||||
schema_version: 2.5,
|
||||
scope_disclaimer: 'Périmètre « test »',
|
||||
zones: {
|
||||
hip: zone('hip', 'Hanche', 'Hip', [
|
||||
node('hip-dysfunctions', {
|
||||
children: [
|
||||
node('Épaule Gauche', { description_fr: 'seulement FR' }),
|
||||
node('ok', { requires_vet_referral: true, children: [] }),
|
||||
node('deep', {
|
||||
children: [node('leaf', { description_en: 'EN only' })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
node('anamnesis', { children: [node('age'), node('use')] }),
|
||||
node('spine-observations', { children: [node('ok')] }),
|
||||
]),
|
||||
'10': zone('10', 'Dix', 'Ten', [
|
||||
node('anamnesis', { children: [node('age')] }),
|
||||
]),
|
||||
'2': zone('2', 'Deux', 'Two', [
|
||||
node('weird'),
|
||||
node('anamnesis', { children: [node('age'), node('use')] }),
|
||||
]),
|
||||
spine: zone('spine', 'Colonne', 'Spine', [
|
||||
node('spine-dysfunctions', { children: [node('ok'), node('x y')] }),
|
||||
]),
|
||||
},
|
||||
}
|
||||
|
||||
const MAIN_BODY = [
|
||||
anno(
|
||||
'circle',
|
||||
{
|
||||
id: 'a1',
|
||||
'name-fr': 'Hanche',
|
||||
'name-en': 'Hip',
|
||||
category: 'articulations',
|
||||
'category-name': 'articulations',
|
||||
lateral: 'bilateral',
|
||||
},
|
||||
' cx="10.5" cy=" 20 " r=" 2 "',
|
||||
),
|
||||
anno(
|
||||
'circle',
|
||||
{ id: 'a1', 'name-fr': 'Hanche', 'name-en': 'Hip' },
|
||||
' cx="1" cy="1" r="1"',
|
||||
),
|
||||
anno(
|
||||
'polygon',
|
||||
{
|
||||
id: 'p1',
|
||||
'name-fr': 'Colonne',
|
||||
'name-en': 'Spine',
|
||||
category: 'charni-res-vert-brales',
|
||||
special: 'vertebral-precision',
|
||||
lateral: 'left',
|
||||
},
|
||||
' points=" 1,2 3,4 5,6 7 "',
|
||||
),
|
||||
anno(
|
||||
'polygon',
|
||||
{
|
||||
id: 'p2',
|
||||
'name-fr': 'Région sacrée',
|
||||
category: 'zone-colonne',
|
||||
'category-name': 'Colonne vertébrale',
|
||||
special: 'vertebral-precision',
|
||||
},
|
||||
' points="0x10,1e1 2,3 4,5"',
|
||||
),
|
||||
anno(
|
||||
'rect',
|
||||
{ id: 'r1', 'name-en': 'Rect only', category: 'os', special: 'other' },
|
||||
' x="1" y="2"',
|
||||
),
|
||||
anno(
|
||||
'circle',
|
||||
{ id: 't1', 'opens-detail': 'head', category: 'cadrans-du-cr-ne' },
|
||||
' cx="5" cy="5" r="2"',
|
||||
),
|
||||
anno(
|
||||
'circle',
|
||||
{
|
||||
id: 'x1',
|
||||
'name-fr': 'Dix',
|
||||
'name-en': 'Ten',
|
||||
category: 'os',
|
||||
lateral: 'unpaired',
|
||||
},
|
||||
' cx="840.1692504882812" cy="-0" r="3"',
|
||||
),
|
||||
].join('\n')
|
||||
|
||||
const HEAD_BODY = [
|
||||
anno(
|
||||
'circle',
|
||||
{ id: 'h1', 'name-fr': 'Deux', category: 'os' },
|
||||
' cx="3" cy="4" r="5"',
|
||||
),
|
||||
anno(
|
||||
'circle',
|
||||
{ id: 'h2', 'name-fr': 'Deux', 'name-en': 'Two', category: 'os' },
|
||||
' cx="3" cy="4" r="5"',
|
||||
),
|
||||
anno(
|
||||
'circle',
|
||||
{
|
||||
id: 'a1',
|
||||
'name-fr': 'Thoracique',
|
||||
'name-en': 'Thoracic',
|
||||
category: 'os',
|
||||
special: 'vertebral-precision',
|
||||
},
|
||||
' cx="1" cy="1" r="1"',
|
||||
),
|
||||
].join('\n')
|
||||
|
||||
function cases(): Case[] {
|
||||
const base: Case = {
|
||||
name: 'generic',
|
||||
main: svg('0 0 100 50', MAIN_BODY),
|
||||
head: svg(null, HEAD_BODY),
|
||||
catalog: JSON.stringify(CATALOG, null, 2),
|
||||
vertebrae: VERTEBRAE,
|
||||
}
|
||||
const minimal: Case = {
|
||||
name: 'minimal',
|
||||
main:
|
||||
'' +
|
||||
svg(
|
||||
'0 0 1 1',
|
||||
anno(
|
||||
'circle',
|
||||
{ id: 'm', 'name-fr': 'Hanche', 'name-en': 'Hip', category: 'os' },
|
||||
' cx="1" cy="1" r="1"',
|
||||
),
|
||||
),
|
||||
head: svg('0 0 1 1', ''),
|
||||
catalog: JSON.stringify({
|
||||
schema_version: '2.0',
|
||||
zones: {
|
||||
hip: zone('hip', 'Hanche', 'Hip', [
|
||||
node('hip-dysfunctions', { children: [node('a')] }),
|
||||
]),
|
||||
},
|
||||
}),
|
||||
vertebrae: 'const V = {C:7,T:18,L:6,S:5,Cd:21}',
|
||||
}
|
||||
const refusals: Case[] = [
|
||||
{
|
||||
...base,
|
||||
name: 'schema',
|
||||
main: base.main.replace('r="3"', 'r="Infinity"'),
|
||||
},
|
||||
{ ...base, name: 'no-zones', catalog: '{"schema_version":"2.0"}' },
|
||||
{ ...base, name: 'catalog-bom', catalog: '' + base.catalog },
|
||||
{
|
||||
...base,
|
||||
name: 'no-cd',
|
||||
vertebrae: 'const V = { C: 7, T: 18, L: 6, S: 5 }',
|
||||
},
|
||||
{ ...base, name: 'no-formula', vertebrae: 'nothing here' },
|
||||
{
|
||||
...base,
|
||||
name: 'inline-sources',
|
||||
catalog: JSON.stringify({
|
||||
zones: {
|
||||
hip: zone('hip', 'Hanche', 'Hip', [node('c', { sources: [{}] })]),
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
...base,
|
||||
name: 'key-not-id',
|
||||
catalog: JSON.stringify({
|
||||
zones: { hip: zone('hop', 'Hanche', 'Hip', []) },
|
||||
}),
|
||||
},
|
||||
{
|
||||
...base,
|
||||
name: 'truthy-referral',
|
||||
catalog: JSON.stringify({
|
||||
zones: {
|
||||
hip: zone('hip', 'Hanche', 'Hip', [
|
||||
node('c', {
|
||||
children: [node('d', { requires_vet_referral: 'yes' })],
|
||||
}),
|
||||
]),
|
||||
},
|
||||
}),
|
||||
},
|
||||
]
|
||||
return [base, minimal, ...refusals]
|
||||
}
|
||||
|
||||
async function run(c: Case) {
|
||||
const input = {
|
||||
mainSvg: { fileName: 'Main.svg', bytes: new TextEncoder().encode(c.main) },
|
||||
headSvg: { fileName: 'Head.svg', bytes: new TextEncoder().encode(c.head) },
|
||||
catalogJson: c.catalog,
|
||||
vertebraeSource: c.vertebrae,
|
||||
}
|
||||
try {
|
||||
const result = importEquineLegacy(input)
|
||||
const parts: Record<string, unknown> = { ...result }
|
||||
delete parts.document
|
||||
delete parts.legacyIdMap
|
||||
return { ...c, ok: true, files: await renderArtifacts(result), parts }
|
||||
} catch (error) {
|
||||
return {
|
||||
...c,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('R5.2 synthetic importer oracle', () => {
|
||||
it('legacy-synthetic.json', async () => {
|
||||
const rows = []
|
||||
for (const c of cases()) rows.push(await run(c))
|
||||
const text = `${JSON.stringify({ cases: rows })}\n`
|
||||
const file = resolve(OUT, 'legacy-synthetic.json')
|
||||
if (MAKE) {
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
writeFileSync(file, text)
|
||||
}
|
||||
expect(text).toBe(readFileSync(file, 'utf8'))
|
||||
})
|
||||
})
|
||||
@@ -1,306 +0,0 @@
|
||||
/**
|
||||
* R5.4 freeze (final gates, 2026-10-23): what Prettier's Markdown printer does to authored text
|
||||
* in the two draft reports. The port reproduces only the table alignment and refuses the text
|
||||
* Prettier would rewrite; this sweep, written by the TypeScript, holds it to that: every probe
|
||||
* (a special character in six positions, whitespace patterns, Markdown constructs) is placed
|
||||
* in a change title, rationale and question, a cited reference and a changed label, and the
|
||||
* sha256 of the raw and formatted CHANGELOG and REVIEW-REPORT are frozen (400 of the probes
|
||||
* come from a seeded generator, so unknown classes surface on their own; eight pairs open a
|
||||
* construct in one field and close it in the question). `MAKE_R5_ORACLES=1` writes
|
||||
* crates/core/tests/oracles/r5/markdown-sweep.json.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyChangeset,
|
||||
buildReportMigrationMap,
|
||||
ChangesetSchema,
|
||||
documentStats,
|
||||
renderChangelog,
|
||||
renderReviewReport,
|
||||
} from '../src'
|
||||
import { changeSummary } from '../src/curation/schema'
|
||||
import { formatMarkdown } from '../src/format'
|
||||
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function sha256(text: string): string {
|
||||
return createHash('sha256').update(text, 'utf8').digest('hex')
|
||||
}
|
||||
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
|
||||
const MAKE = process.env.MAKE_R5_ORACLES === '1'
|
||||
|
||||
const LEGACY_ID_MAP = {
|
||||
views: { head: 'head' },
|
||||
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
|
||||
categories: {},
|
||||
finding_nodes: {},
|
||||
assets: {},
|
||||
}
|
||||
|
||||
const CHARACTERS = [...'*_~\\`<>&[]!#$|+=^{}"\'%@:;?/()-.,’‘“”×≤≥±→–—…«»°≠']
|
||||
|
||||
function positions(c: string): string[] {
|
||||
return [c, `${c}x`, `x${c}`, `a ${c} b`, `a${c}b`, `${c}${c}`]
|
||||
}
|
||||
|
||||
const PATTERNS = [
|
||||
'a b',
|
||||
'a\tb',
|
||||
' a',
|
||||
'a ',
|
||||
'a\nb',
|
||||
'a\rb',
|
||||
'a\n\nb',
|
||||
'*important*',
|
||||
'**gras**',
|
||||
'a **b c** d',
|
||||
'a**b**c',
|
||||
'__init__ et _x',
|
||||
'to_confirm',
|
||||
'`code`',
|
||||
'``double``',
|
||||
'a\\|b',
|
||||
'a|b',
|
||||
'<b>gras</b>',
|
||||
'[lien](https://example.org/x)',
|
||||
'[a](<b>)',
|
||||
'[a]( b )',
|
||||
'[a](b "t")',
|
||||
'[a](b (t))',
|
||||
'[a](b&c)',
|
||||
'[a](b\\)c)',
|
||||
'[a](https://x.org/a(b)c)',
|
||||
']( )',
|
||||
'',
|
||||
'[a][b]',
|
||||
'<http://a&b>',
|
||||
'<https://example.org/x>',
|
||||
'<a@b.co>',
|
||||
'[[ a ]]',
|
||||
'[[a]]',
|
||||
'*',
|
||||
'*',
|
||||
'*',
|
||||
'_',
|
||||
'_',
|
||||
'é',
|
||||
'doi 10.1/x<0697:toih>2.0',
|
||||
'中_中',
|
||||
'ア_ア',
|
||||
'한_한',
|
||||
'é_é',
|
||||
'[a]( https://x.org )',
|
||||
'**a****b**',
|
||||
'\\**a**',
|
||||
'x_**a**',
|
||||
'**a**_x',
|
||||
'** **',
|
||||
'**Total**',
|
||||
'(**a**)',
|
||||
'a **b** c',
|
||||
'Voir_https://example.org/x',
|
||||
'Voir_www.example.org',
|
||||
'https://x.org/**a **',
|
||||
'https://x.org/a_b',
|
||||
'Lien https://x.org/a_b fin',
|
||||
'a\u00a0b',
|
||||
'a\u2003b',
|
||||
'a\u3000b',
|
||||
'中文',
|
||||
'مرحبا',
|
||||
'e\u0301',
|
||||
'Mesure a_b `c_`',
|
||||
'Champ snake_case, voir x_y fin',
|
||||
'to_do',
|
||||
'voir [a `](b)` c',
|
||||
'voir https://x.org/`<a`',
|
||||
'a * b',
|
||||
'*',
|
||||
'_',
|
||||
'a_b',
|
||||
'< x &',
|
||||
'A x &',
|
||||
'![a\\"b]',
|
||||
'![a|b]',
|
||||
'![&]',
|
||||
'![x]',
|
||||
'[[ a [[b]]',
|
||||
'[[a]] [[ b [[c]]',
|
||||
'a & b',
|
||||
'A&B',
|
||||
'x &',
|
||||
'https://x.org/?a=1&pid=2',
|
||||
'https://x.org/?a=1<=2',
|
||||
'https://x.org/?a¬=2',
|
||||
'https://x.org/?a=1&=2',
|
||||
'https://x.org/?a=1©x=2',
|
||||
'&',
|
||||
'# titre',
|
||||
'1. item',
|
||||
'- item',
|
||||
'> citation',
|
||||
'Carmalt 2013 (≠ « palpation »), 3 %, 40 °C',
|
||||
'a = b; c ? d : e',
|
||||
'{"fr":"x"}',
|
||||
'é ü ß ø Ω 中',
|
||||
]
|
||||
|
||||
/** A seeded generator (a 32-bit LCG): the random probes are the same on every run. */
|
||||
function randomProbes(count: number): string[] {
|
||||
const alphabet = [
|
||||
...'ab_*\\`[]()<>&#!~ :/.|"é中=;',
|
||||
'&#',
|
||||
'&',
|
||||
'<',
|
||||
'![',
|
||||
'[[',
|
||||
']]',
|
||||
'https://',
|
||||
'www.',
|
||||
'**',
|
||||
'\n',
|
||||
'\u00a0',
|
||||
]
|
||||
let state = 20261023
|
||||
const next = () => {
|
||||
state = (Math.imul(state, 1664525) + 1013904223) >>> 0
|
||||
return state
|
||||
}
|
||||
const out: string[] = []
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const length = 2 + (next() % 10)
|
||||
let text = ''
|
||||
for (let j = 0; j < length; j += 1)
|
||||
text += alphabet[next() % alphabet.length]
|
||||
out.push(text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function probes(): string[] {
|
||||
return [...CHARACTERS.flatMap(positions), ...PATTERNS, ...randomProbes(400)]
|
||||
}
|
||||
|
||||
/** Openers in the title, the rationale and every other field, closers in the question. */
|
||||
const SPLIT = [
|
||||
['[[', ']]'],
|
||||
['[[ a', 'b ]]'],
|
||||
['[[a', 'b]]'],
|
||||
['{%', '%}'],
|
||||
['[x', '](y)'],
|
||||
['*a', 'b*'],
|
||||
['_a', 'b_'],
|
||||
['<b', '>'],
|
||||
]
|
||||
|
||||
function changesFile(probe: string, referenceId: string, closer = probe) {
|
||||
return {
|
||||
changes: [
|
||||
{
|
||||
id: 'CHG-001',
|
||||
level: 'C',
|
||||
kind: 'correction',
|
||||
title: { fr: `Titre ${probe}`, en: 'Title' },
|
||||
rationale: `Raison ${probe} fin.`,
|
||||
reference_ids: [],
|
||||
question: `Question ${closer} ?`,
|
||||
ops: [
|
||||
{
|
||||
op: 'add',
|
||||
target: 'document',
|
||||
field: 'references',
|
||||
value: {
|
||||
id: referenceId,
|
||||
type: 'web',
|
||||
citation: `Citation ${probe}`,
|
||||
url: null,
|
||||
doi: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
op: 'cite',
|
||||
target: 'finding:hip/hip-dysfunctions/mobility',
|
||||
reference_ids: [referenceId],
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'finding:hip/hip-dysfunctions/mobility',
|
||||
field: 'name.en',
|
||||
value: `Label ${probe}`,
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'finding:hip/hip-dysfunctions/mobility/flexion',
|
||||
field: 'name.fr',
|
||||
value: probe,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
async function run(probe: string, referenceId = 'probe_ref', closer = probe) {
|
||||
const file = changesFile(probe, referenceId, closer)
|
||||
const changeset = ChangesetSchema.parse(file)
|
||||
const baseline = miniSheet()
|
||||
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
|
||||
const before = documentStats(baseline)
|
||||
const after = documentStats(result.document)
|
||||
const migration = buildReportMigrationMap({
|
||||
baseline: miniSheet() as never,
|
||||
final: result.document as never,
|
||||
legacyIdMap: LEGACY_ID_MAP,
|
||||
records: result.records,
|
||||
sheet: { sheetId: 's', versionId: null, documentSha256: '0'.repeat(64) },
|
||||
mainViewId: 'main',
|
||||
})
|
||||
const changelogRaw = renderChangelog(result, before, after, migration.stats)
|
||||
const reviewRaw = renderReviewReport({
|
||||
changes: changeset.changes.map(changeSummary),
|
||||
records: result.records,
|
||||
document: result.document,
|
||||
statsBefore: before,
|
||||
legacyAnomalies: [],
|
||||
})
|
||||
return {
|
||||
probe: closer === probe ? probe : `${probe}|${closer}`,
|
||||
reference_id: referenceId,
|
||||
changes_file: file,
|
||||
changelog_raw_sha256: sha256(changelogRaw),
|
||||
changelog_sha256: sha256(await formatMarkdown(changelogRaw)),
|
||||
review_raw_sha256: sha256(reviewRaw),
|
||||
review_sha256: sha256(await formatMarkdown(reviewRaw)),
|
||||
}
|
||||
}
|
||||
|
||||
describe('R5.4 Markdown sweep oracle', () => {
|
||||
it('markdown-sweep.json', async () => {
|
||||
const rows = []
|
||||
for (const probe of probes()) rows.push(await run(probe))
|
||||
// A cited id ending with `_` puts a closing underscore in a generated code span.
|
||||
for (const probe of ['to_do', 'a_b c', 'x'])
|
||||
rows.push(await run(probe, 'probe_ref_'))
|
||||
// A construct opened in one field and closed in another of the same line.
|
||||
for (const [opener, closer] of SPLIT)
|
||||
rows.push(await run(opener, 'probe_ref', closer))
|
||||
const oracle = {
|
||||
baseline: miniSheet(),
|
||||
references: MINI_REFERENCES,
|
||||
legacy_id_map: LEGACY_ID_MAP,
|
||||
cases: rows,
|
||||
}
|
||||
const text = `${JSON.stringify(oracle)}\n`
|
||||
const file = resolve(OUT, 'markdown-sweep.json')
|
||||
if (MAKE) {
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
writeFileSync(file, text)
|
||||
}
|
||||
expect(text).toBe(readFileSync(file, 'utf8'))
|
||||
}, 120_000)
|
||||
})
|
||||
@@ -1,373 +0,0 @@
|
||||
/**
|
||||
* R5.1 freeze (plan 2026-10-22 §B.2): what the TypeScript pipeline computes
|
||||
* and emits today, recorded for the Rust pipeline to reproduce. Three
|
||||
* oracles under crates/core/tests/oracles/r5/:
|
||||
*
|
||||
* - pipeline.json: the intermediate values the generated files do not show
|
||||
* (import stats, anomalies, rows, region inferences, change records,
|
||||
* stats before and after, integrity warnings, migration stats) and the
|
||||
* ledger of every generated file (bytes, sha256, the sha256 of the
|
||||
* markdown before Prettier).
|
||||
* - ids.json: the deterministic uuid and slug functions over every name the
|
||||
* pipeline derives an id from, plus edge cases.
|
||||
* - fingerprints.json: the sheet fingerprint of every JSON artifact under
|
||||
* each D-R5 candidate rule, the ES6 printing of every non-integer number
|
||||
* of the two documents, and the RFC 8785 vectors.
|
||||
*
|
||||
* `MAKE_R5_ORACLES=1` writes the files; otherwise the pipeline still matches
|
||||
* its own freeze. The committed generated folders stay the byte oracle
|
||||
* (seed.golden.test.ts); nothing here rewrites them.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AnatomicalSheetDocumentSchema } from '@faunosteo/domain'
|
||||
import {
|
||||
buildReportMigrationMap,
|
||||
deterministicUuid,
|
||||
EQUINE_DRAFT_DIR,
|
||||
EQUINE_LEGACY_IMPORT_DIR,
|
||||
MAIN_VIEW_ID,
|
||||
renderArtifacts,
|
||||
renderChangelog,
|
||||
renderDraftArtifacts,
|
||||
renderImportReport,
|
||||
renderReviewReport,
|
||||
sha256Hex,
|
||||
slugify,
|
||||
type DraftResult,
|
||||
type ImportResult,
|
||||
} from '../src'
|
||||
import { runDraft } from './helpers'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = resolve(HERE, '../../..')
|
||||
const OUT = resolve(REPO, 'crates/core/tests/oracles/r5')
|
||||
const MAKE = process.env.MAKE_R5_ORACLES === '1'
|
||||
|
||||
type Json = Record<string, unknown>
|
||||
|
||||
/** The uuid and slug inputs the pipeline derives ids from, plus edges. */
|
||||
const UUID_NAMES = [
|
||||
'faunosteo:sheet:equine:v1',
|
||||
'faunosteo:sheet:equine:v2',
|
||||
'faunosteo:asset:0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541',
|
||||
'',
|
||||
'faunosteo:sheet:équin:v1',
|
||||
'faunosteo:asset:\u{1f40e}',
|
||||
]
|
||||
const SLUG_EDGES = [
|
||||
'',
|
||||
' ',
|
||||
'Cheval',
|
||||
'Épaule gauche',
|
||||
'Vertèbres thoraciques T1–T18',
|
||||
'Œil / orbite',
|
||||
'Straße',
|
||||
'Ørsted',
|
||||
"Rein d'un cheval",
|
||||
'ÀÉÎÕÜ ç ñ',
|
||||
'--déjà--',
|
||||
'a'.repeat(70),
|
||||
'é'.repeat(70),
|
||||
'DŽ Dž dž',
|
||||
'İstanbul',
|
||||
'12 côtes',
|
||||
'Ça (combining cedilla)',
|
||||
]
|
||||
|
||||
/** RFC 8785: UTF-16 member order, no whitespace, JSON.stringify scalars. */
|
||||
function canonicalize(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value)
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`
|
||||
const object = value as Json
|
||||
const keys = Object.keys(object).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
const members = keys.map(
|
||||
(k) => `${JSON.stringify(k)}:${canonicalize(object[k])}`,
|
||||
)
|
||||
return `{${members.join(',')}}`
|
||||
}
|
||||
|
||||
/** RFC 8785 §3.2.3 examples: numbers and escapes, then member ordering. */
|
||||
const RFC_VECTORS: Array<[string, string]> = [
|
||||
[
|
||||
'{"numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], ' +
|
||||
'"string": "\\u20ac$\\u000F\\u000aA\'\\u0042\\u0022\\u005c\\\\\\"\\/", "literals": [null, true, false]}',
|
||||
'{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],' +
|
||||
'"string":"€$\\u000f\\nA\'B\\"\\\\\\\\\\"/"}',
|
||||
],
|
||||
[
|
||||
'{"\\u20ac": "Euro Sign", "\\r": "Carriage Return", "\\ufb33": "Hebrew Letter Dalet With Dagesh", ' +
|
||||
'"1": "One", "\\ud83d\\ude00": "Emoji: Grinning Face", "\\u0080": "Control", ' +
|
||||
'"\\u00f6": "Latin Small Letter O With Diaeresis"}',
|
||||
'{"\\r":"Carriage Return","1":"One","\u0080":"Control","ö":"Latin Small Letter O With Diaeresis",' +
|
||||
'"€":"Euro Sign","😀":"Emoji: Grinning Face","דּ":"Hebrew Letter Dalet With Dagesh"}',
|
||||
],
|
||||
]
|
||||
|
||||
/** Every number of a JSON value that is not an integer, with its JS text. */
|
||||
function nonIntegers(value: unknown, path: string, out: Json[]): void {
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isInteger(value)) out.push({ path, text: String(value) })
|
||||
} else if (Array.isArray(value)) {
|
||||
value.forEach((item, i) => nonIntegers(item, `${path}[${i}]`, out))
|
||||
} else if (value && typeof value === 'object') {
|
||||
for (const [k, v] of Object.entries(value as Json))
|
||||
nonIntegers(v, `${path}.${k}`, out)
|
||||
}
|
||||
}
|
||||
|
||||
/** Every `name.fr` / `name.en` of a document, unique, in document order. */
|
||||
function names(value: unknown, out: Set<string>): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) names(item, out)
|
||||
} else if (value && typeof value === 'object') {
|
||||
const object = value as Json
|
||||
const name = object.name as Json | undefined
|
||||
if (name && typeof name.fr === 'string') out.add(name.fr)
|
||||
if (name && typeof name.en === 'string') out.add(name.en)
|
||||
for (const v of Object.values(object)) names(v, out)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The input form is what the file holds (defaults omitted); the validated
|
||||
* form is what every reader holds after the schema (defaults filled, Zod
|
||||
* output order). A document.json row carries both.
|
||||
*/
|
||||
function fingerprintRow(file: string, text: string): Json {
|
||||
const value = JSON.parse(text) as unknown
|
||||
const pretty = JSON.stringify(value, null, 2)
|
||||
const row: Json = {
|
||||
file,
|
||||
bytes: Buffer.byteLength(text),
|
||||
today_file_bytes: sha256Hex(text),
|
||||
a_js_pretty_newline: sha256Hex(`${pretty}\n`),
|
||||
a_js_pretty: sha256Hex(pretty),
|
||||
a_js_compact: sha256Hex(JSON.stringify(value)),
|
||||
b_rfc8785: sha256Hex(canonicalize(value)),
|
||||
prettier_equals_js_pretty: text === `${pretty}\n`,
|
||||
}
|
||||
if (file.endsWith('/document.json')) {
|
||||
const validated = AnatomicalSheetDocumentSchema.parse(value)
|
||||
row.a_js_pretty_validated = sha256Hex(JSON.stringify(validated, null, 2))
|
||||
row.b_rfc8785_validated = sha256Hex(canonicalize(validated))
|
||||
row.validated_equals_input = canonicalize(validated) === canonicalize(value)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
interface Run {
|
||||
result: ImportResult
|
||||
draft: DraftResult
|
||||
legacyFiles: Record<string, string>
|
||||
draftFiles: Record<string, string>
|
||||
}
|
||||
|
||||
async function run(): Promise<Run> {
|
||||
const { result, draft } = await runDraft()
|
||||
return {
|
||||
result,
|
||||
draft,
|
||||
legacyFiles: await renderArtifacts(result),
|
||||
draftFiles: await renderDraftArtifacts(draft, result.anomalies),
|
||||
}
|
||||
}
|
||||
|
||||
function ledger(
|
||||
folder: string,
|
||||
files: Record<string, string>,
|
||||
raw: Record<string, string>,
|
||||
): Json[] {
|
||||
return Object.entries(files).map(([file, text]) => ({
|
||||
folder,
|
||||
file,
|
||||
bytes: Buffer.byteLength(text),
|
||||
sha256: sha256Hex(text),
|
||||
...(file in raw
|
||||
? {
|
||||
before_prettier_sha256: sha256Hex(raw[file]!),
|
||||
prettier_changed: raw[file] !== text,
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
}
|
||||
|
||||
function pipelineOracle(r: Run): Json {
|
||||
const { result, draft } = r
|
||||
const documentJson = r.draftFiles['document.json']!
|
||||
const migration = buildReportMigrationMap({
|
||||
baseline: draft.baseline as Json,
|
||||
final: draft.document as Json,
|
||||
legacyIdMap: draft.legacyIdMap,
|
||||
records: draft.records,
|
||||
sheet: {
|
||||
sheetId: draft.sheetId,
|
||||
versionId: null,
|
||||
documentSha256: sha256Hex(documentJson),
|
||||
},
|
||||
mainViewId: MAIN_VIEW_ID,
|
||||
})
|
||||
const rawLegacy = { 'IMPORT-REPORT.md': renderImportReport(result) }
|
||||
const rawDraft = {
|
||||
'CHANGELOG.md': renderChangelog(
|
||||
draft,
|
||||
draft.statsBefore,
|
||||
draft.statsAfter,
|
||||
migration.stats,
|
||||
),
|
||||
'REVIEW-REPORT.md': renderReviewReport({
|
||||
...draft,
|
||||
legacyAnomalies: result.anomalies,
|
||||
}),
|
||||
}
|
||||
return {
|
||||
frozen_from: 'packages/anatomy (TypeScript pipeline), R5.1',
|
||||
legacy: {
|
||||
sheetId: result.sheetId,
|
||||
viewBoxes: result.viewBoxes,
|
||||
stats: result.stats,
|
||||
sourceDigests: result.sourceDigests,
|
||||
assets: result.assets,
|
||||
anomalies: result.anomalies,
|
||||
issues: result.issues,
|
||||
regionInferences: result.regionInferences,
|
||||
zoneStats: result.zoneStats,
|
||||
annotationRows: result.annotationRows,
|
||||
},
|
||||
draft: {
|
||||
sheetId: draft.sheetId,
|
||||
changes: draft.changes,
|
||||
assets: draft.assets,
|
||||
statsBefore: draft.statsBefore,
|
||||
statsAfter: draft.statsAfter,
|
||||
issues: draft.issues,
|
||||
migrationStats: migration.stats,
|
||||
records: draft.records,
|
||||
},
|
||||
artifacts: [
|
||||
...ledger(EQUINE_LEGACY_IMPORT_DIR, r.legacyFiles, rawLegacy),
|
||||
...ledger(EQUINE_DRAFT_DIR, r.draftFiles, rawDraft),
|
||||
{
|
||||
folder: EQUINE_DRAFT_DIR,
|
||||
file: `assets/${draft.assets[0]!.file}`,
|
||||
bytes: Buffer.byteLength(draft.cleanedSvg),
|
||||
sha256: sha256Hex(draft.cleanedSvg),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function idsOracle(r: Run): Json {
|
||||
const labels = new Set<string>()
|
||||
names(r.result.document, labels)
|
||||
names(r.draft.document, labels)
|
||||
const slugInputs = [...SLUG_EDGES, ...labels]
|
||||
return {
|
||||
uuid: UUID_NAMES.map((name) => ({ name, uuid: deterministicUuid(name) })),
|
||||
slug: slugInputs.map((label) => ({ label, slug: slugify(label) })),
|
||||
}
|
||||
}
|
||||
|
||||
function fingerprintsOracle(r: Run): Json {
|
||||
const jsonFiles = [
|
||||
...Object.entries(r.legacyFiles).map(
|
||||
([f, t]) => [`${EQUINE_LEGACY_IMPORT_DIR}/${f}`, t] as const,
|
||||
),
|
||||
...Object.entries(r.draftFiles).map(
|
||||
([f, t]) => [`${EQUINE_DRAFT_DIR}/${f}`, t] as const,
|
||||
),
|
||||
].filter(([file]) => file.endsWith('.json'))
|
||||
const numbers: Json[] = []
|
||||
nonIntegers(
|
||||
JSON.parse(r.legacyFiles['document.json']!),
|
||||
'legacy-import/document.json',
|
||||
numbers,
|
||||
)
|
||||
nonIntegers(
|
||||
JSON.parse(r.draftFiles['document.json']!),
|
||||
'draft/document.json',
|
||||
numbers,
|
||||
)
|
||||
return {
|
||||
rules: {
|
||||
today_file_bytes:
|
||||
'sha256 of the Prettier-formatted JSON text the pipeline writes (pipeline.ts sheetRef)',
|
||||
a_js_pretty_newline: 'sha256 of JSON.stringify(v, null, 2) + "\\n"',
|
||||
a_js_pretty: 'sha256 of JSON.stringify(v, null, 2)',
|
||||
a_js_compact: 'sha256 of JSON.stringify(v)',
|
||||
b_rfc8785: 'sha256 of the RFC 8785 canonical text',
|
||||
a_js_pretty_validated:
|
||||
'document.json only: JSON.stringify(schema.parse(v), null, 2), the validated form (defaults filled)',
|
||||
b_rfc8785_validated: 'document.json only: RFC 8785 of the validated form',
|
||||
},
|
||||
artifacts: jsonFiles.map(([file, text]) => fingerprintRow(file, text)),
|
||||
numbers,
|
||||
rfc8785_vectors: RFC_VECTORS.map(([input, canonical]) => ({
|
||||
input,
|
||||
canonical,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function write(name: string, value: Json): string {
|
||||
const text = `${JSON.stringify(value, null, 2)}\n`
|
||||
if (MAKE) {
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
writeFileSync(resolve(OUT, name), text)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
function frozen(name: string): string {
|
||||
return readFileSync(resolve(OUT, name), 'utf8')
|
||||
}
|
||||
|
||||
describe('R5.1 oracles (crates/core/tests/oracles/r5)', () => {
|
||||
it('the RFC 8785 canonicaliser passes the RFC vectors', () => {
|
||||
for (const [input, expected] of RFC_VECTORS) {
|
||||
expect(canonicalize(JSON.parse(input))).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('pipeline.json: intermediate values and the artifact ledger', async () => {
|
||||
const text = write('pipeline.json', pipelineOracle(await run()))
|
||||
expect(text).toBe(frozen('pipeline.json'))
|
||||
})
|
||||
|
||||
it('ids.json: deterministic uuids and slugs', async () => {
|
||||
const text = write('ids.json', idsOracle(await run()))
|
||||
expect(text).toBe(frozen('ids.json'))
|
||||
})
|
||||
|
||||
it('fingerprints.json: the D-R5 matrix and the number printing', async () => {
|
||||
const text = write('fingerprints.json', fingerprintsOracle(await run()))
|
||||
expect(text).toBe(frozen('fingerprints.json'))
|
||||
})
|
||||
|
||||
it('the ledger digests are the committed files (the golden folders)', async () => {
|
||||
const oracle = JSON.parse(frozen('pipeline.json')) as {
|
||||
artifacts: Array<{ folder: string; file: string; sha256: string }>
|
||||
}
|
||||
// Since R5.6 the two fingerprinted draft files are Rust's (`v1`); the ledger recorded the
|
||||
// TypeScript's, frozen under `crates/core/tests/fixtures/r5-6/pre-switch` (the Rust suite
|
||||
// `curation_draft` proves the committed ones are those under the declared rule).
|
||||
const preSwitch = new Set(['sheet-ref.json', 'report-migration-map.json'])
|
||||
for (const row of oracle.artifacts) {
|
||||
const folder =
|
||||
row.folder.endsWith('/draft') && preSwitch.has(row.file)
|
||||
? 'crates/core/tests/fixtures/r5-6/pre-switch'
|
||||
: row.folder
|
||||
const committed = readFileSync(resolve(REPO, folder, row.file))
|
||||
expect(sha256Hex(committed), `${row.folder}/${row.file}`).toBe(row.sha256)
|
||||
}
|
||||
})
|
||||
|
||||
it('two runs emit the same bytes for every artifact', async () => {
|
||||
const [first, second] = [await run(), await run()]
|
||||
expect(first.legacyFiles).toEqual(second.legacyFiles)
|
||||
expect(first.draftFiles).toEqual(second.draftFiles)
|
||||
expect(first.draft.cleanedSvg).toBe(second.draft.cleanedSvg)
|
||||
})
|
||||
})
|
||||
@@ -1,308 +0,0 @@
|
||||
/**
|
||||
* R5.4 freeze (owner brief 2026-10-23 §4, "tester les cas nécessaires"): the TypeScript review
|
||||
* files on synthetic changesets over the mini sheet and a small drawing, so the Rust port of
|
||||
* the CHANGELOG, the review report, the review overlays and the application's drawings is held
|
||||
* to the generic contract and not only to the equine data. Each case records the raw and the
|
||||
* formatted Markdown and the four drawings. `MAKE_R5_ORACLES=1` writes
|
||||
* crates/core/tests/oracles/r5/review-synthetic.json.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyChangeset,
|
||||
buildReportMigrationMap,
|
||||
ChangesetSchema,
|
||||
documentStats,
|
||||
renderAppReviewDrawing,
|
||||
renderChangelog,
|
||||
renderReviewOverlay,
|
||||
renderReviewReport,
|
||||
} from '../src'
|
||||
import { changeSummary } from '../src/curation/schema'
|
||||
import { formatMarkdown } from '../src/format'
|
||||
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
|
||||
const MAKE = process.env.MAKE_R5_ORACLES === '1'
|
||||
|
||||
type Json = Record<string, unknown>
|
||||
|
||||
const DRAWING = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 80" width="100" height="80">',
|
||||
' <path d="M0 0 L10 10" fill="#ccbbaa"/>',
|
||||
' <g id="body"><circle cx="5" cy="5" r="2" fill="#998877"/></g>',
|
||||
'</svg>',
|
||||
'',
|
||||
].join('\n')
|
||||
|
||||
const LEGACY_ID_MAP = {
|
||||
views: { head: 'head' },
|
||||
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
|
||||
categories: {},
|
||||
finding_nodes: {},
|
||||
assets: {},
|
||||
}
|
||||
|
||||
const SHEET = {
|
||||
sheetId: '11111111-1111-5111-8111-111111111111',
|
||||
versionId: null,
|
||||
documentSha256: '0'.repeat(64),
|
||||
}
|
||||
|
||||
const ANOMALIES = [
|
||||
{ code: 'a.one', level: 'a_valider', subject: 's', message: 'm' },
|
||||
{ code: 'a.two', level: 'informatif', subject: 's', message: 'm' },
|
||||
{ code: 'a.three', level: 'a_valider', subject: 's', message: 'm' },
|
||||
]
|
||||
|
||||
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
|
||||
|
||||
function change(id: string, ops: unknown[], extra: Json = {}): Json {
|
||||
return {
|
||||
id,
|
||||
level: 'A',
|
||||
kind: 'technical',
|
||||
title: { fr: 'Essai', en: 'Test' },
|
||||
rationale: 'Essai',
|
||||
reference_ids: [],
|
||||
...extra,
|
||||
ops,
|
||||
}
|
||||
}
|
||||
|
||||
interface Case {
|
||||
name: string
|
||||
changes_file: Json
|
||||
}
|
||||
|
||||
const LONG = 'mot '.repeat(40)
|
||||
|
||||
const CASES: Case[] = [
|
||||
{
|
||||
name: 'every-section',
|
||||
changes_file: {
|
||||
changes: [
|
||||
change(
|
||||
'CHG-001',
|
||||
[
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'name',
|
||||
value: { fr: 'Mobilité | pipe', en: 'Mobility\nline' },
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'finding:neck/neck-dysfunctions/stiffness',
|
||||
field: 'requires_vet_referral',
|
||||
value: true,
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'annotation:hip',
|
||||
field: 'geometry',
|
||||
value: { type: 'circle', cx: 30, cy: 20.5, r: 4 },
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'annotation:neck',
|
||||
field: 'geometry',
|
||||
value: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[10, 10],
|
||||
[20, 10],
|
||||
[15, 25],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
{ kind: 'correction', reference_ids: ['atlas'] },
|
||||
),
|
||||
change(
|
||||
'CHG-002',
|
||||
[
|
||||
{
|
||||
op: 'set',
|
||||
target: `${MOBILITY}/flexion`,
|
||||
field: 'description',
|
||||
value: { fr: LONG, en: `${LONG}é` },
|
||||
},
|
||||
{
|
||||
op: 'cite',
|
||||
target: 'zone:hip',
|
||||
reference_ids: ['paper'],
|
||||
scope: 'subtree',
|
||||
},
|
||||
],
|
||||
{ level: 'B', kind: 'translation', priority: 'high' },
|
||||
),
|
||||
change(
|
||||
'CHG-010',
|
||||
[
|
||||
{
|
||||
op: 'add',
|
||||
target: MOBILITY,
|
||||
value: {
|
||||
id: 'rotation',
|
||||
name: { fr: 'Rotation « axiale »', en: 'Axial rotation' },
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
level: 'C',
|
||||
kind: 'enrichment',
|
||||
question: 'Faut-il la garder ?',
|
||||
priority: 'low',
|
||||
reference_ids: ['paper'],
|
||||
},
|
||||
),
|
||||
change(
|
||||
'CHG-0011',
|
||||
[{ op: 'remove', target: 'finding:hip/anamnesis/trauma' }],
|
||||
{
|
||||
level: 'C',
|
||||
kind: 'restructure',
|
||||
question: 'Retrait confirmé ?',
|
||||
priority: 'high',
|
||||
},
|
||||
),
|
||||
change('CHG-003', [{ op: 'remove', target: `${MOBILITY}/extension` }], {
|
||||
kind: 'removal',
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'detail-view-and-path',
|
||||
changes_file: {
|
||||
changes: [
|
||||
change('CHG-001', [
|
||||
{
|
||||
op: 'add',
|
||||
target: 'document',
|
||||
field: 'annotations',
|
||||
value: {
|
||||
id: 'skull',
|
||||
kind: 'point',
|
||||
view_id: 'head',
|
||||
category_id: 'bones',
|
||||
laterality: 'unpaired',
|
||||
geometry: { type: 'path', d: 'M1 1 L5 5' },
|
||||
name: { fr: 'Crâne', en: 'Skull' },
|
||||
finding_zone_id: 'neck',
|
||||
vertebral_region_code: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
op: 'set',
|
||||
target: 'view:head',
|
||||
field: 'view_box',
|
||||
value: { min_x: 2.5, min_y: 1, width: 40, height: 30 },
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'nothing-but-a-level-a',
|
||||
changes_file: {
|
||||
changes: [
|
||||
change('CHG-001', [
|
||||
{ op: 'set', target: 'document', field: 'name.en', value: 'Small' },
|
||||
]),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Prettier measures an emoji with its RGI table; the port refuses (declared: the report
|
||||
// guard first, UnsupportedMarkdown, before the aligner's UnsupportedWidth of R5.2).
|
||||
name: 'declared-emoji-in-a-cell',
|
||||
changes_file: {
|
||||
changes: [
|
||||
change('CHG-001', [
|
||||
{
|
||||
op: 'set',
|
||||
target: MOBILITY,
|
||||
field: 'name.en',
|
||||
value: 'Mobility 🐴',
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
async function run(c: Case) {
|
||||
const changeset = ChangesetSchema.parse(c.changes_file)
|
||||
const baseline = miniSheet()
|
||||
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
|
||||
const before = documentStats(baseline)
|
||||
const after = documentStats(result.document)
|
||||
const migration = buildReportMigrationMap({
|
||||
baseline: miniSheet() as never,
|
||||
final: result.document as never,
|
||||
legacyIdMap: LEGACY_ID_MAP,
|
||||
records: result.records,
|
||||
sheet: SHEET,
|
||||
mainViewId: 'main',
|
||||
})
|
||||
const changelogRaw = renderChangelog(result, before, after, migration.stats)
|
||||
const reviewRaw = renderReviewReport({
|
||||
changes: changeset.changes.map(changeSummary),
|
||||
records: result.records,
|
||||
document: result.document,
|
||||
statsBefore: before,
|
||||
legacyAnomalies: ANOMALIES as never,
|
||||
})
|
||||
const drawings: Record<string, string> = {}
|
||||
for (const view of result.document.views) {
|
||||
drawings[`annotations-${view.id}`] = renderReviewOverlay({
|
||||
cleanedSvg: DRAWING,
|
||||
before: miniSheet(),
|
||||
after: result.document,
|
||||
viewId: view.id,
|
||||
})
|
||||
}
|
||||
for (const view of result.document.views) {
|
||||
drawings[`app-${view.id}`] = renderAppReviewDrawing({
|
||||
cleanedSvg: DRAWING,
|
||||
document: result.document,
|
||||
viewId: view.id,
|
||||
})
|
||||
}
|
||||
return {
|
||||
...c,
|
||||
changelog_raw: changelogRaw,
|
||||
changelog: await formatMarkdown(changelogRaw),
|
||||
review_raw: reviewRaw,
|
||||
review: await formatMarkdown(reviewRaw),
|
||||
drawings,
|
||||
}
|
||||
}
|
||||
|
||||
describe('R5.4 synthetic review oracle', () => {
|
||||
it('review-synthetic.json', async () => {
|
||||
const rows = []
|
||||
for (const c of CASES) rows.push(await run(c))
|
||||
const oracle = {
|
||||
baseline: miniSheet(),
|
||||
references: MINI_REFERENCES,
|
||||
drawing: DRAWING,
|
||||
anomalies: ANOMALIES,
|
||||
legacy_id_map: LEGACY_ID_MAP,
|
||||
cases: rows,
|
||||
}
|
||||
const text = `${JSON.stringify(oracle)}\n`
|
||||
const file = resolve(OUT, 'review-synthetic.json')
|
||||
if (MAKE) {
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
writeFileSync(file, text)
|
||||
}
|
||||
expect(text).toBe(readFileSync(file, 'utf8'))
|
||||
})
|
||||
})
|
||||
@@ -1,230 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
composeViewSvg,
|
||||
EQUINE_DRAFT_DIR,
|
||||
HALO_FILTER_ID,
|
||||
highlightLayer,
|
||||
renderAnnotationLayer,
|
||||
renderAppReviewDrawing,
|
||||
type DraftResult,
|
||||
type LayerElement,
|
||||
} from '../src'
|
||||
import { REPO_ROOT, runDraft } from './helpers'
|
||||
|
||||
const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR)
|
||||
const HALO_FILTER_MARKUP =
|
||||
`<defs><filter id="${HALO_FILTER_ID}" x="-100%" y="-100%" width="300%" ` +
|
||||
'height="300%" filterUnits="userSpaceOnUse">' +
|
||||
'<feGaussianBlur in="SourceGraphic" stdDeviation="18" result="haloWide"/>' +
|
||||
'<feGaussianBlur in="SourceGraphic" stdDeviation="8" result="haloTight"/>' +
|
||||
'<feMerge><feMergeNode in="haloWide"/><feMergeNode in="haloWide"/>' +
|
||||
'<feMergeNode in="haloWide"/><feMergeNode in="haloTight"/>' +
|
||||
'<feMergeNode in="haloTight"/><feMergeNode in="SourceGraphic"/>' +
|
||||
'</feMerge></filter></defs>'
|
||||
|
||||
let draft: DraftResult
|
||||
let horseSvg: string
|
||||
|
||||
/** The committed cleaned drawing, parsed fresh for every test. */
|
||||
function parseHorse(): Element {
|
||||
const doc = new DOMParser().parseFromString(horseSvg, 'image/svg+xml')
|
||||
return doc.documentElement!
|
||||
}
|
||||
|
||||
function serialize(root: Element): string {
|
||||
return new XMLSerializer().serializeToString(root.ownerDocument!)
|
||||
}
|
||||
|
||||
function elements(list: { length: number; item(i: number): Element | null }) {
|
||||
return Array.from({ length: list.length }, (_, i) => list.item(i)!)
|
||||
}
|
||||
|
||||
/** Element children of the layer `<g>`, the last child of the root. */
|
||||
function layerChildren(root: Element): Element[] {
|
||||
const layer = root.lastChild as Element
|
||||
expect(layer.nodeName).toBe('g')
|
||||
return elements(layer.childNodes as never).filter((n) => n.nodeType === 1)
|
||||
}
|
||||
|
||||
function dataAttributeCount(root: Element): number {
|
||||
return (serialize(root).match(/ data-[a-z-]+="/g) ?? []).length
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
;({ draft } = await runDraft())
|
||||
const [asset] = draft.assets
|
||||
horseSvg = await readFile(join(draftDir, 'assets', asset!.file), 'utf8')
|
||||
})
|
||||
|
||||
describe('composeViewSvg with a highlight', () => {
|
||||
it('keeps both elements of a selected point and the selected spine zone, haloed on the main view', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
|
||||
})
|
||||
const kept = layerChildren(root)
|
||||
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle', 'polygon'])
|
||||
for (const element of kept) {
|
||||
expect(element.getAttribute('fill')).toBe('#b85a3f')
|
||||
expect(element.getAttribute('fill-opacity')).toBe('0.85')
|
||||
expect(element.getAttribute('filter')).toBe(`url(#${HALO_FILTER_ID})`)
|
||||
}
|
||||
expect(kept[0]!.getAttribute('r')).toBe('34')
|
||||
expect(kept[1]!.getAttribute('r')).toBe('22')
|
||||
expect(root.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
|
||||
expect(root.hasAttribute('width')).toBe(false)
|
||||
expect(root.hasAttribute('height')).toBe(false)
|
||||
})
|
||||
|
||||
it('creates <defs> as the first child of an asset without one and fills it with the halo filter', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
highlight: { annotationIds: new Set(['hip']), halo: true },
|
||||
})
|
||||
expect(root.firstChild!.nodeName).toBe('defs')
|
||||
expect(root.getElementsByTagName('defs')).toHaveLength(1)
|
||||
expect(serialize(root)).toContain(HALO_FILTER_MARKUP)
|
||||
})
|
||||
|
||||
it('never duplicates the filter on a root that already holds it', () => {
|
||||
const root = parseHorse()
|
||||
const input = {
|
||||
root,
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
highlight: { annotationIds: new Set(['hip']), halo: true },
|
||||
}
|
||||
composeViewSvg(input)
|
||||
composeViewSvg(input)
|
||||
const filters = elements(root.getElementsByTagName('filter')).filter(
|
||||
(f) => f.getAttribute('id') === HALO_FILTER_ID,
|
||||
)
|
||||
expect(filters).toHaveLength(1)
|
||||
expect(root.getElementsByTagName('defs')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('frames the head view on its view box without any halo', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'head',
|
||||
highlight: { annotationIds: new Set(['parietal']), halo: false },
|
||||
})
|
||||
expect(root.getAttribute('viewBox')).toBe('60 100 500 380')
|
||||
expect(root.getElementsByTagName('defs')).toHaveLength(0)
|
||||
expect(serialize(root)).not.toContain(HALO_FILTER_ID)
|
||||
const kept = layerChildren(root)
|
||||
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle'])
|
||||
for (const element of kept) {
|
||||
expect(element.getAttribute('fill')).toBe('#b85a3f')
|
||||
expect(element.hasAttribute('filter')).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves an empty layer when nothing is selected', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
highlight: { annotationIds: new Set(), halo: true },
|
||||
})
|
||||
expect(layerChildren(root)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('keeps the <title> of every kept marker and emits no data attribute', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
|
||||
})
|
||||
const titles = elements(root.lastChild!.childNodes as never)
|
||||
.filter((n) => n.nodeType === 1)
|
||||
.map((e) => e.getElementsByTagName('title').item(0)!.textContent)
|
||||
expect(titles).toEqual([
|
||||
'Hanche (coxo-fémorale) / Hip joint',
|
||||
'Hanche (coxo-fémorale) / Hip joint',
|
||||
'Vertèbres cervicales / Cervical vertebrae',
|
||||
])
|
||||
expect(dataAttributeCount(root)).toBe(0)
|
||||
})
|
||||
|
||||
it('refuses an unknown view', () => {
|
||||
expect(() =>
|
||||
composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'nope',
|
||||
highlight: { annotationIds: new Set(), halo: false },
|
||||
}),
|
||||
).toThrow('unknown view')
|
||||
})
|
||||
})
|
||||
|
||||
describe('highlightLayer on the layer tree', () => {
|
||||
function flatten(node: LayerElement): LayerElement[] {
|
||||
return [node, ...node.children.flatMap(flatten)]
|
||||
}
|
||||
|
||||
it('filters, restyles and strips data attributes without touching the input', () => {
|
||||
const layer = renderAnnotationLayer({
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
})
|
||||
const before = JSON.stringify(layer)
|
||||
const highlighted = highlightLayer(layer, {
|
||||
annotationIds: new Set(['cervical']),
|
||||
halo: false,
|
||||
})
|
||||
expect(JSON.stringify(layer)).toBe(before)
|
||||
expect(highlighted.children).toHaveLength(1)
|
||||
expect(highlighted.children[0]!.attrs).toMatchObject({
|
||||
fill: '#b85a3f',
|
||||
'fill-opacity': '0.85',
|
||||
'stroke-width': '2',
|
||||
})
|
||||
expect(highlighted.children[0]!.attrs.filter).toBeUndefined()
|
||||
const dataKeys = flatten(highlighted).flatMap((n) =>
|
||||
Object.keys(n.attrs).filter((k) => k.startsWith('data-')),
|
||||
)
|
||||
expect(dataKeys).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('composeViewSvg without a highlight (review drawings)', () => {
|
||||
it.each(['main', 'head'])(
|
||||
'renderAppReviewDrawing(%s) equals the committed review drawing',
|
||||
async (viewId) => {
|
||||
const committed = await readFile(
|
||||
join(draftDir, 'review', `app-${viewId}.svg`),
|
||||
'utf8',
|
||||
)
|
||||
const rendered = renderAppReviewDrawing({
|
||||
cleanedSvg: horseSvg,
|
||||
document: draft.document,
|
||||
viewId,
|
||||
})
|
||||
expect(rendered).toBe(committed)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps the full interactive layer with its data attributes', () => {
|
||||
const root = composeViewSvg({
|
||||
root: parseHorse(),
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
})
|
||||
expect(root.getElementsByTagName('defs')).toHaveLength(0)
|
||||
expect((root.lastChild as Element).getAttribute('data-layer')).toBe(
|
||||
'annotations',
|
||||
)
|
||||
expect(dataAttributeCount(root)).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
@@ -1,158 +0,0 @@
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createLayerElement,
|
||||
renderAnnotationLayer,
|
||||
serializeLayer,
|
||||
styleForView,
|
||||
type DraftResult,
|
||||
type LayerElement,
|
||||
} from '../src'
|
||||
import { miniSheet } from './fixtures/mini-sheet'
|
||||
import { runDraft } from './helpers'
|
||||
|
||||
function flatten(node: LayerElement): LayerElement[] {
|
||||
return [node, ...node.children.flatMap(flatten)]
|
||||
}
|
||||
|
||||
function byId(layer: LayerElement, id: string): LayerElement[] {
|
||||
return flatten(layer).filter((n) => n.attrs['data-anno-id'] === id)
|
||||
}
|
||||
|
||||
describe('annotation layer on the real draft', () => {
|
||||
let draft: DraftResult
|
||||
beforeAll(async () => {
|
||||
;({ draft } = await runDraft())
|
||||
})
|
||||
|
||||
it('draws every annotation of the main view as the legacy pair, zone or trigger', () => {
|
||||
const layer = renderAnnotationLayer({
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
})
|
||||
expect(layer.attrs).toEqual({
|
||||
'data-layer': 'annotations',
|
||||
'data-view-id': 'main',
|
||||
})
|
||||
const main = draft.document.annotations.filter((a) => a.view_id === 'main')
|
||||
for (const a of main) {
|
||||
const els = byId(layer, a.id)
|
||||
if (a.kind === 'point')
|
||||
expect(els.map((e) => e.tag)).toEqual(['circle', 'circle'])
|
||||
else expect(els).toHaveLength(1)
|
||||
}
|
||||
const [hitbox, visible] = byId(layer, 'hip')
|
||||
expect(hitbox!.attrs).toMatchObject({
|
||||
r: '34',
|
||||
fill: 'transparent',
|
||||
'pointer-events': 'all',
|
||||
'data-anno-lateral': 'bilateral',
|
||||
'data-anno-zone': 'hip',
|
||||
})
|
||||
expect(visible!.attrs).toMatchObject({
|
||||
r: '22',
|
||||
fill: '#ff9500',
|
||||
'fill-opacity': '0.65',
|
||||
stroke: '#000',
|
||||
'stroke-width': '1.5',
|
||||
'pointer-events': 'none',
|
||||
})
|
||||
expect(hitbox!.children[0]).toMatchObject({
|
||||
tag: 'title',
|
||||
text: 'Hanche (coxo-fémorale) / Hip joint',
|
||||
})
|
||||
const [spine] = byId(layer, 'cervical')
|
||||
expect(spine!.tag).toBe('polygon')
|
||||
expect(spine!.attrs).toMatchObject({
|
||||
fill: '#e100ff',
|
||||
'fill-opacity': '0.3',
|
||||
'stroke-width': '2',
|
||||
'data-anno-region': 'C',
|
||||
})
|
||||
const [trigger] = byId(layer, 'head-trigger')
|
||||
expect(trigger!.attrs).toMatchObject({
|
||||
'data-anno-kind': 'detail_trigger',
|
||||
'data-anno-opens-view': 'head',
|
||||
'stroke-dasharray': '8,4',
|
||||
'fill-opacity': '0.06',
|
||||
class: 'detail-zone',
|
||||
})
|
||||
expect(trigger!.attrs['data-anno-name-fr']).toBe(
|
||||
'Tête (vue latérale gauche)',
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the detail style, the annotation colour override and the view box on the head view', () => {
|
||||
const layer = renderAnnotationLayer({
|
||||
document: draft.document,
|
||||
viewId: 'head',
|
||||
})
|
||||
const [c0c1Hit, c0c1Vis] = byId(layer, 'c0-c1')
|
||||
expect(c0c1Hit!.attrs.r).toBe('27')
|
||||
expect(c0c1Vis!.attrs).toMatchObject({
|
||||
r: '15',
|
||||
fill: '#ff0000',
|
||||
'fill-opacity': '0.5',
|
||||
})
|
||||
expect(byId(layer, 'atm')[1]!.attrs.fill).toBe('#ff8800')
|
||||
expect(byId(layer, 'hyoid')[1]!.attrs.fill).toBe('#d507c4')
|
||||
expect(byId(layer, 'parietal')[1]!.attrs.fill).toBe('#1baa08')
|
||||
expect(styleForView(draft.document.views[1]!).visibleFillOpacity).toBe(0.5)
|
||||
expect(flatten(layer).some((n) => n.attrs['data-anno-id'] === 'hip')).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('applies states as data-state on both elements of a point', () => {
|
||||
const states = new Map([['hip', 'current' as const]])
|
||||
const layer = renderAnnotationLayer({
|
||||
document: draft.document,
|
||||
viewId: 'main',
|
||||
states,
|
||||
})
|
||||
expect(
|
||||
byId(layer, 'hip').every((e) => e.attrs['data-state'] === 'current'),
|
||||
).toBe(true)
|
||||
expect(
|
||||
byId(layer, 'stifle').every((e) => e.attrs['data-state'] === undefined),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('materialises through a DOM and serialises to the same markup', () => {
|
||||
const layer = renderAnnotationLayer({
|
||||
document: draft.document,
|
||||
viewId: 'head',
|
||||
})
|
||||
const doc = new DOMParser().parseFromString(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg"/>',
|
||||
'image/svg+xml',
|
||||
)
|
||||
const element = createLayerElement(doc as never, layer) as unknown as {
|
||||
getAttribute(name: string): string | null
|
||||
getElementsByTagName(tag: string): { length: number }
|
||||
}
|
||||
expect(element.getAttribute('data-layer')).toBe('annotations')
|
||||
expect(element.getElementsByTagName('circle')).toHaveLength(18)
|
||||
const text = serializeLayer(layer)
|
||||
expect(text).toContain('<g data-layer="annotations" data-view-id="head">')
|
||||
expect(text).toContain('<title>Appareil hyoïdien / Hyoid apparatus</title>')
|
||||
expect(text).not.toContain('<script')
|
||||
})
|
||||
})
|
||||
|
||||
describe('annotation layer edge cases', () => {
|
||||
it('skips annotations without geometry and falls back to grey without any colour', () => {
|
||||
const sheet = miniSheet()
|
||||
const layer = renderAnnotationLayer({ document: sheet, viewId: 'main' })
|
||||
const ids = new Set(
|
||||
flatten(layer)
|
||||
.map((n) => n.attrs['data-anno-id'])
|
||||
.filter(Boolean),
|
||||
)
|
||||
expect(ids.has('hip')).toBe(true)
|
||||
expect(byId(layer, 'hip')[1]!.attrs.fill).toBe('#888888')
|
||||
expect(() =>
|
||||
renderAnnotationLayer({ document: sheet, viewId: 'nope' }),
|
||||
).toThrow('unknown view')
|
||||
})
|
||||
})
|
||||
@@ -1,98 +0,0 @@
|
||||
import { readdir, readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
EQUINE_DRAFT_DIR,
|
||||
EQUINE_LEGACY_IMPORT_DIR,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
renderArtifacts,
|
||||
renderDraftArtifacts,
|
||||
sha256Hex,
|
||||
type AssetRecord,
|
||||
type DraftResult,
|
||||
} from '../src'
|
||||
import { REPO_ROOT, runDraft } from './helpers'
|
||||
|
||||
const legacyDir = join(REPO_ROOT, EQUINE_LEGACY_IMPORT_DIR)
|
||||
const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR)
|
||||
let legacy: Record<string, string>
|
||||
let draftFiles: Record<string, string>
|
||||
let draft: DraftResult
|
||||
|
||||
/** Recursive file list, relative to `dir`, with forward slashes. */
|
||||
async function listFiles(dir: string): Promise<string[]> {
|
||||
const entries = await readdir(dir, { recursive: true, withFileTypes: true })
|
||||
return entries
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1))
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const run = await runDraft()
|
||||
draft = run.draft
|
||||
legacy = await renderArtifacts(run.result)
|
||||
draftFiles = await renderDraftArtifacts(run.draft, run.result.anomalies)
|
||||
})
|
||||
|
||||
describe('committed legacy-import folder (golden)', () => {
|
||||
it.each([
|
||||
'document.json',
|
||||
'legacy-id-map.json',
|
||||
'assets.json',
|
||||
'IMPORT-REPORT.md',
|
||||
])('%s equals a fresh run (rerun pnpm import:equine)', async (file) => {
|
||||
expect(await readFile(join(legacyDir, file), 'utf8')).toBe(legacy[file])
|
||||
})
|
||||
|
||||
it('carries no SQL: the draft folder holds the only seed', () => {
|
||||
expect(Object.keys(legacy).some((file) => file.endsWith('.sql'))).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('copies the SVG assets byte for byte with the recorded sha256', async () => {
|
||||
const assets = JSON.parse(legacy['assets.json']!) as AssetRecord[]
|
||||
const sources = [EQUINE_SOURCE_PATHS.mainSvg, EQUINE_SOURCE_PATHS.headSvg]
|
||||
for (const [index, asset] of assets.entries()) {
|
||||
const copy = await readFile(join(legacyDir, 'assets', asset.file))
|
||||
const original = await readFile(join(REPO_ROOT, sources[index]!))
|
||||
expect(copy.equals(original)).toBe(true)
|
||||
expect(sha256Hex(copy)).toBe(asset.sha256)
|
||||
expect(copy.byteLength).toBe(asset.byte_size)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Since R5.6 the Rust pipeline writes the seed (`pnpm import:equine`) under the fingerprint
|
||||
* convention `sha256-rfc8785-validated-v1`; this TypeScript generator (`import:equine:legacy`)
|
||||
* keeps the historical one. Its two fingerprint-bearing files are compared with the pre-switch
|
||||
* files it wrote (frozen under `crates/core/tests/fixtures/r5-6/pre-switch`, proven against the
|
||||
* R5.1 ledger by the Rust suite `curation_draft`); every other file with the committed seed.
|
||||
*/
|
||||
const PRE_SWITCH = join(REPO_ROOT, 'crates/core/tests/fixtures/r5-6/pre-switch')
|
||||
const FINGERPRINTED = new Set(['sheet-ref.json', 'report-migration-map.json'])
|
||||
|
||||
describe('committed draft folder (golden)', () => {
|
||||
it('equals a fresh run for every produced file (the two fingerprinted ones before R5.6)', async () => {
|
||||
for (const [file, content] of Object.entries(draftFiles)) {
|
||||
const dir = FINGERPRINTED.has(file) ? PRE_SWITCH : draftDir
|
||||
expect(await readFile(join(dir, file), 'utf8'), file).toBe(content)
|
||||
}
|
||||
})
|
||||
|
||||
it('holds no file the run does not produce', async () => {
|
||||
const expected = [
|
||||
...Object.keys(draftFiles),
|
||||
...draft.assets.map((asset) => `assets/${asset.file}`),
|
||||
]
|
||||
expect((await listFiles(draftDir)).sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('holds the cleaned drawing with the recorded sha256', async () => {
|
||||
const [asset] = draft.assets
|
||||
const bytes = await readFile(join(draftDir, 'assets', asset!.file))
|
||||
expect(bytes.toString('utf8')).toBe(draft.cleanedSvg)
|
||||
expect(sha256Hex(bytes)).toBe(asset!.sha256)
|
||||
expect(bytes.byteLength).toBe(asset!.byte_size)
|
||||
})
|
||||
})
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"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"]
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
globals: true,
|
||||
include: ['tests/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
@@ -1,20 +0,0 @@
|
||||
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: '^_' },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "@faunosteo/domain",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Faunosteo pure domain model: canonical anatomical sheet document, report document (v3 + v2 migration), 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",
|
||||
"./report": "./src/report/index.ts",
|
||||
"./archive": "./src/archive/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"
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
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: [] },
|
||||
references: [],
|
||||
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: [],
|
||||
})
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export * from './schema'
|
||||
export * from './validate'
|
||||
export * from './create'
|
||||
export * from './sheet-index'
|
||||
@@ -1,327 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Canonical anatomical sheet document, schema_version 2.
|
||||
*
|
||||
* 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,
|
||||
* reference ids…) are checked by validateSheetDocument, not here, so a
|
||||
* draft with dangling references can still be saved.
|
||||
*
|
||||
* Version 2 (Step 4c): shared bibliographic `references` registry cited by
|
||||
* `reference_ids`, `review_status` on findings and annotations, optional
|
||||
* `count_range` on vertebral regions. No version 1 document was ever
|
||||
* published, so version 1 is not read any more.
|
||||
*/
|
||||
|
||||
export const SHEET_DOCUMENT_SCHEMA_VERSION = 2
|
||||
|
||||
/** 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()
|
||||
|
||||
/**
|
||||
* How far the sheet content was checked against references. `inherited` =
|
||||
* taken over from a previous source without review; `reviewed` = checked
|
||||
* and cited; `to_confirm` = changed or added on documented grounds, still
|
||||
* awaiting a professional's confirmation.
|
||||
*/
|
||||
export const ReviewStatusSchema = z.enum(['inherited', 'reviewed', 'to_confirm'])
|
||||
|
||||
const CountRangeSchema = z
|
||||
.object({ min: z.number().int().min(1), max: z.number().int().min(1) })
|
||||
.strict()
|
||||
|
||||
/**
|
||||
* `count` is the usual number of vertebrae (what the picker shows by
|
||||
* default); `count_range` states the documented individual variation so a
|
||||
* report may record a vertebra beyond the usual count. Null = no variation.
|
||||
*/
|
||||
export const VertebralRegionSchema = z
|
||||
.object({
|
||||
code: RegionCodeSchema,
|
||||
name: LocalizedTextSchema,
|
||||
count: z.number().int().min(1),
|
||||
count_range: CountRangeSchema.nullable().default(null),
|
||||
})
|
||||
.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(),
|
||||
review_status: ReviewStatusSchema.default('inherited'),
|
||||
/** Marker colour of this annotation; null = the category colour. */
|
||||
color: HexColorSchema.nullable().default(null),
|
||||
}
|
||||
|
||||
/** 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,
|
||||
])
|
||||
|
||||
/** Documents are shared across users: only web links, never javascript: URLs. */
|
||||
const HttpUrlSchema = z
|
||||
.string()
|
||||
.url()
|
||||
.refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected')
|
||||
|
||||
/**
|
||||
* One bibliographic reference, declared once in the document and cited by
|
||||
* id from any number of findings (an anatomy atlas backs hundreds of
|
||||
* entries). `citation` is the human-readable form (author, title, edition,
|
||||
* year, publisher or journal, location in the work when known).
|
||||
*/
|
||||
export const ReferenceSchema = z
|
||||
.object({
|
||||
id: StableIdSchema,
|
||||
type: z.enum(['book', 'journal', 'standard', 'legal', 'web', 'manual']),
|
||||
citation: z.string().min(1),
|
||||
url: HttpUrlSchema.nullable().default(null),
|
||||
doi: z.string().min(1).nullable().default(null),
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type Reference = z.infer<typeof ReferenceSchema>
|
||||
export type ReviewStatus = z.infer<typeof ReviewStatusSchema>
|
||||
export type LocalizedText = z.infer<typeof LocalizedTextSchema>
|
||||
export type LocalizedOptionalText = z.infer<typeof LocalizedOptionalTextSchema>
|
||||
|
||||
/** 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
|
||||
reference_ids: string[]
|
||||
review_status: ReviewStatus
|
||||
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
|
||||
reference_ids?: string[]
|
||||
review_status?: ReviewStatus
|
||||
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),
|
||||
reference_ids: z.array(StableIdSchema).default([]),
|
||||
review_status: ReviewStatusSchema.default('inherited'),
|
||||
children: z.array(FindingNodeSchema).default([]),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
|
||||
/** Typed business buckets; creators may add their own as 'custom'. */
|
||||
export const FindingCategoryKindSchema = z.enum([
|
||||
'dysfunction',
|
||||
'consultation_reason',
|
||||
'anamnesis',
|
||||
'custom',
|
||||
])
|
||||
|
||||
export const FindingCategorySchema = z
|
||||
.object({
|
||||
id: StableIdSchema,
|
||||
kind: FindingCategoryKindSchema,
|
||||
name: LocalizedTextSchema,
|
||||
description: LocalizedOptionalTextSchema.default({}),
|
||||
reference_ids: z.array(StableIdSchema).default([]),
|
||||
review_status: ReviewStatusSchema.default('inherited'),
|
||||
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,
|
||||
references: z.array(ReferenceSchema),
|
||||
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<typeof VertebralRegionSchema>
|
||||
export type AnnotationCategory = z.infer<typeof AnnotationCategorySchema>
|
||||
export type ViewBox = z.infer<typeof ViewBoxSchema>
|
||||
export type SheetView = z.infer<typeof SheetViewSchema>
|
||||
export type Geometry = z.infer<typeof GeometrySchema>
|
||||
export type Laterality = z.infer<typeof LateralitySchema>
|
||||
export type Annotation = z.infer<typeof AnnotationSchema>
|
||||
export type FindingCategoryKind = z.infer<typeof FindingCategoryKindSchema>
|
||||
export type FindingCategory = z.output<typeof FindingCategorySchema>
|
||||
export type FindingZone = z.output<typeof FindingZoneSchema>
|
||||
@@ -1,127 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
FindingCategory,
|
||||
FindingNode,
|
||||
FindingZone,
|
||||
LocalizedText,
|
||||
SheetView,
|
||||
VertebralRegion,
|
||||
} from './schema'
|
||||
|
||||
/**
|
||||
* Read-only lookups over a sheet document. Everything the editor and the
|
||||
* PDF engine derive from the sheet (zone names, finding paths, spine
|
||||
* regions, trigger targets) comes from the document here, by stable id:
|
||||
* no label drives logic. The index keeps the source it was built from so a
|
||||
* caller gets back exactly what it passed (a loaded sheet with its migration
|
||||
* map, or an archived snapshot).
|
||||
*/
|
||||
|
||||
/** The minimum a sheet source carries: provenance, document, SVG text by asset id. */
|
||||
export interface SheetIndexSource {
|
||||
ref: { documentSha256: string }
|
||||
document: AnatomicalSheetDocument
|
||||
assets: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
export type ObservableAnnotation = Extract<
|
||||
Annotation,
|
||||
{ kind: 'point' | 'zone' }
|
||||
>
|
||||
|
||||
export interface SheetIndex<S extends SheetIndexSource = SheetIndexSource> {
|
||||
sheet: S
|
||||
mainView: SheetView
|
||||
view(id: string): SheetView | undefined
|
||||
annotation(id: string): Annotation | undefined
|
||||
annotationsOfView(viewId: string): Annotation[]
|
||||
findingZone(id: string): FindingZone | undefined
|
||||
/** The category or node at a path, undefined when absent from the sheet. */
|
||||
nodeAt(
|
||||
zoneId: string,
|
||||
path: readonly string[],
|
||||
): FindingCategory | FindingNode | undefined
|
||||
regions(): VertebralRegion[]
|
||||
region(code: string): VertebralRegion | undefined
|
||||
/** The annotation that opens the vertebra picker for a region on a view. */
|
||||
spineAnnotation(
|
||||
regionCode: string,
|
||||
viewId: string,
|
||||
): ObservableAnnotation | undefined
|
||||
/** Whether an annotation opens the vertebra picker. */
|
||||
isSpine(annotationId: string): boolean
|
||||
name(annotation: Annotation): LocalizedText
|
||||
}
|
||||
|
||||
/** The label in a locale, the other locale as fallback, '' when none. */
|
||||
export function pickLabel(
|
||||
text: LocalizedText | null | undefined,
|
||||
locale: 'fr' | 'en',
|
||||
): string {
|
||||
if (!text) return ''
|
||||
return locale === 'en' ? text.en || text.fr : text.fr || text.en
|
||||
}
|
||||
|
||||
export function isObservable(
|
||||
a: Annotation | undefined,
|
||||
): a is ObservableAnnotation {
|
||||
return a !== undefined && a.kind !== 'detail_trigger'
|
||||
}
|
||||
|
||||
function nodeAtPath(
|
||||
zone: FindingZone | undefined,
|
||||
path: readonly string[],
|
||||
): FindingCategory | FindingNode | undefined {
|
||||
if (!zone || path.length === 0) return undefined
|
||||
let node: FindingCategory | FindingNode | undefined = zone.categories.find(
|
||||
(c) => c.id === path[0],
|
||||
)
|
||||
for (const segment of path.slice(1)) {
|
||||
if (!node) return undefined
|
||||
node = node.children.find((n) => n.id === segment)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
export function buildSheetIndex<S extends SheetIndexSource>(
|
||||
sheet: S,
|
||||
): SheetIndex<S> {
|
||||
const { document } = sheet
|
||||
const views = new Map(document.views.map((v) => [v.id, v]))
|
||||
const annotations = new Map(document.annotations.map((a) => [a.id, a]))
|
||||
const zones = new Map(document.finding_zones.map((z) => [z.id, z]))
|
||||
const regions = new Map(
|
||||
document.vertebral_config.regions.map((r) => [r.code, r]),
|
||||
)
|
||||
const mainView = document.views.find((v) => v.kind === 'main')
|
||||
if (!mainView) throw new Error('sheet has no main view')
|
||||
|
||||
return {
|
||||
sheet,
|
||||
mainView,
|
||||
view: (id) => views.get(id),
|
||||
annotation: (id) => annotations.get(id),
|
||||
annotationsOfView: (viewId) =>
|
||||
document.annotations.filter((a) => a.view_id === viewId),
|
||||
findingZone: (id) => zones.get(id),
|
||||
nodeAt: (zoneId, path) => nodeAtPath(zones.get(zoneId), path),
|
||||
regions: () => document.vertebral_config.regions,
|
||||
region: (code) => regions.get(code),
|
||||
spineAnnotation: (code, viewId) =>
|
||||
document.annotations.find(
|
||||
(a): a is ObservableAnnotation =>
|
||||
isObservable(a) &&
|
||||
a.view_id === viewId &&
|
||||
a.vertebral_region_code === code,
|
||||
),
|
||||
isSpine: (id) => {
|
||||
const a = annotations.get(id)
|
||||
return isObservable(a) && a.vertebral_region_code !== null
|
||||
},
|
||||
name: (a) =>
|
||||
a.kind === 'detail_trigger'
|
||||
? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' })
|
||||
: a.name,
|
||||
}
|
||||
}
|
||||
@@ -1,494 +0,0 @@
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
FindingNode,
|
||||
SheetView,
|
||||
VertebralRegion,
|
||||
} from './schema'
|
||||
|
||||
/**
|
||||
* Integrity tier of the sheet model (ANATOMICAL_SHEET_MODEL.md §2.1).
|
||||
*
|
||||
* The shape tier (Zod) accepts dangling references so drafts can be saved
|
||||
* mid-edit; this tier lists every inconsistency for the editor and gates
|
||||
* publication. Each rule is one function; codes are part of the contract
|
||||
* shared with the SQL re-check (private.sheet_document_issues).
|
||||
*/
|
||||
|
||||
export type SheetIssueSeverity = 'error' | 'warning'
|
||||
|
||||
export interface SheetIssue {
|
||||
code: string
|
||||
severity: SheetIssueSeverity
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type Rule = (doc: AnatomicalSheetDocument) => SheetIssue[]
|
||||
|
||||
type ObservableAnnotation = Exclude<Annotation, { kind: 'detail_trigger' }>
|
||||
type TriggerAnnotation = Extract<Annotation, { kind: 'detail_trigger' }>
|
||||
type DetailView = Extract<SheetView, { kind: 'detail' }>
|
||||
|
||||
/** A sibling level of the finding tree: categories or node children. */
|
||||
interface FindingLevelItem {
|
||||
id: string
|
||||
reference_ids: readonly string[]
|
||||
children: readonly FindingNode[]
|
||||
}
|
||||
|
||||
function error(code: string, path: string, message: string): SheetIssue {
|
||||
return { code, severity: 'error', path, message }
|
||||
}
|
||||
|
||||
function warning(code: string, path: string, message: string): SheetIssue {
|
||||
return { code, severity: 'warning', path, message }
|
||||
}
|
||||
|
||||
/** Indexes of entries whose value already appeared earlier in the list. */
|
||||
function repeatedIndexes(values: readonly string[]): number[] {
|
||||
const seen = new Set<string>()
|
||||
const repeated: number[] = []
|
||||
values.forEach((value, index) => {
|
||||
if (seen.has(value)) repeated.push(index)
|
||||
seen.add(value)
|
||||
})
|
||||
return repeated
|
||||
}
|
||||
|
||||
function duplicateIssues(
|
||||
values: readonly string[],
|
||||
code: string,
|
||||
pathOf: (index: number) => string,
|
||||
): SheetIssue[] {
|
||||
return repeatedIndexes(values).map((index) =>
|
||||
error(code, pathOf(index), `Duplicate id "${values[index]}"`),
|
||||
)
|
||||
}
|
||||
|
||||
function isObservable(
|
||||
annotation: Annotation,
|
||||
): annotation is ObservableAnnotation {
|
||||
return annotation.kind !== 'detail_trigger'
|
||||
}
|
||||
|
||||
function isTrigger(annotation: Annotation): annotation is TriggerAnnotation {
|
||||
return annotation.kind === 'detail_trigger'
|
||||
}
|
||||
|
||||
function viewsById(doc: AnatomicalSheetDocument): Map<string, SheetView> {
|
||||
const byId = new Map<string, SheetView>()
|
||||
for (const view of doc.views) if (!byId.has(view.id)) byId.set(view.id, view)
|
||||
return byId
|
||||
}
|
||||
|
||||
/** Rendering starts from a single root drawing. */
|
||||
const checkMainViewCount: Rule = (doc) => {
|
||||
const count = doc.views.filter((view) => view.kind === 'main').length
|
||||
if (count === 1) return []
|
||||
return [
|
||||
error('view.main.count', 'views', `Expected 1 main view, found ${count}`),
|
||||
]
|
||||
}
|
||||
|
||||
const checkViewIdsUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.views.map((view) => view.id),
|
||||
'view.id.duplicate',
|
||||
(index) => `views[${index}].id`,
|
||||
)
|
||||
|
||||
const checkViewParentsExist: Rule = (doc) => {
|
||||
const byId = viewsById(doc)
|
||||
return doc.views.flatMap((view, index) =>
|
||||
view.kind === 'detail' && !byId.has(view.parent_view_id)
|
||||
? [
|
||||
error(
|
||||
'view.parent.missing',
|
||||
`views[${index}].parent_view_id`,
|
||||
`Parent view "${view.parent_view_id}" does not exist`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the parent chain loops before reaching the main view. A
|
||||
* missing parent ends the walk: that case is view.parent.missing.
|
||||
*/
|
||||
function loopsBeforeMain(view: DetailView, byId: Map<string, SheetView>) {
|
||||
const visited = new Set<string>([view.id])
|
||||
let current: SheetView = view
|
||||
while (current.kind === 'detail') {
|
||||
const parent = byId.get(current.parent_view_id)
|
||||
if (!parent) return false
|
||||
if (visited.has(parent.id)) return true
|
||||
visited.add(parent.id)
|
||||
current = parent
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const checkViewParentCycles: Rule = (doc) => {
|
||||
const byId = viewsById(doc)
|
||||
return doc.views.flatMap((view, index) =>
|
||||
view.kind === 'detail' && loopsBeforeMain(view, byId)
|
||||
? [
|
||||
error(
|
||||
'view.parent.cycle',
|
||||
`views[${index}].parent_view_id`,
|
||||
`Parent chain of "${view.id}" never reaches the main view`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
function isOpenedFromParent(
|
||||
view: DetailView,
|
||||
doc: AnatomicalSheetDocument,
|
||||
): boolean {
|
||||
return doc.annotations.some(
|
||||
(annotation) =>
|
||||
isTrigger(annotation) &&
|
||||
annotation.opens_view_id === view.id &&
|
||||
annotation.view_id === view.parent_view_id,
|
||||
)
|
||||
}
|
||||
|
||||
/** A detail view nobody can open is dead content for the practitioner. */
|
||||
const checkViewsReachable: Rule = (doc) => {
|
||||
const byId = viewsById(doc)
|
||||
return doc.views.flatMap((view, index) =>
|
||||
view.kind === 'detail' &&
|
||||
byId.has(view.parent_view_id) &&
|
||||
!isOpenedFromParent(view, doc)
|
||||
? [
|
||||
error(
|
||||
'view.unreachable',
|
||||
`views[${index}]`,
|
||||
`No detail_trigger in "${view.parent_view_id}" opens "${view.id}"`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
/** Every view must have something to draw: its own asset or a crop. */
|
||||
function viewAssetIssue(view: SheetView, index: number): SheetIssue[] {
|
||||
if (view.svg_asset_id !== null) return []
|
||||
if (view.kind === 'main') {
|
||||
return [
|
||||
error(
|
||||
'view.asset.missing',
|
||||
`views[${index}].svg_asset_id`,
|
||||
`Main view "${view.id}" has no SVG asset`,
|
||||
),
|
||||
]
|
||||
}
|
||||
if (view.view_box !== null) return []
|
||||
return [
|
||||
error(
|
||||
'view.asset.missing',
|
||||
`views[${index}].view_box`,
|
||||
`Detail view "${view.id}" has neither an asset nor a view_box`,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
const checkViewAssets: Rule = (doc) => doc.views.flatMap(viewAssetIssue)
|
||||
|
||||
/** Report points are keyed by annotation id across every view. */
|
||||
const checkAnnotationIdsUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.annotations.map((annotation) => annotation.id),
|
||||
'annotation.id.duplicate',
|
||||
(index) => `annotations[${index}].id`,
|
||||
)
|
||||
|
||||
const checkAnnotationViews: Rule = (doc) => {
|
||||
const byId = viewsById(doc)
|
||||
return doc.annotations.flatMap((annotation, index) =>
|
||||
byId.has(annotation.view_id)
|
||||
? []
|
||||
: [
|
||||
error(
|
||||
'annotation.view.missing',
|
||||
`annotations[${index}].view_id`,
|
||||
`View "${annotation.view_id}" does not exist`,
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
const checkAnnotationCategories: Rule = (doc) => {
|
||||
const ids = new Set(doc.categories.map((category) => category.id))
|
||||
return doc.annotations.flatMap((annotation, index) =>
|
||||
ids.has(annotation.category_id)
|
||||
? []
|
||||
: [
|
||||
error(
|
||||
'annotation.category.missing',
|
||||
`annotations[${index}].category_id`,
|
||||
`Category "${annotation.category_id}" does not exist`,
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/** A trigger opens a direct child of the view it is drawn in. */
|
||||
function opensChildOfOwnView(
|
||||
trigger: TriggerAnnotation,
|
||||
byId: Map<string, SheetView>,
|
||||
): boolean {
|
||||
const target = byId.get(trigger.opens_view_id)
|
||||
return target?.kind === 'detail' && target.parent_view_id === trigger.view_id
|
||||
}
|
||||
|
||||
const checkTriggerTargets: Rule = (doc) => {
|
||||
const byId = viewsById(doc)
|
||||
return doc.annotations.flatMap((annotation, index) =>
|
||||
isTrigger(annotation) && !opensChildOfOwnView(annotation, byId)
|
||||
? [
|
||||
error(
|
||||
'annotation.opens_view.invalid',
|
||||
`annotations[${index}].opens_view_id`,
|
||||
`"${annotation.opens_view_id}" is not a detail child of ` +
|
||||
`"${annotation.view_id}"`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
const checkAnnotationFindingZones: Rule = (doc) => {
|
||||
const ids = new Set(doc.finding_zones.map((zone) => zone.id))
|
||||
return doc.annotations.flatMap((annotation, index) =>
|
||||
isObservable(annotation) &&
|
||||
annotation.finding_zone_id !== null &&
|
||||
!ids.has(annotation.finding_zone_id)
|
||||
? [
|
||||
error(
|
||||
'annotation.finding_zone.missing',
|
||||
`annotations[${index}].finding_zone_id`,
|
||||
`Finding zone "${annotation.finding_zone_id}" does not exist`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
const checkAnnotationRegions: Rule = (doc) => {
|
||||
const codes = new Set(doc.vertebral_config.regions.map((r) => r.code))
|
||||
return doc.annotations.flatMap((annotation, index) =>
|
||||
isObservable(annotation) &&
|
||||
annotation.vertebral_region_code !== null &&
|
||||
!codes.has(annotation.vertebral_region_code)
|
||||
? [
|
||||
error(
|
||||
'annotation.region.missing',
|
||||
`annotations[${index}].vertebral_region_code`,
|
||||
`Vertebral region "${annotation.vertebral_region_code}" ` +
|
||||
'is not configured',
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
/** Allowed in a draft, but a click on it would offer nothing to record. */
|
||||
const checkAnnotationsHaveFindings: Rule = (doc) =>
|
||||
doc.annotations.flatMap((annotation, index) =>
|
||||
isObservable(annotation) && annotation.finding_zone_id === null
|
||||
? [
|
||||
warning(
|
||||
'annotation.no_findings',
|
||||
`annotations[${index}].finding_zone_id`,
|
||||
`Annotation "${annotation.id}" is linked to no finding zone`,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
)
|
||||
|
||||
const checkRegionCodesUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.vertebral_config.regions.map((region) => region.code),
|
||||
'region.code.duplicate',
|
||||
(index) => `vertebral_config.regions[${index}].code`,
|
||||
)
|
||||
|
||||
const checkCategoryIdsUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.categories.map((category) => category.id),
|
||||
'category.id.duplicate',
|
||||
(index) => `categories[${index}].id`,
|
||||
)
|
||||
|
||||
const checkFindingZoneIdsUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.finding_zones.map((zone) => zone.id),
|
||||
'finding_zone.id.duplicate',
|
||||
(index) => `finding_zones[${index}].id`,
|
||||
)
|
||||
|
||||
/**
|
||||
* Findings are addressed by (zone, path[]) as Finding.path does today, so
|
||||
* ids only need to be unique among siblings, at every depth.
|
||||
*/
|
||||
function siblingIssues(
|
||||
nodes: readonly FindingLevelItem[],
|
||||
path: string,
|
||||
): SheetIssue[] {
|
||||
const own = duplicateIssues(
|
||||
nodes.map((node) => node.id),
|
||||
'finding.id.duplicate',
|
||||
(index) => `${path}[${index}].id`,
|
||||
)
|
||||
const nested = nodes.flatMap((node, index) =>
|
||||
siblingIssues(node.children, `${path}[${index}].children`),
|
||||
)
|
||||
return [...own, ...nested]
|
||||
}
|
||||
|
||||
const checkFindingSiblings: Rule = (doc) =>
|
||||
doc.finding_zones.flatMap((zone, index) =>
|
||||
siblingIssues(zone.categories, `finding_zones[${index}].categories`),
|
||||
)
|
||||
|
||||
/** Allowed in a draft, but nothing on the drawing can reach this zone. */
|
||||
const checkFindingZonesReferenced: Rule = (doc) => {
|
||||
const referenced = new Set(
|
||||
doc.annotations.filter(isObservable).map((a) => a.finding_zone_id),
|
||||
)
|
||||
return doc.finding_zones.flatMap((zone, index) =>
|
||||
referenced.has(zone.id)
|
||||
? []
|
||||
: [
|
||||
warning(
|
||||
'finding_zone.unreferenced',
|
||||
`finding_zones[${index}]`,
|
||||
`No annotation points to finding zone "${zone.id}"`,
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
const checkReferenceIdsUnique: Rule = (doc) =>
|
||||
duplicateIssues(
|
||||
doc.references.map((reference) => reference.id),
|
||||
'reference.id.duplicate',
|
||||
(index) => `references[${index}].id`,
|
||||
)
|
||||
|
||||
/** A citation must point at a declared reference, at every depth. */
|
||||
function citationIssues(
|
||||
nodes: readonly FindingLevelItem[],
|
||||
path: string,
|
||||
known: ReadonlySet<string>,
|
||||
): SheetIssue[] {
|
||||
return nodes.flatMap((node, index) => {
|
||||
const own = node.reference_ids.flatMap((id, refIndex) =>
|
||||
known.has(id)
|
||||
? []
|
||||
: [
|
||||
error(
|
||||
'finding.reference.missing',
|
||||
`${path}[${index}].reference_ids[${refIndex}]`,
|
||||
`Reference "${id}" is not declared in references`,
|
||||
),
|
||||
],
|
||||
)
|
||||
const nested = citationIssues(
|
||||
node.children,
|
||||
`${path}[${index}].children`,
|
||||
known,
|
||||
)
|
||||
return [...own, ...nested]
|
||||
})
|
||||
}
|
||||
|
||||
const checkFindingReferences: Rule = (doc) => {
|
||||
const known = new Set(doc.references.map((reference) => reference.id))
|
||||
return doc.finding_zones.flatMap((zone, index) =>
|
||||
citationIssues(
|
||||
zone.categories,
|
||||
`finding_zones[${index}].categories`,
|
||||
known,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The usual count must sit inside the documented variation. */
|
||||
function countRangeIssue(region: VertebralRegion, index: number): SheetIssue[] {
|
||||
const range = region.count_range
|
||||
if (range === null) return []
|
||||
if (range.min <= region.count && region.count <= range.max) return []
|
||||
return [
|
||||
error(
|
||||
'region.count_range.invalid',
|
||||
`vertebral_config.regions[${index}].count_range`,
|
||||
`Region "${region.code}": count ${region.count} outside ` +
|
||||
`${range.min}–${range.max}`,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
const checkRegionCountRanges: Rule = (doc) =>
|
||||
doc.vertebral_config.regions.flatMap(countRangeIssue)
|
||||
|
||||
const RULES: readonly Rule[] = [
|
||||
checkMainViewCount,
|
||||
checkViewIdsUnique,
|
||||
checkViewParentsExist,
|
||||
checkViewParentCycles,
|
||||
checkViewsReachable,
|
||||
checkViewAssets,
|
||||
checkAnnotationIdsUnique,
|
||||
checkAnnotationViews,
|
||||
checkAnnotationCategories,
|
||||
checkTriggerTargets,
|
||||
checkAnnotationFindingZones,
|
||||
checkAnnotationRegions,
|
||||
checkAnnotationsHaveFindings,
|
||||
checkRegionCodesUnique,
|
||||
checkCategoryIdsUnique,
|
||||
checkFindingZoneIdsUnique,
|
||||
checkFindingSiblings,
|
||||
checkFindingZonesReferenced,
|
||||
checkReferenceIdsUnique,
|
||||
checkFindingReferences,
|
||||
checkRegionCountRanges,
|
||||
]
|
||||
|
||||
/** Lists every integrity issue of a shape-valid document. */
|
||||
export function validateSheetDocument(
|
||||
doc: AnatomicalSheetDocument,
|
||||
): SheetIssue[] {
|
||||
return RULES.flatMap((rule) => rule(doc))
|
||||
}
|
||||
|
||||
/** Warnings never block publication; errors always do. */
|
||||
export function isPublishable(issues: readonly SheetIssue[]): boolean {
|
||||
return !issues.some((issue) => issue.severity === 'error')
|
||||
}
|
||||
|
||||
export class SheetValidationError extends Error {
|
||||
readonly issues: SheetIssue[]
|
||||
|
||||
constructor(issues: SheetIssue[]) {
|
||||
const errors = issues.filter((issue) => issue.severity === 'error')
|
||||
super(
|
||||
`Sheet document is not publishable: ${errors.length} error(s), ` +
|
||||
`first: ${errors[0]?.code ?? 'none'}`,
|
||||
)
|
||||
this.name = 'SheetValidationError'
|
||||
this.issues = issues
|
||||
}
|
||||
}
|
||||
|
||||
/** TypeScript-side publication gate, mirrored by SQL at publish time. */
|
||||
export function assertPublishable(doc: AnatomicalSheetDocument): void {
|
||||
const issues = validateSheetDocument(doc)
|
||||
if (!isPublishable(issues)) throw new SheetValidationError(issues)
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* The visual identity a PDF archive embeds so a re-export needs no network
|
||||
* and no `public/` folder (STEP6 §3.4): logos as PNG base64 or SVG text,
|
||||
* credits with the URL and the text printed when the logo fails. Caps are
|
||||
* STEP6 §15 (branding row).
|
||||
*/
|
||||
|
||||
const KIB = 1024
|
||||
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
|
||||
|
||||
/**
|
||||
* `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>`
|
||||
* or `\`: the URL is written into PDF link actions and must never be able
|
||||
* to close a string literal or carry a control character. Expressed as the
|
||||
* allowed ranges of printable ASCII (0x21-0x7e) minus those seven.
|
||||
*/
|
||||
const HTTP_URL_PATTERN = /^https?:\/\/[!#-&*-;=?-[\]-~]+$/
|
||||
|
||||
const HttpUrlSchema = z
|
||||
.string()
|
||||
.max(2048)
|
||||
.url()
|
||||
.regex(HTTP_URL_PATTERN, 'http(s) URL expected')
|
||||
|
||||
export const ImageAssetSchema = z.discriminatedUnion('kind', [
|
||||
z
|
||||
.object({
|
||||
kind: z.literal('png'),
|
||||
base64: z
|
||||
.string()
|
||||
.max(512 * KIB)
|
||||
.regex(BASE64_PATTERN),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ kind: z.literal('svg'), svg: z.string().max(256 * KIB) }).strict(),
|
||||
])
|
||||
export type ImageAsset = z.infer<typeof ImageAssetSchema>
|
||||
|
||||
export const CreditSchema = z
|
||||
.object({
|
||||
logo: ImageAssetSchema.nullable(),
|
||||
url: HttpUrlSchema,
|
||||
fallbackText: z.string().max(128),
|
||||
})
|
||||
.strict()
|
||||
export type Credit = z.infer<typeof CreditSchema>
|
||||
|
||||
export const BrandingSchema = z
|
||||
.object({
|
||||
siteUrl: HttpUrlSchema,
|
||||
headerLogo: ImageAssetSchema.nullable(),
|
||||
footerLogo: ImageAssetSchema.nullable(),
|
||||
poweredBy: CreditSchema.nullable(),
|
||||
partner: CreditSchema.nullable(),
|
||||
})
|
||||
.strict()
|
||||
export type Branding = z.infer<typeof BrandingSchema>
|
||||
@@ -1,172 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import { readReportDocument } from '../report/migrate'
|
||||
import type { ReportMigrationMap } from '../report/migration-map'
|
||||
import { REPORT_VERSION, ReportSchema, type Report } from '../report/v3'
|
||||
import { BrandingSchema, type Branding } from './branding'
|
||||
import { PdfLabelSetSchema, type PdfLabelSet } from './labels'
|
||||
import {
|
||||
SheetSnapshotSchema,
|
||||
SnapshotError,
|
||||
assertSnapshot,
|
||||
type SheetSnapshot,
|
||||
type SnapshotRejection,
|
||||
} from './snapshot'
|
||||
|
||||
/**
|
||||
* Attachment of a Step 6 PDF: the report (v3, unchanged) wrapped with the
|
||||
* sheet snapshot, the branding and the PDF labels it was printed with
|
||||
* (STEP6 §2.3). Reading is layered (§4, §14 "Read"): the report is located
|
||||
* and parsed first so it is never lost because of its wrapper; the wrapper
|
||||
* is then validated or dropped with a reason.
|
||||
*/
|
||||
|
||||
export const ENVELOPE_FORMAT = 'faunosteo-report-archive'
|
||||
export const ENVELOPE_VERSION = 1
|
||||
|
||||
export interface ReportArchiveEnvelope {
|
||||
format: typeof ENVELOPE_FORMAT
|
||||
envelopeVersion: typeof ENVELOPE_VERSION
|
||||
/** ISO timestamp of the export. */
|
||||
exportedAt: string
|
||||
locale: 'fr' | 'en'
|
||||
/** As exported, never rebased. */
|
||||
report: Report
|
||||
sheetSnapshot: SheetSnapshot
|
||||
branding: Branding
|
||||
labels: PdfLabelSet
|
||||
}
|
||||
|
||||
/** Metadata is not strict: an additive v1 field never breaks an older reader. */
|
||||
const EnvelopeMetadataSchema = z.object({
|
||||
format: z.literal(ENVELOPE_FORMAT),
|
||||
envelopeVersion: z.literal(ENVELOPE_VERSION),
|
||||
exportedAt: z.string(),
|
||||
locale: z.enum(['fr', 'en']),
|
||||
})
|
||||
|
||||
/** Everything but the report and the snapshot, which the reader checks itself. */
|
||||
const EnvelopeWrapperSchema = EnvelopeMetadataSchema.extend({
|
||||
branding: BrandingSchema,
|
||||
labels: PdfLabelSetSchema,
|
||||
})
|
||||
|
||||
export const ReportArchiveEnvelopeSchema: z.ZodType<
|
||||
ReportArchiveEnvelope,
|
||||
z.ZodTypeDef,
|
||||
unknown
|
||||
> = EnvelopeWrapperSchema.extend({
|
||||
report: ReportSchema,
|
||||
sheetSnapshot: SheetSnapshotSchema,
|
||||
})
|
||||
|
||||
export type ArchiveOrigin = 'envelope_v1' | 'bare_v3' | 'v2'
|
||||
|
||||
export interface ArchiveReadOutcome {
|
||||
report: Report
|
||||
origin: ArchiveOrigin
|
||||
migrated: boolean
|
||||
/** From the v2 migration; 0 for a v3 report. */
|
||||
unresolvedZones: number
|
||||
unresolvedFindings: number
|
||||
/** The validated envelope, when accepted. */
|
||||
archive: ReportArchiveEnvelope | null
|
||||
/** Envelope present but its snapshot dropped. */
|
||||
snapshotRejected?: SnapshotRejection
|
||||
}
|
||||
|
||||
type Wrapped =
|
||||
| { archive: ReportArchiveEnvelope }
|
||||
| { snapshotRejected: SnapshotRejection }
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** An envelope of any version is recognised by a numeric envelopeVersion. */
|
||||
function envelopeVersionOf(data: unknown): number | null {
|
||||
if (!isRecord(data)) return null
|
||||
const version = data.envelopeVersion
|
||||
return typeof version === 'number' ? version : null
|
||||
}
|
||||
|
||||
function reportVersionOf(data: unknown): number | null {
|
||||
if (!isRecord(data)) return null
|
||||
return typeof data.version === 'number' ? data.version : null
|
||||
}
|
||||
|
||||
function snapshotMatches(snapshot: SheetSnapshot, report: Report): boolean {
|
||||
return (
|
||||
snapshot.ref.sheetId === report.sheet.sheetId &&
|
||||
snapshot.ref.documentSha256 === report.sheet.documentSha256
|
||||
)
|
||||
}
|
||||
|
||||
/** Step 3 for a v1 envelope: wrapper schema → snapshot gate → sheet invariant. */
|
||||
function readEnvelopeV1(
|
||||
data: Record<string, unknown>,
|
||||
report: Report,
|
||||
): Wrapped {
|
||||
const wrapper = EnvelopeWrapperSchema.safeParse(data)
|
||||
if (!wrapper.success) return { snapshotRejected: 'schema' }
|
||||
let snapshot: SheetSnapshot
|
||||
try {
|
||||
snapshot = assertSnapshot(data.sheetSnapshot)
|
||||
} catch (error) {
|
||||
if (error instanceof SnapshotError) {
|
||||
return { snapshotRejected: error.reason }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (!snapshotMatches(snapshot, report)) {
|
||||
return { snapshotRejected: 'sheet_mismatch' }
|
||||
}
|
||||
return {
|
||||
archive: {
|
||||
format: wrapper.data.format,
|
||||
envelopeVersion: wrapper.data.envelopeVersion,
|
||||
exportedAt: wrapper.data.exportedAt,
|
||||
locale: wrapper.data.locale,
|
||||
report,
|
||||
sheetSnapshot: snapshot,
|
||||
branding: wrapper.data.branding,
|
||||
labels: wrapper.data.labels,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the JSON of a PDF attachment of any supported shape: bare Report v2
|
||||
* or v3, or an archive envelope. The report is parsed first and always
|
||||
* returned (`readReportDocument` throws UnsupportedReportVersionError for an
|
||||
* unknown report version); the envelope is accepted whole or dropped with
|
||||
* `snapshotRejected`.
|
||||
*/
|
||||
export function readArchiveDocument(
|
||||
data: unknown,
|
||||
map: ReportMigrationMap,
|
||||
): ArchiveReadOutcome {
|
||||
const envelopeVersion = envelopeVersionOf(data)
|
||||
const reportData =
|
||||
envelopeVersion !== null ? (data as Record<string, unknown>).report : data
|
||||
const outcome = readReportDocument(reportData, map)
|
||||
const migrated = reportVersionOf(reportData) !== REPORT_VERSION
|
||||
const base: ArchiveReadOutcome = {
|
||||
report: outcome.report,
|
||||
origin: migrated ? 'v2' : 'bare_v3',
|
||||
migrated,
|
||||
unresolvedZones: outcome.unresolvedZones,
|
||||
unresolvedFindings: outcome.unresolvedFindings,
|
||||
archive: null,
|
||||
}
|
||||
if (envelopeVersion === null) return base
|
||||
if (envelopeVersion !== ENVELOPE_VERSION) {
|
||||
return { ...base, snapshotRejected: 'unsupported_envelope' }
|
||||
}
|
||||
const wrapped = readEnvelopeV1(
|
||||
data as Record<string, unknown>,
|
||||
outcome.report,
|
||||
)
|
||||
return 'archive' in wrapped
|
||||
? { ...base, origin: 'envelope_v1', archive: wrapped.archive }
|
||||
: { ...base, origin: 'envelope_v1', ...wrapped }
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export * from './snapshot'
|
||||
export * from './branding'
|
||||
export * from './labels'
|
||||
export * from './envelope'
|
||||
@@ -1,57 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* The static strings the PDF engine prints (section headings, metadata,
|
||||
* severities, sides, footer credits), in both locales, frozen into the
|
||||
* archive so a re-export renders the wording of the day. Exactly the dict
|
||||
* keys apps/app/src/pdf read when Step 6 started.
|
||||
*/
|
||||
|
||||
export const PDF_LABEL_KEYS = [
|
||||
'pdf.empty',
|
||||
'pdf.eyebrow.observation',
|
||||
'pdf.eyebrow.synthesis',
|
||||
'pdf.owner_prefix',
|
||||
'pdf.section.comment',
|
||||
'pdf.section.conclusion',
|
||||
'pdf.section.findings_prefix',
|
||||
'pdf.section.free_findings',
|
||||
'pdf.section.next_appointment',
|
||||
'pdf.section.recommendations',
|
||||
'pdf.section.severity',
|
||||
'pdf.section.zones',
|
||||
'pdf.siret_prefix',
|
||||
'pdf.subject',
|
||||
'pdf.title.conclusion',
|
||||
'pdf.title.suffix.bilan',
|
||||
'pdf.view.detail_prefix',
|
||||
'pdf.view.general',
|
||||
'severity.mild',
|
||||
'severity.moderate',
|
||||
'severity.severe',
|
||||
'lateral.left',
|
||||
'lateral.right',
|
||||
'footer.powered_by',
|
||||
'footer.in_partnership',
|
||||
] as const
|
||||
|
||||
export type PdfLabelKey = (typeof PDF_LABEL_KEYS)[number]
|
||||
export type PdfLabels = Record<PdfLabelKey, string>
|
||||
|
||||
export interface PdfLabelSet {
|
||||
fr: PdfLabels
|
||||
en: PdfLabels
|
||||
}
|
||||
|
||||
const labelShape = Object.fromEntries(
|
||||
PDF_LABEL_KEYS.map((key) => [key, z.string().max(256)]),
|
||||
) as Record<PdfLabelKey, z.ZodString>
|
||||
|
||||
export const PdfLabelsSchema: z.ZodType<PdfLabels> = z
|
||||
.object(labelShape)
|
||||
.strict()
|
||||
|
||||
/** Strict: every key present in both locales, no extra key. */
|
||||
export const PdfLabelSetSchema: z.ZodType<PdfLabelSet> = z
|
||||
.object({ fr: PdfLabelsSchema, en: PdfLabelsSchema })
|
||||
.strict()
|
||||
@@ -1,425 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
type AnatomicalSheetDocument,
|
||||
type FindingCategory,
|
||||
type FindingNode,
|
||||
type FindingZone,
|
||||
type SheetView,
|
||||
} from '../anatomical-sheet/schema'
|
||||
import { validateSheetDocument } from '../anatomical-sheet/validate'
|
||||
import type { SheetIndexSource } from '../anatomical-sheet/sheet-index'
|
||||
import { SheetRefSchema, type Report, type SheetRef } from '../report/v3'
|
||||
|
||||
/**
|
||||
* The sheet a report archive carries so an old bilan re-renders without the
|
||||
* current catalog (STEP6 §2.2). The snapshot keeps the shape the renderer and
|
||||
* the sheet index consume: a valid, lean `AnatomicalSheetDocument` (every
|
||||
* view, annotation, category and region; finding trees pruned to the paths
|
||||
* the report uses; bibliography emptied) plus the SVG text of every asset a
|
||||
* view reaches. `assertSnapshot` is the single gate an imported snapshot
|
||||
* passes (STEP6 §15 caps, integrity, reachable assets).
|
||||
*/
|
||||
|
||||
const SHA256_PATTERN = /^[0-9a-f]{64}$/
|
||||
const MIB = 1024 * 1024
|
||||
|
||||
/** Hard limits on an imported snapshot; every excess is a `caps` rejection. */
|
||||
export const SNAPSHOT_CAPS = {
|
||||
views: 64,
|
||||
annotations: 1024,
|
||||
findingNodes: 8192,
|
||||
findingDepth: 8,
|
||||
labelChars: 512,
|
||||
assets: 4,
|
||||
assetBytes: 2 * MIB,
|
||||
assetsTotalBytes: 6 * MIB,
|
||||
} as const
|
||||
|
||||
export type SheetSnapshotRef = SheetRef & {
|
||||
schemaVersion: number
|
||||
speciesId: string
|
||||
}
|
||||
|
||||
export interface SheetSnapshotAsset {
|
||||
svgAssetId: string
|
||||
/** Content address from the seed manifest; a provenance pointer, not a tamper check. */
|
||||
sha256: string | null
|
||||
svg: string
|
||||
}
|
||||
|
||||
export interface SheetSnapshot {
|
||||
status: 'draft' | 'published'
|
||||
ref: SheetSnapshotRef
|
||||
/** Lean, valid document (schema v2, strict). */
|
||||
document: AnatomicalSheetDocument
|
||||
assets: SheetSnapshotAsset[]
|
||||
}
|
||||
|
||||
export const SheetSnapshotRefSchema: z.ZodType<SheetSnapshotRef> =
|
||||
SheetRefSchema.extend({
|
||||
schemaVersion: z.number().int().positive(),
|
||||
speciesId: z.string().min(1),
|
||||
}).strict()
|
||||
|
||||
const SheetSnapshotAssetSchema = z
|
||||
.object({
|
||||
svgAssetId: z.string().uuid(),
|
||||
sha256: z.string().regex(SHA256_PATTERN).nullable(),
|
||||
svg: z.string().max(SNAPSHOT_CAPS.assetBytes),
|
||||
})
|
||||
.strict()
|
||||
|
||||
/** Shape tier only: caps beyond the schema and integrity live in assertSnapshot. */
|
||||
export const SheetSnapshotSchema: z.ZodType<
|
||||
SheetSnapshot,
|
||||
z.ZodTypeDef,
|
||||
unknown
|
||||
> = z
|
||||
.object({
|
||||
status: z.enum(['draft', 'published']),
|
||||
ref: SheetSnapshotRefSchema,
|
||||
document: AnatomicalSheetDocumentSchema,
|
||||
assets: z.array(SheetSnapshotAssetSchema).max(SNAPSHOT_CAPS.assets),
|
||||
})
|
||||
.strict()
|
||||
|
||||
/** What a loaded sheet provides to build a snapshot from. */
|
||||
export interface SnapshotSource {
|
||||
status: 'draft' | 'published'
|
||||
ref: SheetRef
|
||||
speciesId: string
|
||||
schemaVersion: number
|
||||
document: AnatomicalSheetDocument
|
||||
/** SVG text by `svg_asset_id`. */
|
||||
assets: Readonly<Record<string, string>>
|
||||
/** sha256 by `svg_asset_id` (seed manifest); absent → null in the snapshot. */
|
||||
assetHashes?: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
export type SnapshotRejection =
|
||||
| 'unsupported_envelope'
|
||||
| 'schema'
|
||||
| 'caps'
|
||||
| 'integrity'
|
||||
| 'sheet_mismatch'
|
||||
|
||||
/** Thrown by assertSnapshot; `reason` is what the import reports. */
|
||||
export class SnapshotError extends Error {
|
||||
constructor(
|
||||
public readonly reason: SnapshotRejection,
|
||||
detail: string,
|
||||
) {
|
||||
super(`snapshot rejected (${reason}): ${detail}`)
|
||||
this.name = 'SnapshotError'
|
||||
}
|
||||
}
|
||||
|
||||
/** Own-key lookup: ids come from documents (`__proto__` is not an entry). */
|
||||
function own<T>(
|
||||
record: Readonly<Record<string, T>>,
|
||||
key: string,
|
||||
): T | undefined {
|
||||
return Object.hasOwn(record, key) ? record[key] : undefined
|
||||
}
|
||||
|
||||
/** The asset a view draws: its own, else the first one up its parent chain. */
|
||||
function assetOfView(
|
||||
view: SheetView,
|
||||
views: ReadonlyMap<string, SheetView>,
|
||||
): string | null {
|
||||
const visited = new Set<string>()
|
||||
let current: SheetView | undefined = view
|
||||
while (current && !visited.has(current.id)) {
|
||||
if (current.svg_asset_id !== null) return current.svg_asset_id
|
||||
visited.add(current.id)
|
||||
current =
|
||||
current.kind === 'detail' ? views.get(current.parent_view_id) : undefined
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Asset ids reachable from the views, in view order, each once. */
|
||||
function reachableAssetIds(document: AnatomicalSheetDocument): string[] {
|
||||
const views = new Map(document.views.map((v) => [v.id, v]))
|
||||
const ids: string[] = []
|
||||
for (const view of document.views) {
|
||||
const id = assetOfView(view, views)
|
||||
if (id !== null && !ids.includes(id)) ids.push(id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Build
|
||||
|
||||
/** Finding paths of the report grouped by zone, resolved and unresolved alike. */
|
||||
function pathsByZone(report: Report): Map<string, string[][]> {
|
||||
const byZone = new Map<string, string[][]>()
|
||||
for (const observation of report.observations) {
|
||||
for (const finding of observation.findings) {
|
||||
const paths = byZone.get(finding.findingZoneId) ?? []
|
||||
paths.push(finding.path)
|
||||
byZone.set(finding.findingZoneId, paths)
|
||||
}
|
||||
}
|
||||
return byZone
|
||||
}
|
||||
|
||||
/** Keeps, in document order, the nodes at `depth` of some path and their used descendants. */
|
||||
function pruneNodes(
|
||||
nodes: readonly FindingNode[],
|
||||
paths: readonly string[][],
|
||||
depth: number,
|
||||
): FindingNode[] {
|
||||
return nodes
|
||||
.filter((node) => paths.some((path) => path[depth] === node.id))
|
||||
.map((node) => ({
|
||||
id: node.id,
|
||||
name: { ...node.name },
|
||||
description: {},
|
||||
requires_vet_referral: node.requires_vet_referral,
|
||||
reference_ids: [],
|
||||
review_status: node.review_status,
|
||||
children: pruneNodes(
|
||||
node.children,
|
||||
paths.filter((path) => path[depth] === node.id),
|
||||
depth + 1,
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
function pruneCategories(
|
||||
categories: readonly FindingCategory[],
|
||||
paths: readonly string[][],
|
||||
): FindingCategory[] {
|
||||
return categories
|
||||
.filter((category) => paths.some((path) => path[0] === category.id))
|
||||
.map((category) => ({
|
||||
id: category.id,
|
||||
kind: category.kind,
|
||||
name: { ...category.name },
|
||||
description: {},
|
||||
reference_ids: [],
|
||||
review_status: category.review_status,
|
||||
children: pruneNodes(
|
||||
category.children,
|
||||
paths.filter((path) => path[0] === category.id),
|
||||
1,
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
function pruneZone(zone: FindingZone, paths: readonly string[][]): FindingZone {
|
||||
return {
|
||||
id: zone.id,
|
||||
name: { ...zone.name },
|
||||
categories: pruneCategories(zone.categories, paths),
|
||||
}
|
||||
}
|
||||
|
||||
function leanDocument(
|
||||
document: AnatomicalSheetDocument,
|
||||
report: Report,
|
||||
): AnatomicalSheetDocument {
|
||||
const used = pathsByZone(report)
|
||||
return {
|
||||
schema_version: document.schema_version,
|
||||
species_id: document.species_id,
|
||||
name: structuredClone(document.name),
|
||||
description: structuredClone(document.description),
|
||||
scope_disclaimer: structuredClone(document.scope_disclaimer),
|
||||
attribution: structuredClone(document.attribution),
|
||||
vertebral_config: structuredClone(document.vertebral_config),
|
||||
references: [],
|
||||
categories: structuredClone(document.categories),
|
||||
views: structuredClone(document.views),
|
||||
annotations: structuredClone(document.annotations),
|
||||
finding_zones: document.finding_zones.map((zone) =>
|
||||
pruneZone(zone, used.get(zone.id) ?? []),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotAssets(sheet: SnapshotSource): SheetSnapshotAsset[] {
|
||||
const assets: SheetSnapshotAsset[] = []
|
||||
for (const svgAssetId of reachableAssetIds(sheet.document)) {
|
||||
const svg = own(sheet.assets, svgAssetId)
|
||||
if (svg === undefined) continue
|
||||
const sha256 = sheet.assetHashes
|
||||
? (own(sheet.assetHashes, svgAssetId) ?? null)
|
||||
: null
|
||||
assets.push({ svgAssetId, sha256, svg })
|
||||
}
|
||||
return assets
|
||||
}
|
||||
|
||||
/**
|
||||
* The snapshot of `sheet` a given report needs: pure, deterministic
|
||||
* (document order everywhere), inputs untouched. Finding trees keep only the
|
||||
* categories and nodes on a path some finding of the report names, as far as
|
||||
* those nodes exist; a missing asset is left out and caught by assertSnapshot.
|
||||
*/
|
||||
export function buildSheetSnapshot(
|
||||
sheet: SnapshotSource,
|
||||
report: Report,
|
||||
): SheetSnapshot {
|
||||
return {
|
||||
status: sheet.status,
|
||||
ref: {
|
||||
sheetId: sheet.ref.sheetId,
|
||||
versionId: sheet.ref.versionId,
|
||||
documentSha256: sheet.ref.documentSha256,
|
||||
schemaVersion: sheet.schemaVersion,
|
||||
speciesId: sheet.speciesId,
|
||||
},
|
||||
document: leanDocument(sheet.document, report),
|
||||
assets: snapshotAssets(sheet),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Assert
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function childrenOf(node: unknown): unknown[] {
|
||||
if (!isRecord(node)) return []
|
||||
const children = node.children
|
||||
return Array.isArray(children) ? children : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Depth of the finding trees, checked on the raw input before Zod recurses
|
||||
* into it (an attacker-sized tree must not drive the parser). Iterative:
|
||||
* an explicit stack of (node, depth) pairs, categories at depth 1.
|
||||
*/
|
||||
function assertFindingDepth(input: unknown): void {
|
||||
if (!isRecord(input) || !isRecord(input.document)) return
|
||||
const zones = input.document.finding_zones
|
||||
if (!Array.isArray(zones)) return
|
||||
const stack: Array<[unknown, number]> = []
|
||||
for (const zone of zones) {
|
||||
if (!isRecord(zone) || !Array.isArray(zone.categories)) continue
|
||||
for (const category of zone.categories) stack.push([category, 1])
|
||||
}
|
||||
while (stack.length > 0) {
|
||||
const [node, depth] = stack.pop()!
|
||||
if (depth > SNAPSHOT_CAPS.findingDepth) {
|
||||
throw new SnapshotError(
|
||||
'caps',
|
||||
`finding depth over ${SNAPSHOT_CAPS.findingDepth}`,
|
||||
)
|
||||
}
|
||||
for (const child of childrenOf(node)) stack.push([child, depth + 1])
|
||||
}
|
||||
}
|
||||
|
||||
function countFindingNodes(document: AnatomicalSheetDocument): number {
|
||||
let count = 0
|
||||
const stack: Array<FindingCategory | FindingNode> =
|
||||
document.finding_zones.flatMap((zone) => zone.categories)
|
||||
while (stack.length > 0) {
|
||||
count += 1
|
||||
stack.push(...stack.pop()!.children)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* Longest `name` label (`fr` or `en`) anywhere in the document: sheet, views,
|
||||
* annotations, categories, regions, finding zones and nodes. Free texts
|
||||
* (`description`, `scope_disclaimer`) are not labels and carry no cap here.
|
||||
*/
|
||||
function longestName(document: AnatomicalSheetDocument): number {
|
||||
let longest = 0
|
||||
const stack: unknown[] = [document]
|
||||
while (stack.length > 0) {
|
||||
const value = stack.pop()
|
||||
if (Array.isArray(value)) stack.push(...value)
|
||||
if (!isRecord(value)) continue
|
||||
const name = value.name
|
||||
if (isRecord(name)) {
|
||||
for (const key of ['fr', 'en']) {
|
||||
const text = name[key]
|
||||
if (typeof text === 'string') longest = Math.max(longest, text.length)
|
||||
}
|
||||
}
|
||||
stack.push(...Object.values(value))
|
||||
}
|
||||
return longest
|
||||
}
|
||||
|
||||
function utf8Length(text: string): number {
|
||||
return new TextEncoder().encode(text).byteLength
|
||||
}
|
||||
|
||||
function assertCaps(snapshot: SheetSnapshot): void {
|
||||
const over = (what: string) => new SnapshotError('caps', `${what} over cap`)
|
||||
const { document, assets } = snapshot
|
||||
if (document.views.length > SNAPSHOT_CAPS.views) throw over('views')
|
||||
if (document.annotations.length > SNAPSHOT_CAPS.annotations) {
|
||||
throw over('annotations')
|
||||
}
|
||||
if (countFindingNodes(document) > SNAPSHOT_CAPS.findingNodes) {
|
||||
throw over('finding nodes')
|
||||
}
|
||||
if (longestName(document) > SNAPSHOT_CAPS.labelChars) throw over('label')
|
||||
if (assets.length > SNAPSHOT_CAPS.assets) throw over('assets')
|
||||
const sizes = assets.map((asset) => utf8Length(asset.svg))
|
||||
if (sizes.some((size) => size > SNAPSHOT_CAPS.assetBytes)) throw over('asset')
|
||||
const total = sizes.reduce((sum, size) => sum + size, 0)
|
||||
if (total > SNAPSHOT_CAPS.assetsTotalBytes) throw over('assets total')
|
||||
}
|
||||
|
||||
function assertIntegrity(snapshot: SheetSnapshot): void {
|
||||
const errors = validateSheetDocument(snapshot.document).filter(
|
||||
(issue) => issue.severity === 'error',
|
||||
)
|
||||
if (errors.length > 0) {
|
||||
throw new SnapshotError('integrity', errors[0]!.code)
|
||||
}
|
||||
const present = new Set(snapshot.assets.map((asset) => asset.svgAssetId))
|
||||
const views = new Map(snapshot.document.views.map((v) => [v.id, v]))
|
||||
for (const view of snapshot.document.views) {
|
||||
const assetId = assetOfView(view, views)
|
||||
if (assetId === null || !present.has(assetId)) {
|
||||
throw new SnapshotError('integrity', `view "${view.id}" reaches no asset`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The single gate of an imported snapshot, in this order: finding depth on
|
||||
* the raw input → shape (`schema`) → caps (§15) → sheet integrity rules and
|
||||
* every view reaching an asset carried by the snapshot (`integrity`).
|
||||
* Returns the parsed snapshot; throws SnapshotError with the reason.
|
||||
*/
|
||||
export function assertSnapshot(snapshot: unknown): SheetSnapshot {
|
||||
assertFindingDepth(snapshot)
|
||||
const parsed = SheetSnapshotSchema.safeParse(snapshot)
|
||||
if (!parsed.success) {
|
||||
throw new SnapshotError(
|
||||
'schema',
|
||||
parsed.error.issues[0]?.message ?? 'invalid',
|
||||
)
|
||||
}
|
||||
assertCaps(parsed.data)
|
||||
assertIntegrity(parsed.data)
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
/** Adapter: a snapshot as the sheet index reads it (assets array → record). */
|
||||
export function snapshotIndexSource(
|
||||
snapshot: SheetSnapshot,
|
||||
): SheetIndexSource & { ref: SheetSnapshotRef } {
|
||||
return {
|
||||
ref: snapshot.ref,
|
||||
document: snapshot.document,
|
||||
assets: Object.fromEntries(
|
||||
snapshot.assets.map((asset) => [asset.svgAssetId, asset.svg]),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export * from './anatomical-sheet'
|
||||
export * from './report'
|
||||
export * from './archive'
|
||||
@@ -1,37 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Identity snapshots carried by every report version: who wrote it, on
|
||||
* which animal, for which owner. Copied into the report at creation so a
|
||||
* report stays readable when the underlying records change (BDR-010).
|
||||
*/
|
||||
|
||||
export const PractitionerSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
cabinet: z.string().optional(),
|
||||
contact: z.string().optional(),
|
||||
/** SIRET, 14-digit French business identifier (not validated). */
|
||||
siret: z.string().optional(),
|
||||
})
|
||||
export type Practitioner = z.infer<typeof PractitionerSchema>
|
||||
|
||||
export const AnimalSchema = z.object({
|
||||
/** Species of the animal; the sheet the report references matches it. */
|
||||
speciesId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
breed: z.string().optional(),
|
||||
age: z.string().optional(),
|
||||
})
|
||||
export type Animal = z.infer<typeof AnimalSchema>
|
||||
|
||||
export const OwnerSchema = z.object({ name: z.string().min(1) })
|
||||
export type Owner = z.infer<typeof OwnerSchema>
|
||||
|
||||
export const NextAppointmentSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('date'), date: z.string() }),
|
||||
z.object({ kind: z.literal('period'), text: z.string() }),
|
||||
])
|
||||
export type NextAppointment = z.infer<typeof NextAppointmentSchema>
|
||||
|
||||
export const LateralSideSchema = z.enum(['left', 'right'])
|
||||
export type LateralSide = z.infer<typeof LateralSideSchema>
|
||||
@@ -1,32 +0,0 @@
|
||||
export * from './identity'
|
||||
export * from './v3'
|
||||
export {
|
||||
FindingV2Schema,
|
||||
ObservationV2Schema,
|
||||
ObservationZoneV2Schema,
|
||||
ReportV2Schema,
|
||||
SeverityV2Schema,
|
||||
VertebraV2Schema,
|
||||
VertebralRegionV2Schema,
|
||||
type FindingV2,
|
||||
type ObservationV2,
|
||||
type ObservationZoneV2,
|
||||
type ReportV2,
|
||||
type SeverityV2,
|
||||
} from './v2'
|
||||
export {
|
||||
ReportMigrationMapSchema,
|
||||
findingPathKey,
|
||||
type ReportMigrationMap,
|
||||
} from './migration-map'
|
||||
export {
|
||||
migrateReportV2ToV3,
|
||||
readReportDocument,
|
||||
UnsupportedReportVersionError,
|
||||
type MigrationOutcome,
|
||||
} from './migrate'
|
||||
export {
|
||||
rebaseReportOnSheet,
|
||||
type RebaseIndex,
|
||||
type RebaseOutcome,
|
||||
} from './rebase'
|
||||
@@ -1,167 +0,0 @@
|
||||
import { findingPathKey, type ReportMigrationMap } from './migration-map'
|
||||
import {
|
||||
ReportV2Schema,
|
||||
type FindingV2,
|
||||
type ObservationV2,
|
||||
type ObservationZoneV2,
|
||||
type ReportV2,
|
||||
type SeverityV2,
|
||||
} from './v2'
|
||||
import {
|
||||
REPORT_VERSION,
|
||||
ReportSchema,
|
||||
type Finding,
|
||||
type Observation,
|
||||
type Report,
|
||||
type ReportZone,
|
||||
type Severity,
|
||||
} from './v3'
|
||||
|
||||
/**
|
||||
* Lifts a Report v2 (PDF attachment or sessionStorage draft of the deployed
|
||||
* application) to v3 against the migration map of the reference sheet.
|
||||
* Never throws on content: a zone or finding the map cannot place is kept
|
||||
* verbatim with its snapshots and flagged `unresolved`, so the practitioner's
|
||||
* data survives any catalog change and stays identifiable.
|
||||
*/
|
||||
|
||||
/** Own-key lookup: ids come from untrusted documents (`__proto__` is not an entry). */
|
||||
function own<T>(record: Record<string, T>, key: string): T | undefined {
|
||||
return Object.hasOwn(record, key) ? record[key] : undefined
|
||||
}
|
||||
|
||||
const SEVERITY: Record<SeverityV2, Severity> = {
|
||||
légère: 'mild',
|
||||
modérée: 'moderate',
|
||||
sévère: 'severe',
|
||||
}
|
||||
|
||||
export interface MigrationOutcome {
|
||||
report: Report
|
||||
/** Zones whose legacy id has no annotation in the map. */
|
||||
unresolvedZones: number
|
||||
/** Findings whose legacy path no longer exists in the sheet. */
|
||||
unresolvedFindings: number
|
||||
}
|
||||
|
||||
function migrateZone(
|
||||
zone: ObservationZoneV2,
|
||||
map: ReportMigrationMap,
|
||||
): ReportZone {
|
||||
const entry = own(map.annotations, zone.boneId)
|
||||
const viewId = zone.detailSourceId
|
||||
? (own(map.views, zone.detailSourceId) ?? zone.detailSourceId)
|
||||
: map.main_view_id
|
||||
const out: ReportZone = { annotationId: entry?.id ?? zone.boneId, viewId }
|
||||
if (zone.side) out.side = zone.side
|
||||
if (zone.vertebrae) out.vertebrae = zone.vertebrae.map((v) => ({ ...v }))
|
||||
if (entry) {
|
||||
out.labelFrSnapshot = entry.name.fr
|
||||
out.labelEnSnapshot = entry.name.en
|
||||
} else {
|
||||
out.unresolved = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function migrateFinding(finding: FindingV2, map: ReportMigrationMap): Finding {
|
||||
const mapped = own(
|
||||
map.finding_paths,
|
||||
findingPathKey(finding.zoneId, finding.path),
|
||||
)
|
||||
const out: Finding = {
|
||||
findingZoneId: finding.zoneId,
|
||||
path: [...finding.path],
|
||||
labelFrSnapshot: finding.labelFrSnapshot,
|
||||
labelEnSnapshot: finding.labelEnSnapshot,
|
||||
}
|
||||
if (finding.requiresVetReferral) out.requiresVetReferral = true
|
||||
if (finding.side) out.side = finding.side
|
||||
if (typeof mapped === 'string') {
|
||||
const [zoneId, ...path] = mapped.split('/')
|
||||
out.findingZoneId = zoneId!
|
||||
out.path = path
|
||||
} else {
|
||||
// null = removed by curation; undefined = never part of the legacy catalog.
|
||||
out.unresolved = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function migrateObservation(
|
||||
obs: ObservationV2,
|
||||
map: ReportMigrationMap,
|
||||
): Observation {
|
||||
const out: Observation = {
|
||||
id: obs.id,
|
||||
zones: obs.zones.map((z) => migrateZone(z, map)),
|
||||
findings: obs.findings.map((f) => migrateFinding(f, map)),
|
||||
freeTextFindings: [...obs.freeTextFindings],
|
||||
comment: obs.comment,
|
||||
}
|
||||
if (obs.severity) out.severity = SEVERITY[obs.severity]
|
||||
return out
|
||||
}
|
||||
|
||||
export function migrateReportV2ToV3(
|
||||
report: ReportV2,
|
||||
map: ReportMigrationMap,
|
||||
): MigrationOutcome {
|
||||
const observations = report.observations.map((o) =>
|
||||
migrateObservation(o, map),
|
||||
)
|
||||
const migrated: Report = {
|
||||
version: REPORT_VERSION,
|
||||
id: report.id,
|
||||
createdAt: report.createdAt,
|
||||
date: report.date,
|
||||
practitioner: report.practitioner,
|
||||
animal: report.animal,
|
||||
owner: report.owner,
|
||||
sheet: { ...map.sheet },
|
||||
observations,
|
||||
conclusion: report.conclusion,
|
||||
recommendations: report.recommendations,
|
||||
localAnnotations: [],
|
||||
}
|
||||
if (report.nextAppointment) migrated.nextAppointment = report.nextAppointment
|
||||
const zones = observations.flatMap((o) => o.zones)
|
||||
const findings = observations.flatMap((o) => o.findings)
|
||||
return {
|
||||
report: ReportSchema.parse(migrated),
|
||||
unresolvedZones: zones.filter((z) => z.unresolved).length,
|
||||
unresolvedFindings: findings.filter((f) => f.unresolved).length,
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown for a report whose version this code cannot read. */
|
||||
export class UnsupportedReportVersionError extends Error {
|
||||
constructor(public readonly foundVersion: number | null) {
|
||||
super(`unsupported report version: ${foundVersion ?? 'unknown'}`)
|
||||
this.name = 'UnsupportedReportVersionError'
|
||||
}
|
||||
}
|
||||
|
||||
function versionOf(data: unknown): number | null {
|
||||
if (data === null || typeof data !== 'object') return null
|
||||
const v = (data as { version?: unknown }).version
|
||||
return typeof v === 'number' ? v : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a report document of any supported version (2 or 3) and returns it
|
||||
* as v3. Zod errors propagate: a document of a known version that does not
|
||||
* parse is corrupt, not old.
|
||||
*/
|
||||
export function readReportDocument(
|
||||
data: unknown,
|
||||
map: ReportMigrationMap,
|
||||
): MigrationOutcome {
|
||||
const version = versionOf(data)
|
||||
if (version === REPORT_VERSION) {
|
||||
const report = ReportSchema.parse(data)
|
||||
return { report, unresolvedZones: 0, unresolvedFindings: 0 }
|
||||
}
|
||||
if (version === 2) return migrateReportV2ToV3(ReportV2Schema.parse(data), map)
|
||||
throw new UnsupportedReportVersionError(version)
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import { SheetRefSchema } from './v3'
|
||||
|
||||
/**
|
||||
* Correspondence between the legacy identifiers a Report v2 carries and the
|
||||
* canonical sheet a Report v3 references. Generated by the curation pipeline
|
||||
* (`draft/report-migration-map.json`), never written by hand: annotations
|
||||
* come from the legacy id map, finding paths from the applier's rename and
|
||||
* removal records. A `null` finding path means "removed from the sheet":
|
||||
* the migration keeps the finding with its snapshots and flags it.
|
||||
*/
|
||||
|
||||
const LocalizedNameSchema = z.object({ fr: z.string(), en: z.string() })
|
||||
|
||||
export const ReportMigrationMapSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
sheet: SheetRefSchema,
|
||||
/** Id of the view a v2 zone without `detailSourceId` belongs to. */
|
||||
main_view_id: z.string().min(1),
|
||||
/** Legacy detail popup key → view id. */
|
||||
views: z.record(z.string(), z.string().min(1)),
|
||||
/** Legacy `data-anno-id` → annotation id and the legacy labels. */
|
||||
annotations: z.record(
|
||||
z.string(),
|
||||
z.object({ id: z.string().min(1), name: LocalizedNameSchema }),
|
||||
),
|
||||
/**
|
||||
* `<zoneId>/<path segments joined by '/'>` of every legacy finding node →
|
||||
* the same key in the sheet, or null when the node was removed.
|
||||
*/
|
||||
finding_paths: z.record(z.string(), z.string().nullable()),
|
||||
})
|
||||
export type ReportMigrationMap = z.infer<typeof ReportMigrationMapSchema>
|
||||
|
||||
export function findingPathKey(
|
||||
zoneId: string,
|
||||
path: readonly string[],
|
||||
): string {
|
||||
return `${zoneId}/${path.join('/')}`
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import type {
|
||||
SheetIndex,
|
||||
SheetIndexSource,
|
||||
} from '../anatomical-sheet/sheet-index'
|
||||
import type { Annotation, LocalizedText } from '../anatomical-sheet/schema'
|
||||
import type { SheetSnapshot } from '../archive/snapshot'
|
||||
import {
|
||||
ReportSchema,
|
||||
type Finding,
|
||||
type Observation,
|
||||
type Report,
|
||||
type ReportZone,
|
||||
type SheetRef,
|
||||
} from './v3'
|
||||
|
||||
/**
|
||||
* Moves an imported report onto the sheet the application has loaded
|
||||
* (STEP6 §3.5). A report written on another revision of the sheet keeps
|
||||
* every datum: a zone or finding the loaded sheet no longer holds is flagged
|
||||
* `unresolved`, its labels taken from the archived snapshot when the report
|
||||
* carries none, and the report now references the loaded sheet. Nothing
|
||||
* happens when the report already sits on the loaded sheet.
|
||||
*/
|
||||
|
||||
/** An index whose source names its sheet (a loaded sheet or a snapshot). */
|
||||
export type RebaseIndex = SheetIndex<SheetIndexSource & { ref: SheetRef }>
|
||||
|
||||
export interface RebaseOutcome {
|
||||
report: Report
|
||||
/** Zones and findings newly flagged by this rebase. */
|
||||
unresolvedZones: number
|
||||
unresolvedFindings: number
|
||||
rebased: boolean
|
||||
}
|
||||
|
||||
interface Counters {
|
||||
zones: number
|
||||
findings: number
|
||||
}
|
||||
|
||||
/** The name the archived snapshot gives an annotation (a trigger: its view's). */
|
||||
function archivedName(
|
||||
archived: SheetSnapshot | null,
|
||||
annotationId: string,
|
||||
): LocalizedText | undefined {
|
||||
if (!archived) return undefined
|
||||
const annotation: Annotation | undefined = archived.document.annotations.find(
|
||||
(a) => a.id === annotationId,
|
||||
)
|
||||
if (!annotation) return undefined
|
||||
if (annotation.kind !== 'detail_trigger') return annotation.name
|
||||
const view = archived.document.views.find(
|
||||
(v) => v.id === annotation.opens_view_id,
|
||||
)
|
||||
return annotation.name ?? view?.name
|
||||
}
|
||||
|
||||
function flagZone(
|
||||
zone: ReportZone,
|
||||
archived: SheetSnapshot | null,
|
||||
): ReportZone {
|
||||
const out: ReportZone = { ...zone, unresolved: true }
|
||||
const name = archivedName(archived, zone.annotationId)
|
||||
if (name) {
|
||||
out.labelFrSnapshot ??= name.fr
|
||||
out.labelEnSnapshot ??= name.en
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function rebaseZone(
|
||||
zone: ReportZone,
|
||||
index: RebaseIndex,
|
||||
archived: SheetSnapshot | null,
|
||||
counters: Counters,
|
||||
): ReportZone {
|
||||
if (zone.unresolved) return { ...zone }
|
||||
const known =
|
||||
index.annotation(zone.annotationId) !== undefined &&
|
||||
index.view(zone.viewId) !== undefined
|
||||
if (known) return { ...zone }
|
||||
counters.zones += 1
|
||||
return flagZone(zone, archived)
|
||||
}
|
||||
|
||||
function rebaseFinding(
|
||||
finding: Finding,
|
||||
index: RebaseIndex,
|
||||
counters: Counters,
|
||||
): Finding {
|
||||
if (finding.unresolved) return { ...finding }
|
||||
if (index.nodeAt(finding.findingZoneId, finding.path)) return { ...finding }
|
||||
counters.findings += 1
|
||||
return { ...finding, unresolved: true }
|
||||
}
|
||||
|
||||
function rebaseObservation(
|
||||
observation: Observation,
|
||||
index: RebaseIndex,
|
||||
archived: SheetSnapshot | null,
|
||||
counters: Counters,
|
||||
): Observation {
|
||||
return {
|
||||
...observation,
|
||||
zones: observation.zones.map((z) =>
|
||||
rebaseZone(z, index, archived, counters),
|
||||
),
|
||||
findings: observation.findings.map((f) =>
|
||||
rebaseFinding(f, index, counters),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export function rebaseReportOnSheet(
|
||||
report: Report,
|
||||
index: RebaseIndex,
|
||||
archived: SheetSnapshot | null,
|
||||
): RebaseOutcome {
|
||||
if (report.sheet.documentSha256 === index.sheet.ref.documentSha256) {
|
||||
return { report, unresolvedZones: 0, unresolvedFindings: 0, rebased: false }
|
||||
}
|
||||
const counters: Counters = { zones: 0, findings: 0 }
|
||||
const { sheetId, versionId, documentSha256 } = index.sheet.ref
|
||||
const rebased: Report = {
|
||||
...report,
|
||||
sheet: { sheetId, versionId, documentSha256 },
|
||||
observations: report.observations.map((o) =>
|
||||
rebaseObservation(o, index, archived, counters),
|
||||
),
|
||||
}
|
||||
return {
|
||||
report: ReportSchema.parse(rebased),
|
||||
unresolvedZones: counters.zones,
|
||||
unresolvedFindings: counters.findings,
|
||||
rebased: true,
|
||||
}
|
||||
}
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user