test(tests): R2 freeze — archive envelopes of the three golden reports and the frozen N-1 reader
Envelopes exported by the TypeScript domain before the Rust switch (FR, no
logos, fixed export time) are the semantic oracle of the switch (D-R11:
key order may change, values may not). The shipped Zod schemas are copied
verbatim under packages/core-wasm/tests/n-1 (develop 1a7ee7d) so a rollback
reader stays testable after packages/domain is deleted at R5.
This commit is contained in:
1 parent
1a7ee7d9ac
commit
3114d67959
29 files changed
+8581
-46
No files matched your search
@@ -16,6 +16,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@faunosteo/anatomy": "workspace:*",
|
"@faunosteo/anatomy": "workspace:*",
|
||||||
|
"@faunosteo/core-wasm": "workspace:*",
|
||||||
"@faunosteo/domain": "workspace:*",
|
"@faunosteo/domain": "workspace:*",
|
||||||
"@faunosteo/pdf": "workspace:*",
|
"@faunosteo/pdf": "workspace:*",
|
||||||
"@faunosteo/supabase": "workspace:*",
|
"@faunosteo/supabase": "workspace:*",
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { resolve } from 'node:path'
|
||||||
|
import {
|
||||||
|
readReportDocument,
|
||||||
|
ReportSchema,
|
||||||
|
type Report,
|
||||||
|
} from '@faunosteo/domain'
|
||||||
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
|
import { FIXTURES_DIR } from './goldens'
|
||||||
|
import {
|
||||||
|
leavesAsV2Report,
|
||||||
|
legacyLeaves,
|
||||||
|
loadLegacyBaseline,
|
||||||
|
} from './legacyLeaves'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The three reports the Step 6 goldens and the R2 envelope freeze are drawn
|
||||||
|
* from: the Step 5 v2 archive fixture migrated, the v3 demo report, and a v2
|
||||||
|
* report whose sphenoid and ssb findings the migration cannot place.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const GOLDEN_REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
|
||||||
|
export type GoldenReportName = (typeof GOLDEN_REPORTS)[number]
|
||||||
|
|
||||||
|
export interface GoldenReports {
|
||||||
|
reports: Record<GoldenReportName, Report>
|
||||||
|
/** Findings the migration flagged in `v2unresolved`. */
|
||||||
|
unresolvedOfV2Unresolved: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const readJson = (name: string): unknown =>
|
||||||
|
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
|
||||||
|
|
||||||
|
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
|
||||||
|
function buildV2Unresolved(sheet: SheetIndex) {
|
||||||
|
const leaves = legacyLeaves(loadLegacyBaseline())
|
||||||
|
const unresolvedFamilies = leaves.filter(
|
||||||
|
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
|
||||||
|
)
|
||||||
|
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
|
||||||
|
return readReportDocument(
|
||||||
|
leavesAsV2Report([...unresolvedFamilies, resolved]),
|
||||||
|
sheet.sheet.migrationMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildGoldenReports(sheet: SheetIndex): GoldenReports {
|
||||||
|
const v2unresolved = buildV2Unresolved(sheet)
|
||||||
|
return {
|
||||||
|
reports: {
|
||||||
|
v2full: readReportDocument(
|
||||||
|
readJson('report-v2.full.json'),
|
||||||
|
sheet.sheet.migrationMap,
|
||||||
|
).report,
|
||||||
|
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
|
||||||
|
v2unresolved: v2unresolved.report,
|
||||||
|
},
|
||||||
|
unresolvedOfV2Unresolved: v2unresolved.unresolvedFindings,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* R2 freeze (RUST_ARCHITECTURE_REVIEW VI.1, VI.2 R2): the archive envelope
|
||||||
|
* (PDF attachment) of the three golden reports, exported by the application
|
||||||
|
* path with fixed inputs (FR, every logo slot empty, 1×1 raster, fixed
|
||||||
|
* export time), committed as the TypeScript domain wrote it before the
|
||||||
|
* switch to the Rust core. Whatever writes the attachment afterwards, it
|
||||||
|
* must parse with the frozen N-1 reader and be deep-equal to the frozen
|
||||||
|
* envelope; only the key order may differ (D-R11). `MAKE_R2_FREEZE=1`
|
||||||
|
* writes the files: never once the switch has landed without an owner
|
||||||
|
* decision.
|
||||||
|
*/
|
||||||
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
|
import { resolve } from 'node:path'
|
||||||
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { readAttachmentBytes } from '@faunosteo/pdf'
|
||||||
|
import {
|
||||||
|
readArchiveDocument,
|
||||||
|
ReportArchiveEnvelopeSchema,
|
||||||
|
} from '@faunosteo/core-wasm/n-1'
|
||||||
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
|
import { loadTestSheet } from '../helpers/sheet'
|
||||||
|
import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens'
|
||||||
|
import {
|
||||||
|
buildGoldenReports,
|
||||||
|
GOLDEN_REPORTS,
|
||||||
|
type GoldenReports,
|
||||||
|
} from '../helpers/goldenReports'
|
||||||
|
|
||||||
|
vi.mock('@/pdf/browserRasterizer', () => ({
|
||||||
|
browserRasterizer: vi.fn(async () => ONE_PX_PNG),
|
||||||
|
}))
|
||||||
|
vi.mock('@/pdf/branding', async () => {
|
||||||
|
const { brandingOf } = await import('../helpers/goldens')
|
||||||
|
return { loadBranding: vi.fn(() => brandingOf('nologos')) }
|
||||||
|
})
|
||||||
|
|
||||||
|
const FREEZE_DIR = resolve(FIXTURES_DIR, 'goldens/r2')
|
||||||
|
const MAKE_FREEZE = process.env.MAKE_R2_FREEZE === '1'
|
||||||
|
const EXPORTED_AT = new Date('2026-10-13T09:00:00.000Z')
|
||||||
|
|
||||||
|
let sheet: SheetIndex
|
||||||
|
let golden: GoldenReports
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
sheet = await loadTestSheet()
|
||||||
|
golden = buildGoldenReports(sheet)
|
||||||
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
|
vi.useFakeTimers({ toFake: ['Date'] })
|
||||||
|
vi.setSystemTime(EXPORTED_AT)
|
||||||
|
})
|
||||||
|
afterAll(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function exportedAttachment(
|
||||||
|
name: (typeof GOLDEN_REPORTS)[number],
|
||||||
|
): Promise<string> {
|
||||||
|
const { pdf } = await exportReportToPdf(golden.reports[name], sheet, {
|
||||||
|
locale: 'fr',
|
||||||
|
})
|
||||||
|
return new TextDecoder().decode(await readAttachmentBytes(pdf))
|
||||||
|
}
|
||||||
|
|
||||||
|
describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
|
||||||
|
const file = resolve(FREEZE_DIR, `envelope.${name}.fr.nologos.json`)
|
||||||
|
|
||||||
|
it('matches the frozen envelope and the N-1 reader accepts it', async () => {
|
||||||
|
const text = await exportedAttachment(name)
|
||||||
|
if (MAKE_FREEZE) {
|
||||||
|
mkdirSync(FREEZE_DIR, { recursive: true })
|
||||||
|
writeFileSync(file, text)
|
||||||
|
}
|
||||||
|
const data: unknown = JSON.parse(text)
|
||||||
|
expect(data).toEqual(JSON.parse(readFileSync(file, 'utf8')))
|
||||||
|
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
|
||||||
|
const outcome = readArchiveDocument(data, sheet.sheet.migrationMap)
|
||||||
|
expect(outcome.origin).toBe('envelope_v1')
|
||||||
|
expect(outcome.archive).not.toBeNull()
|
||||||
|
expect(outcome.snapshotRejected).toBeUndefined()
|
||||||
|
}, 30_000)
|
||||||
|
})
|
||||||
@@ -12,22 +12,17 @@ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
|||||||
import { PDFDocument } from 'pdf-lib'
|
import { PDFDocument } from 'pdf-lib'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import { resolve } from 'node:path'
|
import { resolve } from 'node:path'
|
||||||
import {
|
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||||
buildSheetSnapshot,
|
|
||||||
readReportDocument,
|
|
||||||
ReportSchema,
|
|
||||||
type Report,
|
|
||||||
} from '@faunosteo/domain'
|
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
import { importReportFromPdf } from '@/pdf/import'
|
import { importReportFromPdf } from '@/pdf/import'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import type { Locale } from '@/i18n/types'
|
import type { Locale } from '@/i18n/types'
|
||||||
import { loadTestSheet } from '../helpers/sheet'
|
import { loadTestSheet } from '../helpers/sheet'
|
||||||
import {
|
import {
|
||||||
leavesAsV2Report,
|
buildGoldenReports,
|
||||||
legacyLeaves,
|
GOLDEN_REPORTS,
|
||||||
loadLegacyBaseline,
|
type GoldenReportName,
|
||||||
} from '../helpers/legacyLeaves'
|
} from '../helpers/goldenReports'
|
||||||
import {
|
import {
|
||||||
checkGolden,
|
checkGolden,
|
||||||
FIXTURES_DIR,
|
FIXTURES_DIR,
|
||||||
@@ -54,43 +49,17 @@ vi.mock('@/pdf/branding', async () => {
|
|||||||
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
|
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
|
||||||
})
|
})
|
||||||
|
|
||||||
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
|
const REPORTS = GOLDEN_REPORTS
|
||||||
type ReportName = (typeof REPORTS)[number]
|
|
||||||
const MODES: readonly LogoMode[] = ['nologos', 'logos']
|
const MODES: readonly LogoMode[] = ['nologos', 'logos']
|
||||||
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
|
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
|
||||||
|
|
||||||
const readJson = (name: string): unknown =>
|
|
||||||
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
|
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
let reports: Record<ReportName, Report>
|
let reports: Record<GoldenReportName, Report>
|
||||||
let unresolvedOfV2Unresolved = 0
|
let unresolvedOfV2Unresolved = 0
|
||||||
|
|
||||||
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
|
|
||||||
function buildV2Unresolved(): Report {
|
|
||||||
const leaves = legacyLeaves(loadLegacyBaseline())
|
|
||||||
const unresolvedFamilies = leaves.filter(
|
|
||||||
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
|
|
||||||
)
|
|
||||||
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
|
|
||||||
const outcome = readReportDocument(
|
|
||||||
leavesAsV2Report([...unresolvedFamilies, resolved]),
|
|
||||||
sheet.sheet.migrationMap,
|
|
||||||
)
|
|
||||||
unresolvedOfV2Unresolved = outcome.unresolvedFindings
|
|
||||||
return outcome.report
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
reports = {
|
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
|
||||||
v2full: readReportDocument(
|
|
||||||
readJson('report-v2.full.json'),
|
|
||||||
sheet.sheet.migrationMap,
|
|
||||||
).report,
|
|
||||||
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
|
|
||||||
v2unresolved: buildV2Unresolved(),
|
|
||||||
}
|
|
||||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
})
|
})
|
||||||
afterAll(() => vi.restoreAllMocks())
|
afterAll(() => vi.restoreAllMocks())
|
||||||
|
|||||||
@@ -2,12 +2,13 @@
|
|||||||
"name": "@faunosteo/core-wasm",
|
"name": "@faunosteo/core-wasm",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Faunosteo core compiled to WebAssembly: loader, generated TypeScript types of the contracts, and the R0 proofs (panic, serialisation, size)",
|
"description": "Faunosteo core compiled to WebAssembly: runtime loader, generated TypeScript types of the contracts, the frozen N-1 reader, and the R0 proofs (panic, serialisation, size)",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
"./types": "./types/index.ts"
|
"./types": "./types/index.ts",
|
||||||
|
"./n-1": "./tests/n-1/index.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
@@ -17,12 +18,14 @@
|
|||||||
"build": "tsc -p tsconfig.json --noEmit"
|
"build": "tsc -p tsconfig.json --noEmit"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@faunosteo/domain": "workspace:*",
|
|
||||||
"@types/node": "^20.19.41",
|
"@types/node": "^20.19.41",
|
||||||
"eslint": "^9.17.0",
|
"eslint": "^9.17.0",
|
||||||
"globals": "^15.14.0",
|
"globals": "^15.14.0",
|
||||||
"typescript": "^5.7.2",
|
"typescript": "^5.7.2",
|
||||||
"typescript-eslint": "^8.19.0",
|
"typescript-eslint": "^8.19.0",
|
||||||
"vitest": "^3.2.7"
|
"vitest": "^3.2.7"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"zod": "^3.24.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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: [],
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export * from './schema'
|
||||||
|
export * from './validate'
|
||||||
|
export * from './create'
|
||||||
|
export * from './sheet-index'
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
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>
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
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>
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
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 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export * from './snapshot'
|
||||||
|
export * from './branding'
|
||||||
|
export * from './labels'
|
||||||
|
export * from './envelope'
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
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]),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './anatomical-sheet'
|
||||||
|
export * from './report'
|
||||||
|
export * from './archive'
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
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>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
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'
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
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('/')}`
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
import {
|
||||||
|
AnimalSchema,
|
||||||
|
LateralSideSchema,
|
||||||
|
NextAppointmentSchema,
|
||||||
|
OwnerSchema,
|
||||||
|
PractitionerSchema,
|
||||||
|
} from './identity'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Report document version 2, exactly as the deployed application wrote it
|
||||||
|
* (PDF attachments of the practitioner's archive, sessionStorage drafts).
|
||||||
|
* Kept as an INPUT format only: nothing writes v2 any more, `migrate.ts`
|
||||||
|
* lifts it to v3. Field comments describe the legacy meaning.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const SeverityV2Schema = z.enum(['légère', 'modérée', 'sévère'])
|
||||||
|
export type SeverityV2 = z.infer<typeof SeverityV2Schema>
|
||||||
|
|
||||||
|
export const VertebralRegionV2Schema = z.enum(['C', 'T', 'L', 'S', 'Cd'])
|
||||||
|
|
||||||
|
export const VertebraV2Schema = z.object({
|
||||||
|
region: VertebralRegionV2Schema,
|
||||||
|
index: z.number().int().positive(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const ObservationZoneV2Schema = z.object({
|
||||||
|
/** The legacy SVG `data-anno-id` (e.g. `point-mpbwtst0`). */
|
||||||
|
boneId: z.string().min(1),
|
||||||
|
/** Legacy detail popup key (`head`) when the zone came from that view. */
|
||||||
|
detailSourceId: z.string().optional(),
|
||||||
|
vertebrae: z.array(VertebraV2Schema).optional(),
|
||||||
|
side: LateralSideSchema.optional(),
|
||||||
|
})
|
||||||
|
export type ObservationZoneV2 = z.infer<typeof ObservationZoneV2Schema>
|
||||||
|
|
||||||
|
export const FindingV2Schema = z.object({
|
||||||
|
/** Legacy catalog zone key (equal to the canonical finding zone id). */
|
||||||
|
zoneId: z.string().min(1),
|
||||||
|
/** Node ids from the zone's categories down to the leaf. */
|
||||||
|
path: z.array(z.string().min(1)).min(1),
|
||||||
|
labelFrSnapshot: z.string().min(1),
|
||||||
|
labelEnSnapshot: z.string().min(1),
|
||||||
|
requiresVetReferral: z.boolean().optional(),
|
||||||
|
side: LateralSideSchema.optional(),
|
||||||
|
})
|
||||||
|
export type FindingV2 = z.infer<typeof FindingV2Schema>
|
||||||
|
|
||||||
|
export const ObservationV2Schema = z.object({
|
||||||
|
id: z.string().min(1),
|
||||||
|
zones: z.array(ObservationZoneV2Schema),
|
||||||
|
findings: z.array(FindingV2Schema),
|
||||||
|
freeTextFindings: z.array(z.string()),
|
||||||
|
severity: SeverityV2Schema.optional(),
|
||||||
|
comment: z.string(),
|
||||||
|
})
|
||||||
|
export type ObservationV2 = z.infer<typeof ObservationV2Schema>
|
||||||
|
|
||||||
|
export const ReportV2Schema = z.object({
|
||||||
|
version: z.literal(2),
|
||||||
|
id: z.string().min(1),
|
||||||
|
createdAt: z.string(),
|
||||||
|
date: z.string(),
|
||||||
|
practitioner: PractitionerSchema,
|
||||||
|
animal: AnimalSchema,
|
||||||
|
owner: OwnerSchema,
|
||||||
|
observations: z.array(ObservationV2Schema),
|
||||||
|
conclusion: z.string(),
|
||||||
|
recommendations: z.string(),
|
||||||
|
nextAppointment: NextAppointmentSchema.optional(),
|
||||||
|
})
|
||||||
|
export type ReportV2 = z.infer<typeof ReportV2Schema>
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
import {
|
||||||
|
AnimalSchema,
|
||||||
|
LateralSideSchema,
|
||||||
|
NextAppointmentSchema,
|
||||||
|
OwnerSchema,
|
||||||
|
PractitionerSchema,
|
||||||
|
} from './identity'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Report document version 3: a report written on the canonical anatomical
|
||||||
|
* sheet. Zones name an annotation of a view of an exact sheet, findings a
|
||||||
|
* node path of a finding zone, both by stable ids; every label the report
|
||||||
|
* needs to stay readable without the sheet is snapshotted. Breaking change
|
||||||
|
* → version 4; additive optional fields keep the version.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const REPORT_VERSION = 3
|
||||||
|
|
||||||
|
export const SeveritySchema = z.enum(['mild', 'moderate', 'severe'])
|
||||||
|
export type Severity = z.infer<typeof SeveritySchema>
|
||||||
|
|
||||||
|
/** Region codes are the sheet's `vertebral_config` codes, checked at runtime. */
|
||||||
|
export const VertebraSchema = z.object({
|
||||||
|
region: z.string().min(1),
|
||||||
|
index: z.number().int().positive(),
|
||||||
|
})
|
||||||
|
export type Vertebra = z.infer<typeof VertebraSchema>
|
||||||
|
|
||||||
|
/** The sheet document a report was built on, by content. */
|
||||||
|
export const SheetRefSchema = z.object({
|
||||||
|
sheetId: z.string().min(1),
|
||||||
|
/** Database version id once the sheet lives in the database; null for a bundled draft. */
|
||||||
|
versionId: z.string().min(1).nullable(),
|
||||||
|
/** sha256 of the document file the report was written against. */
|
||||||
|
documentSha256: z.string().regex(/^[0-9a-f]{64}$/),
|
||||||
|
})
|
||||||
|
export type SheetRef = z.infer<typeof SheetRefSchema>
|
||||||
|
|
||||||
|
export const ReportZoneSchema = z.object({
|
||||||
|
annotationId: z.string().min(1),
|
||||||
|
viewId: z.string().min(1),
|
||||||
|
side: LateralSideSchema.optional(),
|
||||||
|
vertebrae: z.array(VertebraSchema).optional(),
|
||||||
|
/** Annotation name at selection time (or legacy name at migration). */
|
||||||
|
labelFrSnapshot: z.string().optional(),
|
||||||
|
labelEnSnapshot: z.string().optional(),
|
||||||
|
/** Set by the migration when the legacy id has no canonical annotation. */
|
||||||
|
unresolved: z.literal(true).optional(),
|
||||||
|
})
|
||||||
|
export type ReportZone = z.infer<typeof ReportZoneSchema>
|
||||||
|
|
||||||
|
export const FindingSchema = z.object({
|
||||||
|
findingZoneId: z.string().min(1),
|
||||||
|
/** Node ids from the zone's categories down to the leaf. */
|
||||||
|
path: z.array(z.string().min(1)).min(1),
|
||||||
|
labelFrSnapshot: z.string().min(1),
|
||||||
|
labelEnSnapshot: z.string().min(1),
|
||||||
|
requiresVetReferral: z.boolean().optional(),
|
||||||
|
side: LateralSideSchema.optional(),
|
||||||
|
/** Set by the migration when the path no longer exists in the sheet; data kept. */
|
||||||
|
unresolved: z.literal(true).optional(),
|
||||||
|
})
|
||||||
|
export type Finding = z.infer<typeof FindingSchema>
|
||||||
|
|
||||||
|
export const ObservationSchema = z.object({
|
||||||
|
id: z.string().min(1),
|
||||||
|
zones: z.array(ReportZoneSchema),
|
||||||
|
findings: z.array(FindingSchema),
|
||||||
|
freeTextFindings: z.array(z.string()),
|
||||||
|
severity: SeveritySchema.optional(),
|
||||||
|
comment: z.string(),
|
||||||
|
})
|
||||||
|
export type Observation = z.infer<typeof ObservationSchema>
|
||||||
|
|
||||||
|
export const ReportSchema = z.object({
|
||||||
|
version: z.literal(REPORT_VERSION),
|
||||||
|
id: z.string().min(1),
|
||||||
|
/** ISO timestamp of report creation. */
|
||||||
|
createdAt: z.string(),
|
||||||
|
/** ISO date of the clinical encounter. */
|
||||||
|
date: z.string(),
|
||||||
|
practitioner: PractitionerSchema,
|
||||||
|
animal: AnimalSchema,
|
||||||
|
owner: OwnerSchema,
|
||||||
|
sheet: SheetRefSchema,
|
||||||
|
observations: z.array(ObservationSchema),
|
||||||
|
conclusion: z.string(),
|
||||||
|
recommendations: z.string(),
|
||||||
|
nextAppointment: NextAppointmentSchema.optional(),
|
||||||
|
/** Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined. */
|
||||||
|
localAnnotations: z.array(z.unknown()).max(0).default([]),
|
||||||
|
})
|
||||||
|
export type Report = z.infer<typeof ReportSchema>
|
||||||
|
export type ReportInput = z.input<typeof ReportSchema>
|
||||||
|
|
||||||
|
export type { LateralSide, NextAppointment } from './identity'
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* The N-1 reader (RUST_ARCHITECTURE_REVIEW III.3 rule 7, VI.3): the Zod schemas and readers
|
||||||
|
* the last TypeScript build shipped, copied verbatim from `packages/domain/src` at develop
|
||||||
|
* 1a7ee7d (the R2 starting point) into `./domain`. Never edited: a Rust-written report, draft,
|
||||||
|
* snapshot or envelope that these readers refuse would break a rollback to that build.
|
||||||
|
* Permanent, it outlives `packages/domain` (deleted at R5).
|
||||||
|
*/
|
||||||
|
export {
|
||||||
|
ReportSchema,
|
||||||
|
ReportArchiveEnvelopeSchema,
|
||||||
|
SheetSnapshotSchema,
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
BrandingSchema,
|
||||||
|
PdfLabelSetSchema,
|
||||||
|
readArchiveDocument,
|
||||||
|
readReportDocument,
|
||||||
|
assertSnapshot,
|
||||||
|
type Report,
|
||||||
|
type ReportArchiveEnvelope,
|
||||||
|
type ReportMigrationMap,
|
||||||
|
} from './domain'
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
import { ReportZoneSchema, SheetRefSchema } from '@faunosteo/domain'
|
import { ReportZoneSchema, SheetRefSchema } from './n-1/domain'
|
||||||
|
|
||||||
import type { ReportZone, SheetRef } from '../types/index'
|
import type { ReportZone, SheetRef } from '../types/index'
|
||||||
import { callCore, loadCore, type CoreModule } from '../src/index'
|
import { callCore, loadCore, type CoreModule } from '../src/index'
|
||||||
|
|||||||
Generated
+7
-3
@@ -23,6 +23,9 @@ importers:
|
|||||||
'@faunosteo/anatomy':
|
'@faunosteo/anatomy':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/anatomy
|
version: link:../../packages/anatomy
|
||||||
|
'@faunosteo/core-wasm':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../../packages/core-wasm
|
||||||
'@faunosteo/domain':
|
'@faunosteo/domain':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/domain
|
version: link:../../packages/domain
|
||||||
@@ -147,10 +150,11 @@ importers:
|
|||||||
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15)
|
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15)
|
||||||
|
|
||||||
packages/core-wasm:
|
packages/core-wasm:
|
||||||
|
dependencies:
|
||||||
|
zod:
|
||||||
|
specifier: ^3.24.1
|
||||||
|
version: 3.25.76
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@faunosteo/domain':
|
|
||||||
specifier: workspace:*
|
|
||||||
version: link:../domain
|
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^20.19.41
|
specifier: ^20.19.41
|
||||||
version: 20.19.41
|
version: 20.19.41
|
||||||
|
|||||||
Reference in new issue
Block a user