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,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]),
|
||||
),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user