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
@@ -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