fix(pdf,tests): report:compare escapes control characters, prints names and free text only with --full, stats before read, missing file as a per-file failure; inferRegionCode regression test; import.ts JSDoc reattached

This commit is contained in:
bchanot committed 2026-10-10 15:53:07 +02:00
1 parent dc78a00835
commit b1b3e4927e
6 files changed
+257 -72

No files matched your search

+74 -40
View File
@@ -22,8 +22,8 @@ export const UNRESOLVED = '!! UNRESOLVED'
export interface CompareOptions {
locale: Locale
/** Print practitioner, animal and owner names (off by default). */
identity: boolean
/** Print names and the real free texts (off by default: placeholders). */
full: boolean
}
export interface Comparison {
@@ -45,22 +45,47 @@ export interface Counts {
unresolvedFindings: number
}
const q = (text: string) => `"${text}"`
/**
* Escapes C0, DEL and C1 control characters as `\uXXXX` (newline and
* carriage return included): a PDF is untrusted, and a raw escape sequence
* printed to a terminal can rewrite the screen or fake a line.
*/
export function esc(text: string): string {
return text.replace(
/[\u0000-\u001f\u007f-\u009f]/g,
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`,
)
}
const q = (text: string) => `"${esc(text)}"`
function zoneRef(z: { annotationId: string; viewId: string; side?: string }) {
return `${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`
return esc(`${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`)
}
function findingRef(f: { findingZoneId: string; path: readonly string[] }) {
return findingPathKey(f.findingZoneId, f.path)
return esc(findingPathKey(f.findingZoneId, f.path))
}
function vertebraeOf(z: { vertebrae?: { region: string; index: number }[] }) {
return z.vertebrae?.length
? ` [${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')}]`
? ` [${z.vertebrae.map((v) => esc(`${v.region}${v.index}`)).join(', ')}]`
: ''
}
/** Free-text lines: the texts with `full`, else only how many there are. */
function textLines(texts: readonly string[], full: boolean): string[] {
if (texts.length === 0) return []
if (!full) return [`text (${texts.length} entries)`]
return texts.map((t) => `text ${q(t)}`)
}
/** A single free-text field: its content with `full`, else a placeholder. */
function fieldLine(label: string, value: string | undefined, full: boolean) {
if (!value) return []
return [full ? `${label} ${q(value)}` : `${label} (present)`]
}
/** A v3 zone against the sheet: current label, or why it cannot be shown. */
function describeZone(
z: ReportZone,
@@ -86,7 +111,7 @@ function describeFinding(
): string {
const snapshot = q(locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot)
const vet = f.requiresVetReferral ? ' (!)' : ''
const side = f.side ? ` ${f.side}` : ''
const side = f.side ? ` ${esc(f.side)}` : ''
const ref = `${findingRef(f)}${side}${vet}`
if (f.unresolved) {
return `${ref} ${snapshot} ${UNRESOLVED} kept with its snapshot`
@@ -107,7 +132,8 @@ function describeZoneMigration(
locale: Locale,
): string {
const side = legacy.side ? ` ${legacy.side}` : ''
const from = `${legacy.boneId}${legacy.detailSourceId ? '@' + legacy.detailSourceId : ''}${side}${vertebraeOf(legacy)}`
const detail = legacy.detailSourceId ? '@' + legacy.detailSourceId : ''
const from = `${esc(legacy.boneId + detail + side)}${vertebraeOf(legacy)}`
if (out.unresolved) {
return `${from} ${UNRESOLVED} unknown legacy id, kept as ${zoneRef(out)}`
}
@@ -125,22 +151,20 @@ function describeFindingMigration(
): string {
const map = sheet.sheet.migrationMap.finding_paths
const vet = legacy.requiresVetReferral ? ' (!)' : ''
const key = `${findingPathKey(legacy.zoneId, legacy.path)}${vet}`
const legacyKey = findingPathKey(legacy.zoneId, legacy.path)
const key = `${esc(legacyKey)}${vet}`
const snapshot = q(
locale === 'en' ? legacy.labelEnSnapshot : legacy.labelFrSnapshot,
)
if (out.unresolved) {
const why = Object.hasOwn(map, findingPathKey(legacy.zoneId, legacy.path))
const why = Object.hasOwn(map, legacyKey)
? 'removed from the sheet, kept with its label'
: 'never in the legacy catalog, kept with its label'
return `${key} ${snapshot} ${UNRESOLVED} ${why}`
}
const node = sheet.nodeAt(out.findingZoneId, out.path)
const label = node ? q(pickLabel(node.name, locale)) : '!! missing'
const target =
findingRef(out) === findingPathKey(legacy.zoneId, legacy.path)
? 'same'
: findingRef(out)
const target = findingRef(out) === esc(legacyKey) ? 'same' : findingRef(out)
return `${key} ${snapshot} → ${target} ${label}`
}
@@ -150,14 +174,14 @@ function observationLines(
opts: CompareOptions,
): string[] {
const lines = [
`[${obs.id}] severity ${obs.severity ?? 'none'}`,
`[${esc(obs.id)}] severity ${esc(obs.severity ?? 'none')}`,
...obs.zones.map((z) => `zone ${describeZone(z, sheet, opts.locale)}`),
...obs.findings.map(
(f) => `finding ${describeFinding(f, sheet, opts.locale)}`,
),
...obs.freeTextFindings.map((t) => `text ${q(t)}`),
...textLines(obs.freeTextFindings, opts.full),
...fieldLine('comment ', obs.comment, opts.full),
]
if (obs.comment) lines.push(`comment ${q(obs.comment)}`)
return lines
}
@@ -171,9 +195,9 @@ function migratedObservationLines(
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
? `${legacy.severity} → ${out.severity}`
? esc(`${legacy.severity} → ${out.severity}`)
: 'none'
const lines = [`[${legacy.id}] severity ${severity}`]
const lines = [`[${esc(legacy.id)}] severity ${severity}`]
legacy.zones.forEach((z, j) => {
const line = describeZoneMigration(z, out.zones[j]!, sheet, opts.locale)
lines.push(`zone ${line}`)
@@ -187,8 +211,8 @@ function migratedObservationLines(
)
lines.push(`finding ${line}`)
})
lines.push(...legacy.freeTextFindings.map((t) => `text ${q(t)}`))
if (legacy.comment) lines.push(`comment ${q(legacy.comment)}`)
lines.push(...textLines(legacy.freeTextFindings, opts.full))
lines.push(...fieldLine('comment ', legacy.comment, opts.full))
return lines
})
}
@@ -216,15 +240,15 @@ function headerLines(
report.sheet.sheetId === ref.sheetId &&
report.sheet.documentSha256 === ref.documentSha256
const sheetLine = sameSheet
? `sheet ${ref.sheetId} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${report.sheet.sheetId} !! written on another sheet document (sha ${report.sheet.documentSha256.slice(0, 12)}…)`
? `sheet ${esc(ref.sheetId)} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${esc(report.sheet.sheetId)} !! written on another sheet document (sha ${esc(report.sheet.documentSha256.slice(0, 12))}…)`
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
sheetLine,
`id ${report.id} · date ${report.date} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
`id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
if (opts.identity) {
if (opts.full) {
lines.push(
`practitioner ${q(report.practitioner.name)} · animal ${q(report.animal.name)} · owner ${q(report.owner.name)}`,
)
@@ -232,16 +256,19 @@ function headerLines(
return lines
}
function footerLines(report: Report): string[] {
const lines: string[] = []
if (report.conclusion) lines.push(`conclusion ${q(report.conclusion)}`)
if (report.recommendations) {
lines.push(`recommendations ${q(report.recommendations)}`)
}
if (report.nextAppointment) {
lines.push(`next appointment ${JSON.stringify(report.nextAppointment)}`)
}
return lines
function footerLines(report: Report, full: boolean): string[] {
const appointment = report.nextAppointment
return [
...fieldLine('conclusion', report.conclusion, full),
...fieldLine('recommendations', report.recommendations, full),
...(appointment
? [
full
? `next appointment ${esc(JSON.stringify(appointment))}`
: `next appointment (${appointment.kind})`,
]
: []),
]
}
/**
@@ -260,14 +287,20 @@ export function compareReport(
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
)
// A diff must see a lost conclusion: its lines always carry the full texts.
const fullOpts = { ...opts, full: true }
const normalized = [
...report.observations.flatMap((o) => observationLines(o, sheet, fullOpts)),
...footerLines(report, true),
]
return {
source,
header: headerLines(source, report, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
footer: footerLines(report),
normalized: [...v3Lines.flat(), ...footerLines(report)],
footer: footerLines(report, opts.full),
normalized,
counts: countsOf(report),
}
}
@@ -308,13 +341,13 @@ export function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
files: [],
locale: 'fr',
identity: false,
full: false,
summary: false,
diff: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]!
if (arg === '--identity') args.identity = true
if (arg === '--full') args.full = true
else if (arg === '--summary') args.summary = true
else if (arg === '--diff') args.diff = true
else if (arg === '--locale') {
@@ -323,7 +356,8 @@ export function parseArgs(argv: string[]): CliArgs {
throw new Error('--locale takes fr or en')
}
args.locale = value
} else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)
} else if (arg.startsWith('--'))
throw new Error(`unknown option ${esc(arg)}`)
else args.files.push(arg)
}
return args