feat(domain): archive contracts — sheet snapshot (lean document, caps, integrity), envelope v1 layered reader, branding and label schemas, report rebase, sheet index moved from the app; bundle carries asset hashes
This commit is contained in:
1 parent
8b86b926c8
commit
cdc0943f35
25 files changed
+2253
-116
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
# CONTRACT — step-06 phase 3 engine
|
# CONTRACT — step-06 phase 3 engine
|
||||||
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
|
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
|
||||||
- status: draft (dispatched after phases 1 and 2 land)
|
- status: active (phases 1 and 2 landed)
|
||||||
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3
|
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3
|
||||||
|
|
||||||
## REQUEST (IMMUTABLE)
|
## REQUEST (IMMUTABLE)
|
||||||
@@ -12,7 +12,7 @@ Create `packages/pdf` (`@faunosteo/pdf`): the browser-free PDF engine that expor
|
|||||||
EXPECT: ok
|
EXPECT: ok
|
||||||
2. Public API of `packages/pdf/src/index.ts` exactly spec §13: `exportReportArchive`, `exportFromEnvelope`, `readReportArchive`, `readAttachedDocument`, `ArchiveReadError` (kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version), `ArchiveExportError` (kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages), `Rasterizer`, `ExportInput`, `ExportResult`, `ExportWarning`, `PdfLocale`, `defaultPdfLabels`, `PDF_KEYWORD`, `MAX_PDF_BYTES`, `MAX_ATTACHMENT_BYTES`, plus `composeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): string` for tests and the app.
|
2. Public API of `packages/pdf/src/index.ts` exactly spec §13: `exportReportArchive`, `exportFromEnvelope`, `readReportArchive`, `readAttachedDocument`, `ArchiveReadError` (kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version), `ArchiveExportError` (kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages), `Rasterizer`, `ExportInput`, `ExportResult`, `ExportWarning`, `PdfLocale`, `defaultPdfLabels`, `PDF_KEYWORD`, `MAX_PDF_BYTES`, `MAX_ATTACHMENT_BYTES`, plus `composeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): string` for tests and the app.
|
||||||
3. Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images: `kind 'png'` → base64 decoded with `atob` → `embedPng`; `kind 'svg'` → sanitised + rasterised at width 1200 (height from its viewBox, same clamp) → `embedPng`; each slot fails alone (`logo_failed` warning); view raster failure → page without image + `view_raster_failed`; parallel rasterisation, sequential embedding in view order; `exportedAt` drives every date; `setKeywords([PDF_KEYWORD])`; envelope attached pretty-printed as `osteo-report.json`, description `Faunosteo report archive v1`.
|
3. Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images: `kind 'png'` → base64 decoded with `atob` → `embedPng`; `kind 'svg'` → sanitised + rasterised at width 1200 (height from its viewBox, same clamp) → `embedPng`; each slot fails alone (`logo_failed` warning); view raster failure → page without image + `view_raster_failed`; parallel rasterisation, sequential embedding in view order; `exportedAt` drives every date; `setKeywords([PDF_KEYWORD])`; envelope attached pretty-printed as `osteo-report.json`, description `Faunosteo report archive v1`.
|
||||||
4. Goldens (T3): `tests/goldens.test.ts` reproduces every Phase 0 golden under `apps/app/tests/fixtures/goldens/step6/` for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by reading `apps/app/tests/helpers/legacyLeaves.ts` logic, copy what you need into `tests/helpers/`), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical; views facts identical except `titles` (hidden markers are absent in the engine; assert `titles` ≥ highlighted count instead). Logo modes: `nologos` = Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG; `logos` = Branding built from the real `apps/app/public` files (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG (same constants as Phase 0). Any mismatch is a visible change: do not "fix" the golden; report it.
|
4. Goldens (T3): `tests/goldens.test.ts` reproduces every Phase 0 golden under `apps/app/tests/fixtures/goldens/step6/` for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by reading `apps/app/tests/helpers/legacyLeaves.ts` logic, copy what you need into `tests/helpers/`), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical (Phase 0 recorded images and links PER LOCALE: `images.<report>.<locale>.<logos>.json`, `links.<report>.<locale>.<logos>.json`, because the footer centres the powered-by block on the label width); views facts identical except `titles` and `dataAttributes` (hidden markers are absent in the engine and the layer `<g>` loses its `data-layer`/`data-view-id`: assert `titles` ≥ highlighted count and `dataAttributes === 0` instead of the golden's 2). Logo modes: `nologos` = Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG; `logos` = Branding built from the real `apps/app/public` files (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG for views AND for the partner SVG (same constants and the same single stub as Phase 0, see `apps/app/tests/helpers/goldens.ts`). Compose through `composeViewSvg` from `@faunosteo/anatomy/render` (generic `root: ComposeElement`, xmldom `Element` satisfies it) with `highlight: { annotationIds, halo: view.kind === 'main' }`. Any mismatch is a visible change: do not "fix" the golden; report it.
|
||||||
CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3
|
CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3
|
||||||
EXPECT: Tests .* passed
|
EXPECT: Tests .* passed
|
||||||
5. T1 no-sheet re-export (`tests/reexport.test.ts`): export demo from a snapshot built with `buildSheetSnapshot` on the draft loaded from `supabase/seed/anatomical-sheets/equine/draft/` → `readReportArchive` → `exportFromEnvelope` → identical text/images/views facts; envelope deep-equal minus `exportedAt`; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope).
|
5. T1 no-sheet re-export (`tests/reexport.test.ts`): export demo from a snapshot built with `buildSheetSnapshot` on the draft loaded from `supabase/seed/anatomical-sheets/equine/draft/` → `readReportArchive` → `exportFromEnvelope` → identical text/images/views facts; envelope deep-equal minus `exportedAt`; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope).
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# CONTRACT — step-06 phase 4 app
|
||||||
|
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
|
||||||
|
- status: draft (dispatched after phase 3 lands)
|
||||||
|
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "App session", "Branding in the app", §16 messages, §17 (T12/T13 kept green), Part I §7 T2/T14/T15
|
||||||
|
|
||||||
|
## REQUEST (IMMUTABLE)
|
||||||
|
Wire the application onto `@faunosteo/pdf`: export through the engine with a snapshot, branding and the browser rasterizer; import through the engine with layered reading, kept archive and explicit rebase; new import messages; old PDF code removed; `report:compare` on the engine read API. No visual change to pages or app layout; alerts follow the existing `window.alert` pattern.
|
||||||
|
|
||||||
|
## ACCEPTANCE CRITERIA
|
||||||
|
1. `apps/app/src/pdf/` contains only: `export.ts` (`exportReportToPdf(report, index, { locale }): Promise<Uint8Array>` kept as the route-facing signature, implemented as `exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), branding: await loadBranding(), labels: defaultPdfLabels, locale, rasterizer: browserRasterizer, exportedAt: new Date() })`, warnings → `console.warn`), `import.ts` (`importReportFromPdf(bytes, map)` returning the engine's `ArchiveReadOutcome`; `ImportError` kinds `invalid_pdf | incompatible_version | no_attachment | attachment_stripped` mapped 1:1 from `ArchiveReadError`), `browserRasterizer.ts` (today's `svgToPng.ts` adapted to `(svg, { widthPx, heightPx }) => Promise<Uint8Array>`: the engine computes the size, the adapter sets width/height on the root and draws), `branding.ts` (`loadBranding(): Promise<Branding>` per spec §14). `render/`, `attachment.ts`, `fonts.ts`, `src/anatomy/drawing.ts`'s highlight code are deleted; `drawing.ts` keeps `buildViewSvg`/`parseDrawing`/`sanitizeSvg` for the canvas (unchanged behaviour).
|
||||||
|
CHECK: ls apps/app/src/pdf
|
||||||
|
EXPECT: branding.ts browserRasterizer.ts export.ts import.ts
|
||||||
|
2. Store/persistence per spec §14 "App session": `archive: ReportArchiveEnvelope | null` in `ReportStore`, `hydrateImport({ report, archive })`, `initReport`/`reset`/`hydrateReport` clear it, `osteo:archive` key written only on those actions, `restoreDraft(index)` rebases a stale draft and restores the archive; `ArchivePersistence` beside `ReportPersistence`; tests in `state.reportStore.test.ts` extended (archive kept across a draft restore, cleared on new report, not rewritten on edits: spy on setItem).
|
||||||
|
3. `HomeRoute`: `importReportFromPdf` → `rebaseReportOnSheet(outcome.report, sheet.index, outcome.archive?.sheetSnapshot ?? null)` → `hydrateImport` → one alert composed per spec §16 (lines: migrated / archive_ok / snapshot_rejected with reason label / rebased with count) → `/editor`; error mapping adds `attachment_stripped`. `EditorRoute` export path unchanged for the user (download name, failure alert). The Phase 0 characterisation tests `routes.HomeRoute.import.test.tsx` and `routes.EditorRoute.export.test.tsx` stay green with at most these edits: the mocked outcome objects gain `origin`/`archive` fields, and the export call-shape assertion stays `(report, index, { locale })`.
|
||||||
|
4. i18n: keys of spec §16 added to fr.ts and en.ts with the given wording; `pdf.*` keys removed from both app dicts (the engine owns them; `severity.*`, `lateral.*`, `footer.*` stay, the UI uses them); `i18n.keys.test.ts` parity green.
|
||||||
|
5. `scripts/compare-reports.ts` + `scripts/compare/report.ts`: read through `readAttachedDocument` from `@faunosteo/pdf` and `readArchiveDocument` from `@faunosteo/domain/archive`; an envelope prints one extra header line `archive v1 (snapshot kept | snapshot rejected: <reason>)` under the same escaping rules; `scripts.compare.test.ts` green.
|
||||||
|
6. New tests: `pdf.export.app.test.ts` (T2: export the demo fixture through `exportReportToPdf` with the real bundled sheet, then mutate a cloned LoadedSheet's labels and one geometry, re-export the ENVELOPE through `exportFromEnvelope` and assert the engine output facts equal the first export, not the mutated sheet; T13 call shape covered by Phase 0), `pdf.goldens.test.ts` adapted so the app export path reproduces the Phase 0 goldens through the engine (same spies; the `rasterizeSvg` mock becomes a mock of `@/pdf/browserRasterizer`), `routes.HomeRoute.archive.test.tsx` (T15: envelope import with same sha → archive kept in store, archive_ok alert; envelope whose sha differs → rebased alert with count, unresolved flags, labels filled, `report.sheet` updated; snapshot rejected outcome → snapshot_rejected alert with the reason label; `attachment_stripped` → its error message), `migration.leaves.test.ts` kept green (612 leaves through the new path).
|
||||||
|
7. Bundle cost: `SHEET_BUNDLE=draft corepack pnpm build` in apps/app succeeds; report the gzip size of the main JS chunk before (from `git stash`-free method: build develop in a worktree is NOT allowed; instead read the size printed by vite for the chunk containing xmldom and report the total gz of dist/assets/*.js) and the size of the xmldom portion if vite's output isolates it; ceiling 50 KB gz for xmldom's share, else report.
|
||||||
|
8. Green: from the repo root `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build`; `grep -rn "fetch(" apps/app/src/pdf` shows only `branding.ts`.
|
||||||
|
CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm test:run 2>&1 | grep -E "Test Files|Tests " | tail -8
|
||||||
|
EXPECT: all passed
|
||||||
|
|
||||||
|
## FILE SCOPE
|
||||||
|
apps/app/src/pdf/**, apps/app/src/anatomy/drawing.ts (removal of highlight-only code if any), apps/app/src/app/routes/{HomeRoute,EditorRoute,NewReportRoute}.tsx (minimal), apps/app/src/state/{reportStore,persistence}.ts, apps/app/src/i18n/{fr,en}.ts, apps/app/scripts/**, apps/app/package.json (dependency `@faunosteo/pdf: workspace:*`, drop `pdf-lib` only if no app code imports it anymore), apps/app/tests/** (adaptations named above; goldens JSON files never edited), CLAUDE.md folder map lines for apps/app/src/pdf (keep docs minimal; Phase 5 owns the docs). Nothing under packages/**.
|
||||||
@@ -57,6 +57,7 @@ function loadSheet(): SheetIndex {
|
|||||||
document: json('document.json'),
|
document: json('document.json'),
|
||||||
migrationMap: json('report-migration-map.json'),
|
migrationMap: json('report-migration-map.json'),
|
||||||
assets: {},
|
assets: {},
|
||||||
|
assetHashes: {},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,113 +1,11 @@
|
|||||||
import type {
|
import type { SheetIndex as DomainSheetIndex } from '@faunosteo/domain'
|
||||||
Annotation,
|
|
||||||
FindingCategory,
|
|
||||||
FindingNode,
|
|
||||||
FindingZone,
|
|
||||||
LocalizedText,
|
|
||||||
SheetView,
|
|
||||||
VertebralRegion,
|
|
||||||
} from '@faunosteo/domain'
|
|
||||||
import type { Locale } from '@/i18n/types'
|
|
||||||
import type { LoadedSheet } from '@/sheets/provider'
|
import type { LoadedSheet } from '@/sheets/provider'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-only lookups over a loaded sheet. Everything the editor used to derive
|
* The sheet index lives in @faunosteo/domain since Step 6 (shared with the
|
||||||
* from SVG attributes, label matching or the species manifest comes from the
|
* PDF engine). This shim keeps the app's import path and binds the index to
|
||||||
* document here, by stable id: no label drives logic.
|
* the sheet the app loads, so `index.sheet` still carries the migration map.
|
||||||
*/
|
*/
|
||||||
|
export { buildSheetIndex, isObservable, pickLabel } from '@faunosteo/domain'
|
||||||
export type ObservableAnnotation = Extract<
|
export type { ObservableAnnotation } from '@faunosteo/domain'
|
||||||
Annotation,
|
export type SheetIndex = DomainSheetIndex<LoadedSheet>
|
||||||
{ kind: 'point' | 'zone' }
|
|
||||||
>
|
|
||||||
|
|
||||||
export interface SheetIndex {
|
|
||||||
sheet: LoadedSheet
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
export function pickLabel(
|
|
||||||
text: LocalizedText | null | undefined,
|
|
||||||
locale: Locale,
|
|
||||||
): 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'
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildSheetIndex(sheet: LoadedSheet): SheetIndex {
|
|
||||||
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')
|
|
||||||
|
|
||||||
const nodeAt: SheetIndex['nodeAt'] = (zoneId, path) => {
|
|
||||||
const zone = zones.get(zoneId)
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -28,15 +28,21 @@ export interface BundledSheetData {
|
|||||||
document: unknown
|
document: unknown
|
||||||
migrationMap: unknown
|
migrationMap: unknown
|
||||||
assets: Record<string, string>
|
assets: Record<string, string>
|
||||||
|
/** sha256 by `svg_asset_id`, from the seed manifest. */
|
||||||
|
assetHashes: Record<string, string>
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoadedSheet {
|
export interface LoadedSheet {
|
||||||
status: SheetStatus
|
status: SheetStatus
|
||||||
ref: SheetRef
|
ref: SheetRef
|
||||||
speciesId: string
|
speciesId: string
|
||||||
|
/** Document schema version of the sheet (`ref.schema_version`). */
|
||||||
|
schemaVersion: number
|
||||||
document: AnatomicalSheetDocument
|
document: AnatomicalSheetDocument
|
||||||
/** SVG text by `svg_asset_id`. */
|
/** SVG text by `svg_asset_id`. */
|
||||||
assets: Readonly<Record<string, string>>
|
assets: Readonly<Record<string, string>>
|
||||||
|
/** sha256 by `svg_asset_id`; carried into a report archive as provenance. */
|
||||||
|
assetHashes: Readonly<Record<string, string>>
|
||||||
migrationMap: ReportMigrationMap
|
migrationMap: ReportMigrationMap
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,8 +62,10 @@ export function parseBundledSheet(data: BundledSheetData): LoadedSheet {
|
|||||||
documentSha256: data.ref.document_sha256,
|
documentSha256: data.ref.document_sha256,
|
||||||
},
|
},
|
||||||
speciesId: data.ref.species_id,
|
speciesId: data.ref.species_id,
|
||||||
|
schemaVersion: data.ref.schema_version,
|
||||||
document,
|
document,
|
||||||
assets: data.assets,
|
assets: data.assets,
|
||||||
|
assetHashes: data.assetHashes,
|
||||||
migrationMap,
|
migrationMap,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
* Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet
|
* Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet
|
||||||
* loads, validates, and indexes as the canonical document says.
|
* loads, validates, and indexes as the canonical document says.
|
||||||
*/
|
*/
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { resolve } from 'node:path'
|
||||||
import { beforeAll, describe, expect, it } from 'vitest'
|
import { beforeAll, describe, expect, it } from 'vitest'
|
||||||
import { bundledSheetProvider } from '@/sheets/provider'
|
import { bundledSheetProvider } from '@/sheets/provider'
|
||||||
import {
|
import {
|
||||||
@@ -12,6 +14,12 @@ import {
|
|||||||
} from '@/services/sheetIndex'
|
} from '@/services/sheetIndex'
|
||||||
import { loadTestSheet } from '../helpers/sheet'
|
import { loadTestSheet } from '../helpers/sheet'
|
||||||
|
|
||||||
|
/** The seed manifest the bundle reads its asset hashes from. */
|
||||||
|
const ASSET_MANIFEST = resolve(
|
||||||
|
__dirname,
|
||||||
|
'../../../../supabase/seed/anatomical-sheets/equine/draft/assets.json',
|
||||||
|
)
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
@@ -32,6 +40,19 @@ describe('bundled sheet provider', () => {
|
|||||||
)
|
)
|
||||||
expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull()
|
expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('carries the schema version and the manifest hash of the horse asset', async () => {
|
||||||
|
const loaded = await bundledSheetProvider.getReferenceSheet('equine')
|
||||||
|
const manifest = JSON.parse(readFileSync(ASSET_MANIFEST, 'utf8')) as {
|
||||||
|
sha256: string
|
||||||
|
svg_asset_id: string
|
||||||
|
}[]
|
||||||
|
const horse = manifest[0]!
|
||||||
|
expect(loaded!.schemaVersion).toBe(2)
|
||||||
|
expect(Object.keys(loaded!.assetHashes)).toEqual([horse.svg_asset_id])
|
||||||
|
expect(loaded!.assetHashes[horse.svg_asset_id]).toBe(horse.sha256)
|
||||||
|
expect(horse.sha256).toMatch(/^[0-9a-f]{64}$/)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('sheet index', () => {
|
describe('sheet index', () => {
|
||||||
@@ -93,9 +114,12 @@ describe('sheet index', () => {
|
|||||||
.filter(isObservable)
|
.filter(isObservable)
|
||||||
.map((a) => a.vertebral_region_code)
|
.map((a) => a.vertebral_region_code)
|
||||||
.filter((c) => c !== null)
|
.filter((c) => c !== null)
|
||||||
expect(sheet.regions().map((r) => r.code).sort()).toEqual(
|
expect(
|
||||||
[...carried].sort(),
|
sheet
|
||||||
)
|
.regions()
|
||||||
|
.map((r) => r.code)
|
||||||
|
.sort(),
|
||||||
|
).toEqual([...carried].sort())
|
||||||
})
|
})
|
||||||
|
|
||||||
it('resolves finding paths and reports absent ones', () => {
|
it('resolves finding paths and reports absent ones', () => {
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import type { Plugin } from 'vite'
|
|||||||
* application as the virtual module `virtual:faunosteo-sheet`.
|
* application as the virtual module `virtual:faunosteo-sheet`.
|
||||||
*
|
*
|
||||||
* Mode `draft` embeds `document.json`, `sheet-ref.json`,
|
* Mode `draft` embeds `document.json`, `sheet-ref.json`,
|
||||||
* `report-migration-map.json` and the SVG assets of the seed folder; mode
|
* `report-migration-map.json`, the SVG assets of the seed folder and their
|
||||||
|
* manifest hashes (`assets.json`, carried into report archives); mode
|
||||||
* `none` exports null and the app shows "no sheet configured". The default is
|
* `none` exports null and the app shows "no sheet configured". The default is
|
||||||
* `draft` for the dev server and `none` for a build: a production bundle never
|
* `draft` for the dev server and `none` for a build: a production bundle never
|
||||||
* carries the medically unvalidated draft unless `SHEET_BUNDLE=draft` is set
|
* carries the medically unvalidated draft unless `SHEET_BUNDLE=draft` is set
|
||||||
@@ -36,6 +37,7 @@ interface SeedFiles {
|
|||||||
document: unknown
|
document: unknown
|
||||||
migrationMap: unknown
|
migrationMap: unknown
|
||||||
assets: Record<string, string>
|
assets: Record<string, string>
|
||||||
|
assetHashes: Record<string, string>
|
||||||
watched: string[]
|
watched: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,20 +46,24 @@ function readSeed(seedDir: string): SeedFiles {
|
|||||||
JSON.parse(readFileSync(join(seedDir, name), 'utf8')) as unknown
|
JSON.parse(readFileSync(join(seedDir, name), 'utf8')) as unknown
|
||||||
const manifest = json('assets.json') as {
|
const manifest = json('assets.json') as {
|
||||||
file: string
|
file: string
|
||||||
|
sha256: string
|
||||||
svg_asset_id: string
|
svg_asset_id: string
|
||||||
}[]
|
}[]
|
||||||
const assets: Record<string, string> = {}
|
const assets: Record<string, string> = {}
|
||||||
|
const assetHashes: Record<string, string> = {}
|
||||||
for (const asset of manifest) {
|
for (const asset of manifest) {
|
||||||
assets[asset.svg_asset_id] = readFileSync(
|
assets[asset.svg_asset_id] = readFileSync(
|
||||||
join(seedDir, 'assets', asset.file),
|
join(seedDir, 'assets', asset.file),
|
||||||
'utf8',
|
'utf8',
|
||||||
)
|
)
|
||||||
|
assetHashes[asset.svg_asset_id] = asset.sha256
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
ref: json('sheet-ref.json'),
|
ref: json('sheet-ref.json'),
|
||||||
document: json('document.json'),
|
document: json('document.json'),
|
||||||
migrationMap: json('report-migration-map.json'),
|
migrationMap: json('report-migration-map.json'),
|
||||||
assets,
|
assets,
|
||||||
|
assetHashes,
|
||||||
watched: [
|
watched: [
|
||||||
'sheet-ref.json',
|
'sheet-ref.json',
|
||||||
'document.json',
|
'document.json',
|
||||||
@@ -88,6 +94,7 @@ export function faunosteoSheetBundle(options: {
|
|||||||
document: seed.document,
|
document: seed.document,
|
||||||
migrationMap: seed.migrationMap,
|
migrationMap: seed.migrationMap,
|
||||||
assets: seed.assets,
|
assets: seed.assets,
|
||||||
|
assetHashes: seed.assetHashes,
|
||||||
}
|
}
|
||||||
return `export const bundledSheet = ${JSON.stringify(payload)}\n`
|
return `export const bundledSheet = ${JSON.stringify(payload)}\n`
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
"./anatomical-sheet": "./src/anatomical-sheet/index.ts",
|
"./anatomical-sheet": "./src/anatomical-sheet/index.ts",
|
||||||
"./report": "./src/report/index.ts"
|
"./report": "./src/report/index.ts",
|
||||||
|
"./archive": "./src/archive/index.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from './schema'
|
export * from './schema'
|
||||||
export * from './validate'
|
export * from './validate'
|
||||||
export * from './create'
|
export * from './create'
|
||||||
|
export * from './sheet-index'
|
||||||
@@ -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,51 @@
|
|||||||
|
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}$/
|
||||||
|
|
||||||
|
const HttpUrlSchema = z
|
||||||
|
.string()
|
||||||
|
.max(2048)
|
||||||
|
.url()
|
||||||
|
.refine((url) => /^https?:\/\//i.test(url), '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]),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
export * from './anatomical-sheet'
|
export * from './anatomical-sheet'
|
||||||
export * from './report'
|
export * from './report'
|
||||||
|
export * from './archive'
|
||||||
@@ -25,3 +25,8 @@ export {
|
|||||||
UnsupportedReportVersionError,
|
UnsupportedReportVersionError,
|
||||||
type MigrationOutcome,
|
type MigrationOutcome,
|
||||||
} from './migrate'
|
} from './migrate'
|
||||||
|
export {
|
||||||
|
rebaseReportOnSheet,
|
||||||
|
type RebaseIndex,
|
||||||
|
type RebaseOutcome,
|
||||||
|
} from './rebase'
|
||||||
@@ -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,137 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
BrandingSchema,
|
||||||
|
PDF_LABEL_KEYS,
|
||||||
|
PdfLabelSetSchema,
|
||||||
|
type Branding,
|
||||||
|
type PdfLabels,
|
||||||
|
} from '../src'
|
||||||
|
|
||||||
|
export function sampleBranding(): Branding {
|
||||||
|
return {
|
||||||
|
siteUrl: 'https://faunosteo.com',
|
||||||
|
headerLogo: { kind: 'png', base64: 'iVBORw0KGgo=' },
|
||||||
|
footerLogo: null,
|
||||||
|
poweredBy: {
|
||||||
|
logo: null,
|
||||||
|
url: 'https://zenquality.fr',
|
||||||
|
fallbackText: 'zenquality.fr',
|
||||||
|
},
|
||||||
|
partner: {
|
||||||
|
logo: { kind: 'svg', svg: '<svg xmlns="http://www.w3.org/2000/svg"/>' },
|
||||||
|
url: 'https://www.instagram.com/paws.iin.harmony',
|
||||||
|
fallbackText: '@paws.iin.harmony',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sampleLabels(): PdfLabels {
|
||||||
|
return Object.fromEntries(
|
||||||
|
PDF_LABEL_KEYS.map((key) => [key, key]),
|
||||||
|
) as PdfLabels
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BrandingSchema', () => {
|
||||||
|
it('accepts the current identity and both image kinds', () => {
|
||||||
|
expect(BrandingSchema.parse(sampleBranding())).toEqual(sampleBranding())
|
||||||
|
const bare = {
|
||||||
|
siteUrl: 'http://localhost:5173',
|
||||||
|
headerLogo: null,
|
||||||
|
footerLogo: null,
|
||||||
|
poweredBy: null,
|
||||||
|
partner: null,
|
||||||
|
}
|
||||||
|
expect(BrandingSchema.parse(bare)).toEqual(bare)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['unknown key', (b: Branding) => ({ ...b, extra: 1 })],
|
||||||
|
[
|
||||||
|
'non-http URL',
|
||||||
|
(b: Branding) => ({ ...b, siteUrl: 'javascript:alert(1)' }),
|
||||||
|
],
|
||||||
|
['ftp URL', (b: Branding) => ({ ...b, siteUrl: 'ftp://x.test/a' })],
|
||||||
|
[
|
||||||
|
'URL over 2048 chars',
|
||||||
|
(b: Branding) => ({
|
||||||
|
...b,
|
||||||
|
siteUrl: `https://x.test/${'a'.repeat(2048)}`,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'PNG base64 over 512 KiB',
|
||||||
|
(b: Branding) => ({
|
||||||
|
...b,
|
||||||
|
headerLogo: { kind: 'png', base64: 'A'.repeat(512 * 1024 + 4) },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'PNG base64 with foreign characters',
|
||||||
|
(b: Branding) => ({
|
||||||
|
...b,
|
||||||
|
headerLogo: { kind: 'png', base64: '<svg/>' },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'SVG over 256 KiB',
|
||||||
|
(b: Branding) => ({
|
||||||
|
...b,
|
||||||
|
footerLogo: { kind: 'svg', svg: 'x'.repeat(256 * 1024 + 1) },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'fallback text over 128 chars',
|
||||||
|
(b: Branding) => ({
|
||||||
|
...b,
|
||||||
|
poweredBy: { ...b.poweredBy!, fallbackText: 'x'.repeat(129) },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'credit with unknown key',
|
||||||
|
(b: Branding) => ({ ...b, partner: { ...b.partner!, extra: true } }),
|
||||||
|
],
|
||||||
|
])('rejects %s', (_name, mutate) => {
|
||||||
|
expect(BrandingSchema.safeParse(mutate(sampleBranding())).success).toBe(
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('PdfLabelSetSchema', () => {
|
||||||
|
it('lists 25 distinct keys and accepts a complete set in both locales', () => {
|
||||||
|
expect(PDF_LABEL_KEYS).toHaveLength(25)
|
||||||
|
expect(new Set(PDF_LABEL_KEYS).size).toBe(25)
|
||||||
|
const set = { fr: sampleLabels(), en: sampleLabels() }
|
||||||
|
expect(PdfLabelSetSchema.parse(set)).toEqual(set)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects a missing key, an extra key, a long value, a missing locale', () => {
|
||||||
|
const missing: Partial<PdfLabels> = sampleLabels()
|
||||||
|
delete missing['pdf.empty']
|
||||||
|
expect(
|
||||||
|
PdfLabelSetSchema.safeParse({ fr: missing, en: sampleLabels() }).success,
|
||||||
|
).toBe(false)
|
||||||
|
expect(
|
||||||
|
PdfLabelSetSchema.safeParse({
|
||||||
|
fr: { ...sampleLabels(), 'pdf.extra': 'x' },
|
||||||
|
en: sampleLabels(),
|
||||||
|
}).success,
|
||||||
|
).toBe(false)
|
||||||
|
expect(
|
||||||
|
PdfLabelSetSchema.safeParse({
|
||||||
|
fr: { ...sampleLabels(), 'pdf.subject': 'x'.repeat(257) },
|
||||||
|
en: sampleLabels(),
|
||||||
|
}).success,
|
||||||
|
).toBe(false)
|
||||||
|
expect(PdfLabelSetSchema.safeParse({ fr: sampleLabels() }).success).toBe(
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
PdfLabelSetSchema.safeParse({
|
||||||
|
fr: sampleLabels(),
|
||||||
|
en: sampleLabels(),
|
||||||
|
de: sampleLabels(),
|
||||||
|
}).success,
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
ENVELOPE_FORMAT,
|
||||||
|
ENVELOPE_VERSION,
|
||||||
|
ReportArchiveEnvelopeSchema,
|
||||||
|
UnsupportedReportVersionError,
|
||||||
|
buildSheetSnapshot,
|
||||||
|
migrateReportV2ToV3,
|
||||||
|
readArchiveDocument,
|
||||||
|
readReportDocument,
|
||||||
|
type ReportArchiveEnvelope,
|
||||||
|
} from '../src'
|
||||||
|
import fullV2 from './fixtures/report-v2.full.json'
|
||||||
|
import { sampleBranding, sampleLabels } from './archive.branding-labels.test'
|
||||||
|
import { loadDraftSheet } from './helpers/draft-sheet'
|
||||||
|
import {
|
||||||
|
leavesAsV2Report,
|
||||||
|
legacyLeaves,
|
||||||
|
loadLegacyBaseline,
|
||||||
|
} from './helpers/legacy-leaves'
|
||||||
|
|
||||||
|
const draft = loadDraftSheet()
|
||||||
|
const map = draft.migrationMap
|
||||||
|
const { report } = readReportDocument(fullV2, map)
|
||||||
|
|
||||||
|
/** A fresh envelope as JSON.parse of an attachment would give it. */
|
||||||
|
function envelope(): ReportArchiveEnvelope {
|
||||||
|
const env: ReportArchiveEnvelope = {
|
||||||
|
format: ENVELOPE_FORMAT,
|
||||||
|
envelopeVersion: ENVELOPE_VERSION,
|
||||||
|
exportedAt: '2026-10-11T10:00:00.000Z',
|
||||||
|
locale: 'fr',
|
||||||
|
report,
|
||||||
|
sheetSnapshot: buildSheetSnapshot(draft, report),
|
||||||
|
branding: sampleBranding(),
|
||||||
|
labels: { fr: sampleLabels(), en: sampleLabels() },
|
||||||
|
}
|
||||||
|
return JSON.parse(JSON.stringify(env)) as ReportArchiveEnvelope
|
||||||
|
}
|
||||||
|
|
||||||
|
type Raw = Record<string, unknown>
|
||||||
|
const raw = (env: ReportArchiveEnvelope): Raw => env as unknown as Raw
|
||||||
|
|
||||||
|
describe('readArchiveDocument: bare reports', () => {
|
||||||
|
it('reads a bare v3 as is', () => {
|
||||||
|
const outcome = readArchiveDocument(JSON.parse(JSON.stringify(report)), map)
|
||||||
|
expect(outcome).toEqual({
|
||||||
|
report,
|
||||||
|
origin: 'bare_v3',
|
||||||
|
migrated: false,
|
||||||
|
unresolvedZones: 0,
|
||||||
|
unresolvedFindings: 0,
|
||||||
|
archive: null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('migrates a bare v2 with the counts of the migration', () => {
|
||||||
|
const outcome = readArchiveDocument(fullV2, map)
|
||||||
|
expect(outcome.origin).toBe('v2')
|
||||||
|
expect(outcome.migrated).toBe(true)
|
||||||
|
expect(outcome.archive).toBeNull()
|
||||||
|
expect(outcome.report).toEqual(report)
|
||||||
|
expect(outcome.snapshotRejected).toBeUndefined()
|
||||||
|
|
||||||
|
const leaves = leavesAsV2Report(legacyLeaves(loadLegacyBaseline()))
|
||||||
|
const expected = migrateReportV2ToV3(leaves, map)
|
||||||
|
const migrated = readArchiveDocument(leaves, map)
|
||||||
|
expect(expected.unresolvedFindings).toBeGreaterThan(0)
|
||||||
|
expect(migrated.unresolvedFindings).toBe(expected.unresolvedFindings)
|
||||||
|
expect(migrated.unresolvedZones).toBe(expected.unresolvedZones)
|
||||||
|
expect(migrated.report).toEqual(expected.report)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws for a report version it cannot read, or a non-object', () => {
|
||||||
|
expect(() => readArchiveDocument({ ...report, version: 1 }, map)).toThrow(
|
||||||
|
UnsupportedReportVersionError,
|
||||||
|
)
|
||||||
|
for (const data of [null, undefined, 'report', 42, [report]]) {
|
||||||
|
expect(() => readArchiveDocument(data, map)).toThrow(
|
||||||
|
UnsupportedReportVersionError,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('readArchiveDocument: envelopes', () => {
|
||||||
|
it('accepts a valid v1 envelope whole', () => {
|
||||||
|
const env = envelope()
|
||||||
|
const outcome = readArchiveDocument(env, map)
|
||||||
|
expect(outcome.origin).toBe('envelope_v1')
|
||||||
|
expect(outcome.migrated).toBe(false)
|
||||||
|
expect(outcome.unresolvedZones).toBe(0)
|
||||||
|
expect(outcome.snapshotRejected).toBeUndefined()
|
||||||
|
expect(outcome.report).toEqual(report)
|
||||||
|
expect(outcome.archive).toEqual(env)
|
||||||
|
expect(ReportArchiveEnvelopeSchema.parse(env)).toEqual(env)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the report of an envelope version it does not know', () => {
|
||||||
|
const outcome = readArchiveDocument(
|
||||||
|
{ ...envelope(), envelopeVersion: 2 },
|
||||||
|
map,
|
||||||
|
)
|
||||||
|
expect(outcome.report).toEqual(report)
|
||||||
|
expect(outcome.origin).toBe('bare_v3')
|
||||||
|
expect(outcome.archive).toBeNull()
|
||||||
|
expect(outcome.snapshotRejected).toBe('unsupported_envelope')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('names the report version when the wrapped report is unknown', () => {
|
||||||
|
const env = raw(envelope())
|
||||||
|
env.report = { ...report, version: 4 }
|
||||||
|
let thrown: unknown
|
||||||
|
try {
|
||||||
|
readArchiveDocument(env, map)
|
||||||
|
} catch (error) {
|
||||||
|
thrown = error
|
||||||
|
}
|
||||||
|
expect(thrown).toBeInstanceOf(UnsupportedReportVersionError)
|
||||||
|
expect((thrown as UnsupportedReportVersionError).foundVersion).toBe(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores unknown metadata keys, __proto__ included, within v1', () => {
|
||||||
|
const env = raw(envelope())
|
||||||
|
env.futureField = { anything: true }
|
||||||
|
const outcome = readArchiveDocument(env, map)
|
||||||
|
expect(outcome.archive).not.toBeNull()
|
||||||
|
expect('futureField' in outcome.archive!).toBe(false)
|
||||||
|
|
||||||
|
const text = JSON.stringify(envelope()).replace(
|
||||||
|
'"format"',
|
||||||
|
'"__proto__":{"polluted":true},"format"',
|
||||||
|
)
|
||||||
|
const polluted = readArchiveDocument(JSON.parse(text), map)
|
||||||
|
expect(polluted.archive).not.toBeNull()
|
||||||
|
expect(({} as { polluted?: boolean }).polluted).toBeUndefined()
|
||||||
|
expect(Object.hasOwn(polluted.archive!, '__proto__')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops the envelope on a wrapper fault (schema): branding, labels, metadata', () => {
|
||||||
|
const branding = raw(envelope())
|
||||||
|
branding.branding = { ...sampleBranding(), siteUrl: 'javascript:alert(1)' }
|
||||||
|
expect(readArchiveDocument(branding, map)).toMatchObject({
|
||||||
|
report,
|
||||||
|
origin: 'envelope_v1',
|
||||||
|
archive: null,
|
||||||
|
snapshotRejected: 'schema',
|
||||||
|
})
|
||||||
|
|
||||||
|
const labels = raw(envelope())
|
||||||
|
labels.labels = { fr: sampleLabels() }
|
||||||
|
expect(readArchiveDocument(labels, map).snapshotRejected).toBe('schema')
|
||||||
|
|
||||||
|
const locale = raw(envelope())
|
||||||
|
locale.locale = 'de'
|
||||||
|
expect(readArchiveDocument(locale, map).snapshotRejected).toBe('schema')
|
||||||
|
|
||||||
|
const format = raw(envelope())
|
||||||
|
format.format = 'other'
|
||||||
|
expect(readArchiveDocument(format, map).snapshotRejected).toBe('schema')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops a snapshot over the caps or failing its own schema', () => {
|
||||||
|
const caps = envelope()
|
||||||
|
caps.sheetSnapshot.document.name.fr = 'x'.repeat(513)
|
||||||
|
expect(readArchiveDocument(caps, map)).toMatchObject({
|
||||||
|
report,
|
||||||
|
archive: null,
|
||||||
|
snapshotRejected: 'caps',
|
||||||
|
})
|
||||||
|
|
||||||
|
const schema = raw(envelope())
|
||||||
|
schema.sheetSnapshot = { ...envelope().sheetSnapshot, extra: 1 }
|
||||||
|
expect(readArchiveDocument(schema, map).snapshotRejected).toBe('schema')
|
||||||
|
|
||||||
|
const missing = raw(envelope())
|
||||||
|
delete missing.sheetSnapshot
|
||||||
|
expect(readArchiveDocument(missing, map).snapshotRejected).toBe('schema')
|
||||||
|
|
||||||
|
const integrity = envelope()
|
||||||
|
integrity.sheetSnapshot.assets = []
|
||||||
|
expect(readArchiveDocument(integrity, map).snapshotRejected).toBe(
|
||||||
|
'integrity',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops a snapshot of another sheet than the report (sheet_mismatch)', () => {
|
||||||
|
const sha = envelope()
|
||||||
|
sha.sheetSnapshot.ref.documentSha256 = 'f'.repeat(64)
|
||||||
|
expect(readArchiveDocument(sha, map)).toMatchObject({
|
||||||
|
report,
|
||||||
|
origin: 'envelope_v1',
|
||||||
|
archive: null,
|
||||||
|
snapshotRejected: 'sheet_mismatch',
|
||||||
|
})
|
||||||
|
|
||||||
|
const id = envelope()
|
||||||
|
id.sheetSnapshot.ref.sheetId = 'another-sheet'
|
||||||
|
expect(readArchiveDocument(id, map).snapshotRejected).toBe('sheet_mismatch')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('migrates a v2 report found inside an envelope and still checks the snapshot', () => {
|
||||||
|
const env = raw(envelope())
|
||||||
|
env.report = fullV2
|
||||||
|
const outcome = readArchiveDocument(env, map)
|
||||||
|
expect(outcome.origin).toBe('envelope_v1')
|
||||||
|
expect(outcome.migrated).toBe(true)
|
||||||
|
expect(outcome.report).toEqual(report)
|
||||||
|
expect(outcome.archive?.report).toEqual(report)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
REPORT_VERSION,
|
||||||
|
SNAPSHOT_CAPS,
|
||||||
|
SnapshotError,
|
||||||
|
assertSnapshot,
|
||||||
|
buildSheetIndex,
|
||||||
|
buildSheetSnapshot,
|
||||||
|
readReportDocument,
|
||||||
|
snapshotIndexSource,
|
||||||
|
validateSheetDocument,
|
||||||
|
type Report,
|
||||||
|
type SheetSnapshot,
|
||||||
|
type SnapshotRejection,
|
||||||
|
type SnapshotSource,
|
||||||
|
} from '../src'
|
||||||
|
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
|
||||||
|
import fullV2 from './fixtures/report-v2.full.json'
|
||||||
|
import { loadDraftSheet } from './helpers/draft-sheet'
|
||||||
|
import {
|
||||||
|
leavesAsV2Report,
|
||||||
|
legacyLeaves,
|
||||||
|
loadLegacyBaseline,
|
||||||
|
} from './helpers/legacy-leaves'
|
||||||
|
|
||||||
|
const SHA = 'b'.repeat(64)
|
||||||
|
const HASH = 'c'.repeat(64)
|
||||||
|
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"></svg>'
|
||||||
|
|
||||||
|
function sliceSource(): SnapshotSource {
|
||||||
|
return {
|
||||||
|
status: 'draft',
|
||||||
|
ref: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA },
|
||||||
|
speciesId: 'equine',
|
||||||
|
schemaVersion: 2,
|
||||||
|
document: horseSlice(),
|
||||||
|
assets: { [HORSE_MAIN_ASSET_ID]: SVG },
|
||||||
|
assetHashes: { [HORSE_MAIN_ASSET_ID]: HASH },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sliceReport(): Report {
|
||||||
|
return {
|
||||||
|
version: REPORT_VERSION,
|
||||||
|
id: 'r1',
|
||||||
|
createdAt: '2026-10-10T10:00:00Z',
|
||||||
|
date: '2026-10-10',
|
||||||
|
practitioner: { name: 'Dr. Dupont' },
|
||||||
|
animal: { speciesId: 'equine', name: 'Mistral' },
|
||||||
|
owner: { name: 'Jean Martin' },
|
||||||
|
sheet: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA },
|
||||||
|
observations: [
|
||||||
|
{
|
||||||
|
id: 'obs-1',
|
||||||
|
zones: [{ annotationId: 'hip', viewId: 'view-main' }],
|
||||||
|
findings: [
|
||||||
|
{
|
||||||
|
findingZoneId: 'hip',
|
||||||
|
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
|
||||||
|
labelFrSnapshot: 'Restriction en flexion',
|
||||||
|
labelEnSnapshot: 'Flexion restriction',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
findingZoneId: 'hip',
|
||||||
|
path: ['hip-dysfunctions', 'articular', 'ghost-leaf'],
|
||||||
|
labelFrSnapshot: 'Disparu',
|
||||||
|
labelEnSnapshot: 'Gone',
|
||||||
|
unresolved: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
findingZoneId: 'sphenoid',
|
||||||
|
path: ['ssb-dysfunctions', 'physiological', 'torsion-right'],
|
||||||
|
labelFrSnapshot: 'Torsion droite',
|
||||||
|
labelEnSnapshot: 'Right torsion',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
freeTextFindings: [],
|
||||||
|
comment: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
conclusion: '',
|
||||||
|
recommendations: '',
|
||||||
|
localAnnotations: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sliceSnapshot(): SheetSnapshot {
|
||||||
|
return buildSheetSnapshot(sliceSource(), sliceReport())
|
||||||
|
}
|
||||||
|
|
||||||
|
function rejection(input: unknown): SnapshotRejection | 'accepted' {
|
||||||
|
try {
|
||||||
|
assertSnapshot(input)
|
||||||
|
return 'accepted'
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof SnapshotError) return error.reason
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('buildSheetSnapshot on the equine draft', () => {
|
||||||
|
const draft = loadDraftSheet()
|
||||||
|
const { report } = readReportDocument(fullV2, draft.migrationMap)
|
||||||
|
const snapshot = buildSheetSnapshot(draft, report)
|
||||||
|
|
||||||
|
it('keeps every view, annotation, category and region, empties the bibliography', () => {
|
||||||
|
expect(snapshot.document.views).toEqual(draft.document.views)
|
||||||
|
expect(snapshot.document.annotations).toEqual(draft.document.annotations)
|
||||||
|
expect(snapshot.document.categories).toEqual(draft.document.categories)
|
||||||
|
expect(snapshot.document.vertebral_config).toEqual(
|
||||||
|
draft.document.vertebral_config,
|
||||||
|
)
|
||||||
|
expect(snapshot.document.references).toEqual([])
|
||||||
|
expect(snapshot.document.name).toEqual(draft.document.name)
|
||||||
|
expect(snapshot.document.scope_disclaimer).toEqual(
|
||||||
|
draft.document.scope_disclaimer,
|
||||||
|
)
|
||||||
|
expect(snapshot.document.attribution).toEqual(draft.document.attribution)
|
||||||
|
expect(snapshot.document.species_id).toBe('equine')
|
||||||
|
expect(snapshot.document.schema_version).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('prunes finding trees to the paths the report uses, every zone kept', () => {
|
||||||
|
expect(snapshot.document.finding_zones.map((z) => z.id)).toEqual(
|
||||||
|
draft.document.finding_zones.map((z) => z.id),
|
||||||
|
)
|
||||||
|
const c7 = snapshot.document.finding_zones.find((z) => z.id === 'c7-t1')!
|
||||||
|
expect(c7.categories).toHaveLength(1)
|
||||||
|
expect(c7.categories[0]).toMatchObject({
|
||||||
|
id: 'c7-t1-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
description: {},
|
||||||
|
reference_ids: [],
|
||||||
|
})
|
||||||
|
expect(c7.categories[0]!.children.map((n) => n.id)).toEqual(['segmental'])
|
||||||
|
expect(c7.categories[0]!.children[0]!.children).toMatchObject([
|
||||||
|
{ id: 'fixation', description: {}, reference_ids: [], children: [] },
|
||||||
|
])
|
||||||
|
const used = new Set(
|
||||||
|
report.observations.flatMap((o) =>
|
||||||
|
o.findings.map((f) => f.findingZoneId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for (const zone of snapshot.document.finding_zones) {
|
||||||
|
if (!used.has(zone.id)) expect(zone.categories, zone.id).toEqual([])
|
||||||
|
else expect(zone.categories.length, zone.id).toBeGreaterThan(0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries the reachable asset with its manifest hash and the full ref', () => {
|
||||||
|
const [assetId] = Object.keys(draft.assets)
|
||||||
|
expect(snapshot.assets).toEqual([
|
||||||
|
{
|
||||||
|
svgAssetId: assetId,
|
||||||
|
sha256: draft.assetHashes[assetId!],
|
||||||
|
svg: draft.assets[assetId!],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(snapshot.ref).toEqual({
|
||||||
|
...draft.ref,
|
||||||
|
schemaVersion: 2,
|
||||||
|
speciesId: 'equine',
|
||||||
|
})
|
||||||
|
expect(snapshot.status).toBe('draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is a valid document with no integrity error, under 250,000 bytes pretty-printed', () => {
|
||||||
|
expect(() =>
|
||||||
|
AnatomicalSheetDocumentSchema.parse(snapshot.document),
|
||||||
|
).not.toThrow()
|
||||||
|
const errors = validateSheetDocument(snapshot.document).filter(
|
||||||
|
(i) => i.severity === 'error',
|
||||||
|
)
|
||||||
|
expect(errors).toEqual([])
|
||||||
|
const bytes = Buffer.byteLength(JSON.stringify(snapshot, null, 2), 'utf8')
|
||||||
|
console.log(
|
||||||
|
`snapshot (report-v2.full on the draft, pretty JSON): ${bytes} bytes`,
|
||||||
|
)
|
||||||
|
expect(bytes).toBeLessThan(250_000)
|
||||||
|
expect(assertSnapshot(snapshot)).toEqual(snapshot)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is pure and deterministic', () => {
|
||||||
|
const before = JSON.stringify(draft.document)
|
||||||
|
const again = buildSheetSnapshot(draft, report)
|
||||||
|
expect(JSON.stringify(draft.document)).toBe(before)
|
||||||
|
expect(again).toEqual(snapshot)
|
||||||
|
expect(again.document.views).not.toBe(draft.document.views)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps what exists of an unresolved path and nothing else (legacy leaves)', () => {
|
||||||
|
const v2 = leavesAsV2Report(legacyLeaves(loadLegacyBaseline()))
|
||||||
|
const migrated = readReportDocument(v2, draft.migrationMap)
|
||||||
|
expect(migrated.unresolvedFindings).toBeGreaterThan(0)
|
||||||
|
const snap = buildSheetSnapshot(draft, migrated.report)
|
||||||
|
expect(assertSnapshot(snap)).toEqual(snap)
|
||||||
|
const index = buildSheetIndex(snapshotIndexSource(snap))
|
||||||
|
const findings = migrated.report.observations.flatMap((o) => o.findings)
|
||||||
|
for (const finding of findings) {
|
||||||
|
const node = index.nodeAt(finding.findingZoneId, finding.path)
|
||||||
|
if (finding.unresolved)
|
||||||
|
expect(node, finding.path.join('/')).toBeUndefined()
|
||||||
|
else expect(node, finding.path.join('/')).toBeDefined()
|
||||||
|
}
|
||||||
|
expect(index.sheet.ref.sheetId).toBe(draft.ref.sheetId)
|
||||||
|
expect(index.sheet.assets[snap.assets[0]!.svgAssetId]).toBe(
|
||||||
|
snap.assets[0]!.svg,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('buildSheetSnapshot on the slice', () => {
|
||||||
|
it('copies review_status and requires_vet_referral, skips an asset it has no text for', () => {
|
||||||
|
const snapshot = sliceSnapshot()
|
||||||
|
const hip = snapshot.document.finding_zones.find((z) => z.id === 'hip')!
|
||||||
|
expect(hip.categories.map((c) => c.id)).toEqual(['hip-dysfunctions'])
|
||||||
|
expect(hip.categories[0]!.review_status).toBe('inherited')
|
||||||
|
expect(hip.categories[0]!.children[0]!.children.map((n) => n.id)).toEqual([
|
||||||
|
'restriction-flexion',
|
||||||
|
])
|
||||||
|
const sphenoid = snapshot.document.finding_zones.find(
|
||||||
|
(z) => z.id === 'sphenoid',
|
||||||
|
)!
|
||||||
|
expect(sphenoid.categories[0]!.children[0]!.children[0]).toMatchObject({
|
||||||
|
id: 'torsion-right',
|
||||||
|
requires_vet_referral: false,
|
||||||
|
})
|
||||||
|
expect(snapshot.assets).toEqual([
|
||||||
|
{ svgAssetId: HORSE_MAIN_ASSET_ID, sha256: HASH, svg: SVG },
|
||||||
|
])
|
||||||
|
const noHash = { ...sliceSource(), assetHashes: undefined }
|
||||||
|
expect(
|
||||||
|
buildSheetSnapshot(noHash, sliceReport()).assets[0]!.sha256,
|
||||||
|
).toBeNull()
|
||||||
|
const noSvg = { ...sliceSource(), assets: {} }
|
||||||
|
expect(buildSheetSnapshot(noSvg, sliceReport()).assets).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('assertSnapshot', () => {
|
||||||
|
it('accepts the slice snapshot and returns the parsed copy', () => {
|
||||||
|
const snapshot = sliceSnapshot()
|
||||||
|
const parsed = assertSnapshot(JSON.parse(JSON.stringify(snapshot)))
|
||||||
|
expect(parsed).toEqual(snapshot)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects a finding tree deeper than the cap before parsing anything (caps)', () => {
|
||||||
|
let node: unknown = { id: 'leaf' }
|
||||||
|
for (let depth = 0; depth < SNAPSHOT_CAPS.findingDepth; depth += 1) {
|
||||||
|
node = { id: `n${depth}`, children: [node] }
|
||||||
|
}
|
||||||
|
const raw = {
|
||||||
|
garbage: true,
|
||||||
|
document: { finding_zones: [{ categories: [node] }] },
|
||||||
|
}
|
||||||
|
expect(rejection(raw)).toBe('caps')
|
||||||
|
const shallow = {
|
||||||
|
document: { finding_zones: [{ categories: [{ id: 'c' }] }] },
|
||||||
|
}
|
||||||
|
expect(rejection(shallow)).toBe('schema')
|
||||||
|
expect(rejection({ document: { finding_zones: 'x' } })).toBe('schema')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects shape faults (schema): unknown key, missing field, too many assets, non-object', () => {
|
||||||
|
expect(rejection({ ...sliceSnapshot(), extra: 1 })).toBe('schema')
|
||||||
|
const noStatus: Partial<SheetSnapshot> = sliceSnapshot()
|
||||||
|
delete noStatus.status
|
||||||
|
expect(rejection(noStatus)).toBe('schema')
|
||||||
|
const many = sliceSnapshot()
|
||||||
|
many.assets = Array.from({ length: 5 }, (_, i) => ({
|
||||||
|
svgAssetId: `00000000-0000-4000-8000-00000000000${i}`,
|
||||||
|
sha256: null,
|
||||||
|
svg: SVG,
|
||||||
|
}))
|
||||||
|
expect(rejection(many)).toBe('schema')
|
||||||
|
expect(rejection(null)).toBe('schema')
|
||||||
|
expect(rejection('snapshot')).toBe('schema')
|
||||||
|
expect(rejection([sliceSnapshot()])).toBe('schema')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects a __proto__ key without polluting anything', () => {
|
||||||
|
const raw = JSON.parse(
|
||||||
|
JSON.stringify(sliceSnapshot()).replace(
|
||||||
|
'"status"',
|
||||||
|
'"__proto__":{"polluted":1},"status"',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
expect(rejection(raw)).toBe('schema')
|
||||||
|
expect(({} as { polluted?: number }).polluted).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects counts over the caps (caps)', () => {
|
||||||
|
const views = sliceSnapshot()
|
||||||
|
views.document.views.push(
|
||||||
|
...Array.from({ length: SNAPSHOT_CAPS.views }, (_, i) => ({
|
||||||
|
...views.document.views[1]!,
|
||||||
|
id: `extra-${i}`,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
expect(rejection(views)).toBe('caps')
|
||||||
|
|
||||||
|
const annotations = sliceSnapshot()
|
||||||
|
annotations.document.annotations.push(
|
||||||
|
...Array.from({ length: SNAPSHOT_CAPS.annotations }, (_, i) => ({
|
||||||
|
...annotations.document.annotations[0]!,
|
||||||
|
id: `extra-${i}`,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
expect(rejection(annotations)).toBe('caps')
|
||||||
|
|
||||||
|
const nodes = sliceSnapshot()
|
||||||
|
const category = nodes.document.finding_zones[0]!.categories[0]!
|
||||||
|
category.children = Array.from(
|
||||||
|
{ length: SNAPSHOT_CAPS.findingNodes },
|
||||||
|
(_, i) => ({
|
||||||
|
id: `leaf-${i}`,
|
||||||
|
name: { fr: 'x', en: 'x' },
|
||||||
|
description: {},
|
||||||
|
requires_vet_referral: false,
|
||||||
|
reference_ids: [],
|
||||||
|
review_status: 'inherited',
|
||||||
|
children: [],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(rejection(nodes)).toBe('caps')
|
||||||
|
|
||||||
|
const label = sliceSnapshot()
|
||||||
|
label.document.name.fr = 'x'.repeat(SNAPSHOT_CAPS.labelChars + 1)
|
||||||
|
expect(rejection(label)).toBe('caps')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects oversize assets in bytes, single and total (caps)', () => {
|
||||||
|
const big = sliceSnapshot()
|
||||||
|
// 1.1M two-byte code points: under the schema's char cap, over 2 MiB.
|
||||||
|
big.assets[0]!.svg = 'é'.repeat(1_100_000)
|
||||||
|
expect(rejection(big)).toBe('caps')
|
||||||
|
|
||||||
|
const total = sliceSnapshot()
|
||||||
|
total.assets = Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
svgAssetId:
|
||||||
|
i === 0
|
||||||
|
? HORSE_MAIN_ASSET_ID
|
||||||
|
: `00000000-0000-4000-8000-00000000000${i}`,
|
||||||
|
sha256: null,
|
||||||
|
svg: 'a'.repeat(1_600_000),
|
||||||
|
}))
|
||||||
|
expect(rejection(total)).toBe('caps')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects integrity faults: a sheet rule error, a view reaching no carried asset', () => {
|
||||||
|
const rule = sliceSnapshot()
|
||||||
|
rule.document.finding_zones = rule.document.finding_zones.filter(
|
||||||
|
(z) => z.id !== 'atm',
|
||||||
|
)
|
||||||
|
expect(rejection(rule)).toBe('integrity')
|
||||||
|
|
||||||
|
const noAsset = sliceSnapshot()
|
||||||
|
noAsset.assets = []
|
||||||
|
expect(rejection(noAsset)).toBe('integrity')
|
||||||
|
|
||||||
|
const otherAsset = sliceSnapshot()
|
||||||
|
otherAsset.assets[0]!.svgAssetId = '00000000-0000-4000-8000-000000000009'
|
||||||
|
expect(rejection(otherAsset)).toBe('integrity')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { join, resolve } from 'node:path'
|
||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
ReportMigrationMapSchema,
|
||||||
|
type ReportMigrationMap,
|
||||||
|
type SnapshotSource,
|
||||||
|
} from '../../src'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The committed equine draft (`pnpm import:equine`) as the application
|
||||||
|
* bundles it: document, reference, SVG assets and their manifest hashes,
|
||||||
|
* plus the v2 → v3 migration map. Read from the seed, never copied.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const DRAFT_DIR = resolve(
|
||||||
|
fileURLToPath(import.meta.url),
|
||||||
|
'../../../../../supabase/seed/anatomical-sheets/equine/draft',
|
||||||
|
)
|
||||||
|
|
||||||
|
interface SeedRef {
|
||||||
|
sheet_id: string
|
||||||
|
version_id: string | null
|
||||||
|
document_sha256: string
|
||||||
|
schema_version: number
|
||||||
|
species_id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SeedAsset {
|
||||||
|
file: string
|
||||||
|
sha256: string
|
||||||
|
svg_asset_id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function json<T>(name: string): T {
|
||||||
|
return JSON.parse(readFileSync(join(DRAFT_DIR, name), 'utf8')) as T
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DraftSheet extends SnapshotSource {
|
||||||
|
assetHashes: Readonly<Record<string, string>>
|
||||||
|
migrationMap: ReportMigrationMap
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadDraftSheet(): DraftSheet {
|
||||||
|
const ref = json<SeedRef>('sheet-ref.json')
|
||||||
|
const manifest = json<SeedAsset[]>('assets.json')
|
||||||
|
const assets: Record<string, string> = {}
|
||||||
|
const assetHashes: Record<string, string> = {}
|
||||||
|
for (const asset of manifest) {
|
||||||
|
assets[asset.svg_asset_id] = readFileSync(
|
||||||
|
join(DRAFT_DIR, 'assets', asset.file),
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
assetHashes[asset.svg_asset_id] = asset.sha256
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: 'draft',
|
||||||
|
ref: {
|
||||||
|
sheetId: ref.sheet_id,
|
||||||
|
versionId: ref.version_id,
|
||||||
|
documentSha256: ref.document_sha256,
|
||||||
|
},
|
||||||
|
speciesId: ref.species_id,
|
||||||
|
schemaVersion: ref.schema_version,
|
||||||
|
document: AnatomicalSheetDocumentSchema.parse(json('document.json')),
|
||||||
|
assets,
|
||||||
|
assetHashes,
|
||||||
|
migrationMap: ReportMigrationMapSchema.parse(
|
||||||
|
json('report-migration-map.json'),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { resolve } from 'node:path'
|
||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
ReportV2Schema,
|
||||||
|
type AnatomicalSheetDocument,
|
||||||
|
type FindingCategory,
|
||||||
|
type FindingNode,
|
||||||
|
type ObservationV2,
|
||||||
|
type ReportV2,
|
||||||
|
} from '../../src'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The legacy catalog as the application's archive knew it: every leaf of the
|
||||||
|
* generated baseline (`legacy-import/document.json`) becomes a Report v2
|
||||||
|
* finding, grouped in one observation per zone. Same recipe as the app and
|
||||||
|
* anatomy helpers; migrated through the draft map it yields the unresolved
|
||||||
|
* items (sphenoid / ssb leaves) a Phase 0 golden was frozen with.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BASELINE = resolve(
|
||||||
|
fileURLToPath(import.meta.url),
|
||||||
|
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
|
||||||
|
)
|
||||||
|
|
||||||
|
export interface LegacyLeaf {
|
||||||
|
zoneId: string
|
||||||
|
path: string[]
|
||||||
|
name: { fr: string; en: string }
|
||||||
|
vet: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadLegacyBaseline(): AnatomicalSheetDocument {
|
||||||
|
return AnatomicalSheetDocumentSchema.parse(
|
||||||
|
JSON.parse(readFileSync(BASELINE, 'utf8')),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
|
||||||
|
const out: LegacyLeaf[] = []
|
||||||
|
const walk = (
|
||||||
|
zoneId: string,
|
||||||
|
nodes: readonly (FindingCategory | FindingNode)[],
|
||||||
|
prefix: string[],
|
||||||
|
) => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
const path = [...prefix, node.id]
|
||||||
|
if (node.children.length > 0) walk(zoneId, node.children, path)
|
||||||
|
else {
|
||||||
|
const vet =
|
||||||
|
'requires_vet_referral' in node && node.requires_vet_referral
|
||||||
|
out.push({ zoneId, path, name: node.name, vet })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||||
|
const byZone = new Map<string, ObservationV2>()
|
||||||
|
for (const leaf of leaves) {
|
||||||
|
let obs = byZone.get(leaf.zoneId)
|
||||||
|
if (!obs) {
|
||||||
|
obs = {
|
||||||
|
id: `obs-${leaf.zoneId}`,
|
||||||
|
zones: [],
|
||||||
|
findings: [],
|
||||||
|
freeTextFindings: [],
|
||||||
|
comment: '',
|
||||||
|
}
|
||||||
|
byZone.set(leaf.zoneId, obs)
|
||||||
|
}
|
||||||
|
obs.findings.push({
|
||||||
|
zoneId: leaf.zoneId,
|
||||||
|
path: leaf.path,
|
||||||
|
labelFrSnapshot: leaf.name.fr,
|
||||||
|
labelEnSnapshot: leaf.name.en || leaf.name.fr,
|
||||||
|
...(leaf.vet ? { requiresVetReferral: true } : {}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return ReportV2Schema.parse({
|
||||||
|
version: 2,
|
||||||
|
id: 'all-leaves',
|
||||||
|
createdAt: '2026-10-10T00:00:00Z',
|
||||||
|
date: '2026-10-10',
|
||||||
|
practitioner: { name: 'Synthetic' },
|
||||||
|
animal: { speciesId: 'equine', name: 'Synthetic' },
|
||||||
|
owner: { name: 'Synthetic' },
|
||||||
|
observations: [...byZone.values()],
|
||||||
|
conclusion: '',
|
||||||
|
recommendations: '',
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
REPORT_VERSION,
|
||||||
|
ReportSchema,
|
||||||
|
buildSheetIndex,
|
||||||
|
buildSheetSnapshot,
|
||||||
|
rebaseReportOnSheet,
|
||||||
|
type AnatomicalSheetDocument,
|
||||||
|
type Report,
|
||||||
|
type SheetRef,
|
||||||
|
type SnapshotSource,
|
||||||
|
} from '../src'
|
||||||
|
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
|
||||||
|
|
||||||
|
const SHA_A = 'a'.repeat(64)
|
||||||
|
const SHA_B = 'b'.repeat(64)
|
||||||
|
const REF_A: SheetRef = {
|
||||||
|
sheetId: 'sheet-1',
|
||||||
|
versionId: null,
|
||||||
|
documentSha256: SHA_A,
|
||||||
|
}
|
||||||
|
const REF_B: SheetRef = {
|
||||||
|
sheetId: 'sheet-1',
|
||||||
|
versionId: 'v2',
|
||||||
|
documentSha256: SHA_B,
|
||||||
|
}
|
||||||
|
|
||||||
|
function source(
|
||||||
|
ref: SheetRef,
|
||||||
|
document: AnatomicalSheetDocument,
|
||||||
|
): SnapshotSource {
|
||||||
|
return {
|
||||||
|
status: 'draft',
|
||||||
|
ref,
|
||||||
|
speciesId: 'equine',
|
||||||
|
schemaVersion: 2,
|
||||||
|
document,
|
||||||
|
assets: { [HORSE_MAIN_ASSET_ID]: '<svg/>' },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Revision B: the TMJ marker and the head trigger are gone, hip lost its articular node. */
|
||||||
|
function revisionB(): AnatomicalSheetDocument {
|
||||||
|
const doc = horseSlice()
|
||||||
|
doc.annotations = doc.annotations.filter(
|
||||||
|
(a) => a.id !== 'atm' && a.id !== 'head-trigger',
|
||||||
|
)
|
||||||
|
const hip = doc.finding_zones.find((z) => z.id === 'hip')!
|
||||||
|
hip.categories[0]!.children = hip.categories[0]!.children.filter(
|
||||||
|
(n) => n.id !== 'articular',
|
||||||
|
)
|
||||||
|
return doc
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportOnA(): Report {
|
||||||
|
return {
|
||||||
|
version: REPORT_VERSION,
|
||||||
|
id: 'r1',
|
||||||
|
createdAt: '2026-10-10T10:00:00Z',
|
||||||
|
date: '2026-10-10',
|
||||||
|
practitioner: { name: 'Dr. Dupont' },
|
||||||
|
animal: { speciesId: 'equine', name: 'Mistral' },
|
||||||
|
owner: { name: 'Jean Martin' },
|
||||||
|
sheet: REF_A,
|
||||||
|
observations: [
|
||||||
|
{
|
||||||
|
id: 'obs-1',
|
||||||
|
zones: [
|
||||||
|
{
|
||||||
|
annotationId: 'hip',
|
||||||
|
viewId: 'view-main',
|
||||||
|
side: 'left',
|
||||||
|
labelFrSnapshot: 'Hanche (coxo-fémorale)',
|
||||||
|
labelEnSnapshot: 'Hip joint',
|
||||||
|
},
|
||||||
|
{ annotationId: 'atm', viewId: 'view-head' },
|
||||||
|
{ annotationId: 'head-trigger', viewId: 'view-main' },
|
||||||
|
{
|
||||||
|
annotationId: 'hip',
|
||||||
|
viewId: 'ghost-view',
|
||||||
|
labelFrSnapshot: 'Gardé',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
annotationId: 'gone-long-ago',
|
||||||
|
viewId: 'view-main',
|
||||||
|
labelFrSnapshot: 'Ancien',
|
||||||
|
unresolved: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
findings: [
|
||||||
|
{
|
||||||
|
findingZoneId: 'hip',
|
||||||
|
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
|
||||||
|
labelFrSnapshot: 'Restriction en flexion',
|
||||||
|
labelEnSnapshot: 'Flexion restriction',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
findingZoneId: 'cervical',
|
||||||
|
path: ['cervical-observations', 'stumbling-proprioceptive'],
|
||||||
|
labelFrSnapshot: 'Trébuchements',
|
||||||
|
labelEnSnapshot: 'Stumbling',
|
||||||
|
requiresVetReferral: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
findingZoneId: 'atm',
|
||||||
|
path: ['atm-observations', 'headshaking'],
|
||||||
|
labelFrSnapshot: 'Headshaking',
|
||||||
|
labelEnSnapshot: 'Headshaking',
|
||||||
|
unresolved: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
freeTextFindings: ['note'],
|
||||||
|
severity: 'moderate',
|
||||||
|
comment: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
conclusion: 'c',
|
||||||
|
recommendations: 'r',
|
||||||
|
localAnnotations: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indexA = buildSheetIndex(source(REF_A, horseSlice()))
|
||||||
|
const indexB = buildSheetIndex(source(REF_B, revisionB()))
|
||||||
|
|
||||||
|
describe('rebaseReportOnSheet', () => {
|
||||||
|
it('returns the report untouched when it already sits on the loaded sheet', () => {
|
||||||
|
const report = reportOnA()
|
||||||
|
const outcome = rebaseReportOnSheet(report, indexA, null)
|
||||||
|
expect(outcome).toEqual({
|
||||||
|
report,
|
||||||
|
unresolvedZones: 0,
|
||||||
|
unresolvedFindings: 0,
|
||||||
|
rebased: false,
|
||||||
|
})
|
||||||
|
expect(outcome.report).toBe(report)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('flags what the new sheet lost, labels it from the archive, keeps the rest', () => {
|
||||||
|
const report = reportOnA()
|
||||||
|
const archived = buildSheetSnapshot(source(REF_A, horseSlice()), report)
|
||||||
|
const outcome = rebaseReportOnSheet(report, indexB, archived)
|
||||||
|
expect(outcome.rebased).toBe(true)
|
||||||
|
expect(outcome.unresolvedZones).toBe(3)
|
||||||
|
expect(outcome.unresolvedFindings).toBe(1)
|
||||||
|
expect(outcome.report.sheet).toEqual(REF_B)
|
||||||
|
expect(() => ReportSchema.parse(outcome.report)).not.toThrow()
|
||||||
|
|
||||||
|
const [hip, atm, trigger, ghostView, old] =
|
||||||
|
outcome.report.observations[0]!.zones
|
||||||
|
expect(hip).toEqual(report.observations[0]!.zones[0])
|
||||||
|
expect(atm).toEqual({
|
||||||
|
annotationId: 'atm',
|
||||||
|
viewId: 'view-head',
|
||||||
|
unresolved: true,
|
||||||
|
labelFrSnapshot: 'Articulation Temporo-Mandibulaire (ATM)',
|
||||||
|
labelEnSnapshot: 'Temporomandibular Joint (TMJ)',
|
||||||
|
})
|
||||||
|
expect(trigger).toEqual({
|
||||||
|
annotationId: 'head-trigger',
|
||||||
|
viewId: 'view-main',
|
||||||
|
unresolved: true,
|
||||||
|
labelFrSnapshot: 'Tête',
|
||||||
|
labelEnSnapshot: 'Head',
|
||||||
|
})
|
||||||
|
expect(ghostView).toEqual({
|
||||||
|
annotationId: 'hip',
|
||||||
|
viewId: 'ghost-view',
|
||||||
|
unresolved: true,
|
||||||
|
labelFrSnapshot: 'Gardé',
|
||||||
|
labelEnSnapshot: 'Hip joint',
|
||||||
|
})
|
||||||
|
expect(old).toEqual(report.observations[0]!.zones[4])
|
||||||
|
|
||||||
|
const [flexion, stumbling, headshaking] =
|
||||||
|
outcome.report.observations[0]!.findings
|
||||||
|
expect(flexion).toEqual({
|
||||||
|
...report.observations[0]!.findings[0],
|
||||||
|
unresolved: true,
|
||||||
|
})
|
||||||
|
expect(stumbling).toEqual(report.observations[0]!.findings[1])
|
||||||
|
expect(headshaking).toEqual(report.observations[0]!.findings[2])
|
||||||
|
expect(outcome.report.observations[0]!.freeTextFindings).toEqual(['note'])
|
||||||
|
expect(report).toEqual(reportOnA())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fills no label without an archived snapshot', () => {
|
||||||
|
const outcome = rebaseReportOnSheet(reportOnA(), indexB, null)
|
||||||
|
expect(outcome.report.observations[0]!.zones[1]).toEqual({
|
||||||
|
annotationId: 'atm',
|
||||||
|
viewId: 'view-head',
|
||||||
|
unresolved: true,
|
||||||
|
})
|
||||||
|
expect(outcome.unresolvedZones).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('counts nothing twice: a rebased report rebased again onto the same sheet is stable', () => {
|
||||||
|
const first = rebaseReportOnSheet(reportOnA(), indexB, null)
|
||||||
|
const second = rebaseReportOnSheet(
|
||||||
|
{ ...first.report, sheet: REF_A },
|
||||||
|
indexB,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
expect(second.unresolvedZones).toBe(0)
|
||||||
|
expect(second.unresolvedFindings).toBe(0)
|
||||||
|
expect(second.report).toEqual(first.report)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
buildSheetIndex,
|
||||||
|
isObservable,
|
||||||
|
pickLabel,
|
||||||
|
type SheetIndexSource,
|
||||||
|
} from '../src'
|
||||||
|
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
|
||||||
|
|
||||||
|
const SHA = 'a'.repeat(64)
|
||||||
|
|
||||||
|
function source() {
|
||||||
|
return {
|
||||||
|
ref: { documentSha256: SHA },
|
||||||
|
document: horseSlice(),
|
||||||
|
assets: { [HORSE_MAIN_ASSET_ID]: '<svg/>' },
|
||||||
|
extra: 'kept by the index',
|
||||||
|
} satisfies SheetIndexSource & { extra: string }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('buildSheetIndex', () => {
|
||||||
|
it('keeps the source as given, typed as the caller passed it', () => {
|
||||||
|
const index = buildSheetIndex(source())
|
||||||
|
expect(index.sheet.extra).toBe('kept by the index')
|
||||||
|
expect(index.sheet.ref.documentSha256).toBe(SHA)
|
||||||
|
expect(index.mainView.id).toBe('view-main')
|
||||||
|
expect(index.view('view-head')?.kind).toBe('detail')
|
||||||
|
expect(index.view('nowhere')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('looks up annotations, zones, regions and spine markers by id', () => {
|
||||||
|
const index = buildSheetIndex(source())
|
||||||
|
expect(index.annotation('hip')?.kind).toBe('point')
|
||||||
|
expect(index.annotationsOfView('view-head').map((a) => a.id)).toContain(
|
||||||
|
'atm',
|
||||||
|
)
|
||||||
|
expect(index.findingZone('cervical')?.name.en).toBe('Cervical Vertebrae')
|
||||||
|
expect(index.regions().map((r) => r.code)).toEqual([
|
||||||
|
'C',
|
||||||
|
'T',
|
||||||
|
'L',
|
||||||
|
'S',
|
||||||
|
'Cd',
|
||||||
|
])
|
||||||
|
expect(index.region('Cd')?.count_range).toEqual({ min: 15, max: 21 })
|
||||||
|
expect(index.spineAnnotation('C', 'view-main')?.id).toBe(
|
||||||
|
'cervical-vertebrae',
|
||||||
|
)
|
||||||
|
expect(index.spineAnnotation('C', 'view-head')).toBeUndefined()
|
||||||
|
expect(index.isSpine('cervical-vertebrae')).toBe(true)
|
||||||
|
expect(index.isSpine('hip')).toBe(false)
|
||||||
|
expect(index.isSpine('head-trigger')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resolves finding paths and reports absent ones', () => {
|
||||||
|
const index = buildSheetIndex(source())
|
||||||
|
expect(
|
||||||
|
index.nodeAt('hip', [
|
||||||
|
'hip-dysfunctions',
|
||||||
|
'articular',
|
||||||
|
'restriction-flexion',
|
||||||
|
])?.name.fr,
|
||||||
|
).toBe('Restriction en flexion')
|
||||||
|
expect(index.nodeAt('hip', ['hip-dysfunctions'])?.name.fr).toBe(
|
||||||
|
'Dysfonctions ostéopathiques',
|
||||||
|
)
|
||||||
|
expect(index.nodeAt('hip', ['hip-dysfunctions', 'ghost'])).toBeUndefined()
|
||||||
|
expect(index.nodeAt('nowhere', ['x'])).toBeUndefined()
|
||||||
|
expect(index.nodeAt('hip', [])).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('names a nameless trigger after the view it opens', () => {
|
||||||
|
const index = buildSheetIndex(source())
|
||||||
|
expect(index.name(index.annotation('head-trigger')!)).toEqual({
|
||||||
|
fr: 'Tête',
|
||||||
|
en: 'Head',
|
||||||
|
})
|
||||||
|
expect(index.name(index.annotation('hip')!).en).toBe('Hip joint')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a document without a main view', () => {
|
||||||
|
const src = source()
|
||||||
|
src.document.views = src.document.views.filter((v) => v.kind !== 'main')
|
||||||
|
expect(() => buildSheetIndex(src)).toThrow('no main view')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('pickLabel / isObservable', () => {
|
||||||
|
it('falls back to the other locale and to the empty string', () => {
|
||||||
|
expect(pickLabel({ fr: 'Hanche', en: 'Hip' }, 'fr')).toBe('Hanche')
|
||||||
|
expect(pickLabel({ fr: 'Hanche', en: 'Hip' }, 'en')).toBe('Hip')
|
||||||
|
expect(pickLabel({ fr: 'Hanche', en: '' }, 'en')).toBe('Hanche')
|
||||||
|
expect(pickLabel({ fr: '', en: 'Hip' }, 'fr')).toBe('Hip')
|
||||||
|
expect(pickLabel(null, 'fr')).toBe('')
|
||||||
|
expect(pickLabel(undefined, 'en')).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tells observable annotations from triggers', () => {
|
||||||
|
const index = buildSheetIndex(source())
|
||||||
|
expect(isObservable(index.annotation('hip'))).toBe(true)
|
||||||
|
expect(isObservable(index.annotation('head-trigger'))).toBe(false)
|
||||||
|
expect(isObservable(undefined)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user