feat(app): export and import through @faunosteo/pdf — snapshot, archived branding and labels, browser rasterizer, imported archive kept in session, explicit rebase with messages; legacy PDF modules removed

This commit is contained in:
bchanot committed 2026-10-11 13:32:14 +02:00
1 parent 20dafc0b00
commit 9bd5173a9c
43 files changed
+1492 -1989

No files matched your search

+3 -3
View File
@@ -180,9 +180,9 @@ faunosteo/
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/
│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts
│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ │ └─ branding.ts + browserRasterizer.ts ← public/ logos → Branding; Image/canvas Rasterizer adapter
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
│ └─ main.tsx
+1
View File
@@ -17,6 +17,7 @@
"dependencies": {
"@faunosteo/anatomy": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/pdf": "workspace:*",
"@faunosteo/supabase": "workspace:*",
"motion": "^11.11.17",
"pdf-lib": "^1.17.1",
+20 -8
View File
@@ -20,12 +20,14 @@ import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PDFDocument } from 'pdf-lib'
import {
readReportDocument,
REPORT_VERSION,
readArchiveDocument,
UnsupportedReportVersionError,
} from '@faunosteo/domain'
import { readAttachedDocument } from '../src/pdf/attachment'
import { MAX_PDF_BYTES } from '../src/pdf/import'
import {
ArchiveReadError,
MAX_PDF_BYTES,
readAttachedDocument,
} from '@faunosteo/pdf'
import { parseBundledSheet } from '../src/sheets/provider'
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
import {
@@ -87,23 +89,33 @@ async function compareFile(
const bytes = new Uint8Array(readFileSync(path))
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true })
const raw = await readAttachedDocument(pdf)
const version = (raw as { version: number }).version
try {
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, version !== REPORT_VERSION, sheet, args)
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, args)
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new Error(`report version ${version} cannot be read`)
// The version is a number or null: nothing of the attachment is echoed.
throw new Error(`report version ${err.foundVersion} cannot be read`)
}
throw err
}
}
/** The engine's typed read failures, worded without echoing the file. */
const READ_FAILURES: Record<ArchiveReadError['kind'], string> = {
invalid_pdf: 'not a readable PDF',
no_attachment: 'no Faunosteo attachment found',
attachment_stripped:
'attachment stripped (the PDF is stamped as a Faunosteo archive)',
incompatible_version: 'report version cannot be read',
}
/** A missing or unreadable file is a failed entry, not a crash. */
function failureReason(err: unknown): string {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT') return 'file not found'
if (code === 'EACCES') return 'file not readable'
if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind]
// JSON.parse messages echo a fragment of the attachment.
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
return err instanceof Error ? err.message : String(err)
+31 -10
View File
@@ -1,9 +1,9 @@
import {
ReportV2Schema,
findingPathKey,
type ArchiveReadOutcome,
type Finding,
type FindingV2,
type MigrationOutcome,
type ObservationZoneV2,
type Report,
type ReportZone,
@@ -15,7 +15,8 @@ import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
* Pure comparison of a report document found in a PDF with its v3 reading:
* a v2 archive is shown legacy id → canonical id line by line, a v3 report
* is checked against the bundled sheet. Every item the sheet cannot place is
* marked `!! UNRESOLVED` with the reason, nothing is summarised away.
* marked `!! UNRESOLVED` with the reason, nothing is summarised away. A Step 6
* envelope adds one header line saying whether its snapshot was kept.
*/
export const UNRESOLVED = '!! UNRESOLVED'
@@ -186,13 +187,22 @@ function observationLines(
return lines
}
/** The report document inside the attachment: the envelope's, or the bare one. */
function reportDataOf(raw: unknown): unknown {
const isEnvelope =
typeof raw === 'object' &&
raw !== null &&
typeof (raw as { envelopeVersion?: unknown }).envelopeVersion === 'number'
return isEnvelope ? (raw as { report: unknown }).report : raw
}
function migratedObservationLines(
raw: unknown,
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[][] {
const v2 = ReportV2Schema.parse(raw)
const v2 = ReportV2Schema.parse(reportDataOf(raw))
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
@@ -230,12 +240,22 @@ function countsOf(report: Report): Counts {
}
}
/** The envelope line: present only when the attachment was an archive. */
function archiveLine(outcome: ArchiveReadOutcome): string[] {
if (outcome.archive) return ['archive v1 (snapshot kept)']
if (outcome.snapshotRejected) {
return [`archive v1 (snapshot rejected: ${esc(outcome.snapshotRejected)})`]
}
return []
}
function headerLines(
source: 'v2' | 'v3',
report: Report,
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const { report } = outcome
const ref = sheet.sheet.ref
const sameSheet =
report.sheet.sheetId === ref.sheetId &&
@@ -246,6 +266,7 @@ function headerLines(
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
...archiveLine(outcome),
sheetLine,
`id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
@@ -273,17 +294,17 @@ function footerLines(report: Report, full: boolean): string[] {
}
/**
* `raw` is the attachment as found in the PDF, `outcome` its v3 reading
* (`readReportDocument`); `migrated` tells which vocabulary the lines use.
* `raw` is the attachment as found in the PDF (bare report or envelope),
* `outcome` its layered reading (`readArchiveDocument`); `outcome.migrated`
* tells which vocabulary the lines use.
*/
export function compareReport(
raw: unknown,
outcome: MigrationOutcome,
migrated: boolean,
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): Comparison {
const { report } = outcome
const { report, migrated } = outcome
const source = migrated ? 'v2' : 'v3'
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
@@ -295,7 +316,7 @@ export function compareReport(
]
return {
source,
header: headerLines(source, report, sheet, opts),
header: headerLines(source, outcome, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
+1 -2
View File
@@ -57,8 +57,7 @@ export default function EditorRoute() {
// No report in memory: restore the per-tab draft once the sheet is known.
useEffect(() => {
if (report) return
if (sheet.status === 'ready')
store.restoreDraft(sheet.index.sheet.migrationMap)
if (sheet.status === 'ready') store.restoreDraft(sheet.index)
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate])
+75 -35
View File
@@ -1,64 +1,104 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import {
rebaseReportOnSheet,
type ArchiveReadOutcome,
type RebaseOutcome,
} from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/**
* The lines of the one alert shown after a successful import (STEP6 §16):
* a lossy v2 migration, the archive kept, the snapshot dropped with its
* reason, the rebase onto the current sheet. Empty when nothing applies.
*/
function importMessages(
outcome: ArchiveReadOutcome,
rebase: RebaseOutcome,
t: Translate,
): string[] {
const lines: string[] = []
const lost = outcome.unresolvedFindings + outcome.unresolvedZones
if (outcome.migrated && lost > 0) {
lines.push(t('home.import.migrated').replace('{count}', String(lost)))
}
if (outcome.archive) lines.push(t('home.import.archive_ok'))
if (outcome.snapshotRejected) {
lines.push(
t('home.import.snapshot_rejected').replace(
'{reason}',
t(`home.import.snapshot_reason.${outcome.snapshotRejected}`),
),
)
}
if (rebase.rebased) {
const count = rebase.unresolvedZones + rebase.unresolvedFindings
lines.push(t('home.import.rebased').replace('{count}', String(count)))
}
return lines
}
/** The error line under the import button, by ImportError kind. */
function importErrorMessage(err: unknown, t: Translate): string {
if (!(err instanceof ImportError)) return t('home.import.error_generic')
switch (err.kind) {
case 'incompatible_version':
return t('home.import.error_incompatible_version').replace(
'{version}',
String(err.foundVersion ?? '?'),
)
case 'invalid_pdf':
return t('home.import.error_invalid_pdf')
case 'attachment_stripped':
return t('home.import.error_attachment_stripped')
case 'no_attachment':
return t('home.import.error_no_attachment')
}
}
export default function HomeRoute() {
const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null)
const hydrate = useReportStore((s) => s.hydrateReport)
const hydrateImport = useReportStore((s) => s.hydrateImport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
outcome.report,
index,
outcome.archive?.sheetSnapshot ?? null,
)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
navigate('/editor')
}
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file || sheet.status !== 'ready') return
setBusy(true)
setError(null)
try {
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(
bytes,
sheet.index.sheet.migrationMap,
)
if (
outcome.migrated &&
outcome.unresolvedFindings + outcome.unresolvedZones > 0
) {
window.alert(
t('home.import.migrated').replace(
'{count}',
String(outcome.unresolvedFindings + outcome.unresolvedZones),
),
)
}
hydrate(outcome.report)
navigate('/editor')
await importFile(file, sheet.index)
} catch (err) {
if (err instanceof ImportError) {
if (err.kind === 'incompatible_version') {
setError(
t('home.import.error_incompatible_version').replace(
'{version}',
String(err.foundVersion ?? '?'),
),
)
} else if (err.kind === 'invalid_pdf') {
setError(t('home.import.error_invalid_pdf'))
} else {
setError(t('home.import.error_no_attachment'))
}
} else {
setError(t('home.import.error_generic'))
}
setError(importErrorMessage(err, t))
} finally {
setBusy(false)
if (fileRef.current) fileRef.current.value = ''
+15 -19
View File
@@ -32,6 +32,21 @@ export const en: Dict = {
'This PDF uses format v{version}, which this version of the application cannot read (accepted formats: v2 and v3).',
'home.import.migrated':
'Report imported from an older format. Findings not found in the current sheet: {count} (kept with their labels).',
'home.import.archive_ok':
'Faunosteo archive imported: report and the original sheet snapshot kept.',
'home.import.snapshot_rejected':
'Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is.',
'home.import.snapshot_reason.unsupported_envelope':
'archive from a newer version',
'home.import.snapshot_reason.schema': 'invalid content',
'home.import.snapshot_reason.caps': 'size or complexity over the limits',
'home.import.snapshot_reason.integrity': 'inconsistent sheet',
'home.import.snapshot_reason.sheet_mismatch':
"sheet differs from the report's",
'home.import.rebased':
"Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels).",
'home.import.error_attachment_stripped':
'This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file.',
'home.no_sheet.title': 'No anatomical sheet',
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
@@ -150,25 +165,6 @@ export const en: Dict = {
'severity.moderate': 'moderate',
'severity.severe': 'severe',
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHESIS',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'FINDINGS — ',
'pdf.section.free_findings': 'FREE FINDINGS',
'pdf.section.severity': 'SEVERITY',
'pdf.section.comment': 'COMMENT',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMENDATIONS',
'pdf.section.next_appointment': 'NEXT APPOINTMENT',
'pdf.view.general': 'GENERAL VIEW',
'pdf.view.detail_prefix': 'DETAIL VIEW — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Owner: ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Osteo report — ',
'pdf.subject': 'Animal osteopathic report',
'lang.group_label': 'Language',
'lang.switch_to_fr': 'Passer en français',
'lang.switch_to_en': 'Switch to English',
+15 -20
View File
@@ -34,6 +34,21 @@ export const fr: Dict = {
"Ce PDF est au format v{version}, que cette version de l'application ne sait pas lire (formats acceptés : v2 et v3).",
'home.import.migrated':
'Bilan importé depuis un ancien format. Constats non retrouvés dans la fiche actuelle : {count} (conservés avec leurs libellés).',
'home.import.archive_ok':
"Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés.",
'home.import.snapshot_rejected':
"Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle.",
'home.import.snapshot_reason.unsupported_envelope':
"archive d'une version plus récente",
'home.import.snapshot_reason.schema': 'contenu invalide',
'home.import.snapshot_reason.caps': 'taille ou complexité excessive',
'home.import.snapshot_reason.integrity': 'fiche incohérente',
'home.import.snapshot_reason.sheet_mismatch':
'fiche différente de celle du bilan',
'home.import.rebased':
"Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés).",
'home.import.error_attachment_stripped':
"Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine.",
'home.no_sheet.title': 'Aucune fiche anatomique',
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
@@ -165,26 +180,6 @@ export const fr: Dict = {
'severity.moderate': 'modérée',
'severity.severe': 'sévère',
// pdf
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHÈSE',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'CONSTATS — ',
'pdf.section.free_findings': 'CONSTATS LIBRES',
'pdf.section.severity': 'SÉVÉRITÉ',
'pdf.section.comment': 'COMMENTAIRE',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMANDATIONS',
'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS',
'pdf.view.general': 'VUE GÉNÉRALE',
'pdf.view.detail_prefix': 'VUE DÉTAIL — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Propriétaire : ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Bilan ostéo — ',
'pdf.subject': "Bilan d'ostéopathie animalière",
// language switcher
'lang.group_label': 'Langue',
'lang.switch_to_fr': 'Passer en français',
-200
View File
@@ -1,200 +0,0 @@
import { AFRelationship, type PDFDocument } from 'pdf-lib'
import {
readReportDocument,
REPORT_VERSION,
UnsupportedReportVersionError,
type MigrationOutcome,
type Report,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* The report document travels inside the PDF as a native attachment.
* Written as v3; read back as v3, or as v2 migrated through the sheet's
* migration map (the practitioner's archive). Any other version is refused
* with the found version.
*/
const FILENAME = 'osteo-report.json'
export class IncompatibleReportVersionError extends Error {
constructor(public readonly foundVersion: number | null) {
super(`incompatible_version:${foundVersion ?? 'unknown'}`)
this.name = 'IncompatibleReportVersionError'
}
}
export async function attachReportJson(
pdfDoc: PDFDocument,
report: Report,
): Promise<void> {
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
await pdfDoc.attach(bytes, FILENAME, {
mimeType: 'application/json',
description: `Faunosteo state v${REPORT_VERSION}`,
creationDate: new Date(),
modificationDate: new Date(),
afRelationship: AFRelationship.Data,
})
}
export interface ExtractedReport extends MigrationOutcome {
/** True when the attachment was an older version lifted to v3. */
migrated: boolean
}
/**
* The raw report document carried by the PDF, of whatever version, before
* any migration: what the archive check tool shows next to the v3 result.
* Throws when the PDF carries no Faunosteo attachment or an oversized one.
*/
export async function readAttachedDocument(
pdfDoc: PDFDocument,
): Promise<unknown> {
const bytes = await attachmentBytes(pdfDoc)
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment too large')
}
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (versionOf(data) === null) {
throw new Error('attachment carries no report version')
}
return data
}
export async function extractReportJson(
pdfDoc: PDFDocument,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
const data = await readAttachedDocument(pdfDoc)
try {
return {
...readReportDocument(data, map),
migrated: versionOf(data) !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
}
async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {
const maybeApi = pdfDoc as unknown as {
getAttachments?: () => Array<{ name: string; data: Uint8Array }>
}
if (typeof maybeApi.getAttachments === 'function') {
const list = maybeApi.getAttachments()
if (list && list.length) {
const hit =
list.find(
(a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'),
) ?? list[0]
return hit.data
}
}
const fallback = await traverseForJsonAttachment(pdfDoc)
if (!fallback) throw new Error('No osteo-report attachment found')
return fallback
}
/** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */
const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
function versionOf(data: unknown): number | null {
if (data === null || typeof data !== 'object') return null
const v = (data as { version?: unknown }).version
return typeof v === 'number' ? v : null
}
interface RawObj {
contents?: Uint8Array
dict?: { entries?: () => Array<[unknown, unknown]> }
}
/**
* Hard ceiling on inflated attachment size. A valid report JSON is far
* smaller; anything bigger is a decompression bomb or corruption.
*/
const MAX_INFLATED_BYTES = MAX_ATTACHMENT_BYTES
/** Exported for tests. Returns null on failure or when the cap is exceeded. */
export async function inflateFlate(
bytes: Uint8Array,
): Promise<Uint8Array | null> {
if (typeof DecompressionStream === 'undefined') return null
try {
const stream = new Blob([bytes as BlobPart])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
const reader = stream.getReader()
const chunks: Uint8Array[] = []
let total = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
total += value.byteLength
if (total > MAX_INFLATED_BYTES) {
await reader.cancel()
return null
}
chunks.push(value)
}
const out = new Uint8Array(total)
let offset = 0
for (const c of chunks) {
out.set(c, offset)
offset += c.byteLength
}
return out
} catch {
return null
}
}
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
for (const [k, v] of entries) {
if (String(k).includes('Filter') && String(v).includes('FlateDecode'))
return true
}
return false
}
async function traverseForJsonAttachment(
pdfDoc: PDFDocument,
): Promise<Uint8Array | null> {
const ctx = (
pdfDoc as unknown as {
context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> }
}
).context
for (const [, obj] of ctx.enumerateIndirectObjects()) {
if (!obj || typeof obj !== 'object') continue
if (!(obj.contents instanceof Uint8Array)) continue
const entries = obj.dict?.entries?.() ?? []
let isEmbeddedFile = false
let isJsonSubtype = false
for (const [k, v] of entries) {
const ks = String(k)
const vs = String(v)
if (ks.includes('Type') && vs.includes('EmbeddedFile'))
isEmbeddedFile = true
// PDF name syntax escapes '/' as '#2F': /application#2Fjson
if (
ks.includes('Subtype') &&
(vs.includes('application/json') || vs.includes('application#2Fjson'))
) {
isJsonSubtype = true
}
}
if (!isEmbeddedFile && !isJsonSubtype) continue
if (dictHasFlateFilter(entries)) {
const inflated = await inflateFlate(obj.contents)
if (inflated) return inflated
}
return obj.contents
}
return null
}
+81
View File
@@ -0,0 +1,81 @@
import type { Branding, ImageAsset } from '@faunosteo/domain'
/**
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
* the four `public/` files fetched by their current URLs, each failure
* leaving its slot empty with a warning (the page then prints the credit's
* fallback text), plus the credit URLs. The result travels inside the
* archive, so a re-export never needs these files again.
*/
// shortcut: the site URL and the credit constants belong to the runtime
// config (ConfigProvider); they live here until AppConfig carries them.
const SITE_URL = 'https://faunosteo.com'
const POWERED_BY = {
url: 'https://zenquality.fr',
fallbackText: 'zenquality.fr',
}
const PARTNER = {
url: 'https://www.instagram.com/paws.iin.harmony',
fallbackText: '@paws.iin.harmony',
}
const HEADER_LOGO_URL = '/assets/faunosteo_logo_horizontal-512.png'
const FOOTER_LOGO_URL = '/assets/faunosteo-horizontal-com-512.png'
const POWERED_BY_LOGO_URL = '/brand/zenquality-logo-fr.png'
const PARTNER_LOGO_URL = '/Paws_in_harmony.svg'
/** btoa takes a binary string; chunking keeps the argument list small. */
function bytesToBase64(bytes: Uint8Array): string {
const CHUNK = 0x8000
let binary = ''
for (let i = 0; i < bytes.length; i += CHUNK) {
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
}
return btoa(binary)
}
async function fetchOk(url: string): Promise<Response> {
const resp = await fetch(url)
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
return resp
}
async function pngAsset(url: string): Promise<ImageAsset> {
const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer())
return { kind: 'png', base64: bytesToBase64(bytes) }
}
async function svgAsset(url: string): Promise<ImageAsset> {
return { kind: 'svg', svg: await (await fetchOk(url)).text() }
}
/** A slot fails alone: the export goes on without that logo. */
async function slot(
load: Promise<ImageAsset>,
url: string,
): Promise<ImageAsset | null> {
try {
return await load
} catch (err) {
console.warn(`Branding asset ${url} skipped:`, err)
return null
}
}
export async function loadBranding(): Promise<Branding> {
const [headerLogo, footerLogo, poweredByLogo, partnerLogo] =
await Promise.all([
slot(pngAsset(HEADER_LOGO_URL), HEADER_LOGO_URL),
slot(pngAsset(FOOTER_LOGO_URL), FOOTER_LOGO_URL),
slot(pngAsset(POWERED_BY_LOGO_URL), POWERED_BY_LOGO_URL),
slot(svgAsset(PARTNER_LOGO_URL), PARTNER_LOGO_URL),
])
return {
siteUrl: SITE_URL,
headerLogo,
footerLogo,
poweredBy: { logo: poweredByLogo, ...POWERED_BY },
partner: { logo: partnerLogo, ...PARTNER },
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { Rasterizer } from '@faunosteo/pdf'
/**
* The browser side of the engine's rasterizer adapter: the engine has fixed
* the pixel size, this module only stamps it on the SVG root and lets the
* browser draw the SVG through an Image / canvas pair, which renders exactly
* what the practitioner sees in the inline anatomy canvas.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte)
}
/** The root carries the namespace and the engine's size; nothing else changes. */
function sizedSvg(svg: string, widthPx: number, heightPx: number): string {
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
).documentElement
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
root.setAttribute('width', String(widthPx))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function loadImage(svg: string): Promise<HTMLImageElement> {
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
}).finally(() => URL.revokeObjectURL(url))
}
function drawOnWhiteCanvas(
img: HTMLImageElement,
widthPx: number,
heightPx: number,
): HTMLCanvasElement {
const canvas = document.createElement('canvas')
canvas.width = widthPx
canvas.height = heightPx
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
ctx.drawImage(img, 0, 0, widthPx, heightPx)
return canvas
}
function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
}
/** Fallback when toBlob yields nothing: decode the data URL by hand. */
function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array {
const dataUrl = canvas.toDataURL('image/png')
if (!dataUrl.startsWith('data:image/png')) {
throw new Error(
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
)
}
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned a data URL without a payload')
}
const binary = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
if (!startsWithPngSignature(bytes)) {
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
}
return bytes
}
async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {
const blob = await canvasBlob(canvas)
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
return pngFromDataUrl(canvas)
}
export const browserRasterizer: Rasterizer = async (
svg,
{ widthPx, heightPx },
) => {
const img = await loadImage(sizedSvg(svg, widthPx, heightPx))
return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx))
}
+21 -82
View File
@@ -1,97 +1,36 @@
import { PDFDocument } from 'pdf-lib'
import type { Report } from '@faunosteo/domain'
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import type { SheetIndex } from '@/services/sheetIndex'
import { embedFonts } from './fonts'
import { addObservationPage } from './render/observationPage'
import { addConclusionPage } from './render/conclusionPage'
import { attachReportJson } from './attachment'
import { drawFooter } from './render/footer'
import {
loadFaunosteoLogo,
loadFaunosteoComLogo,
loadZenqualityLogo,
} from './render/logo'
import { rasterizeSvg } from './render/svgToPng'
import { loadBranding } from './branding'
import { browserRasterizer } from './browserRasterizer'
export interface PdfExportOptions {
locale: Locale
}
/**
* Exports a report to PDF from the in-memory document and the loaded sheet:
* labels and drawings come from the sheet, nothing is fetched except the
* partner logos. The v3 document is attached for re-import.
* Exports the report as an archive PDF through the engine: the loaded sheet
* becomes the snapshot the pages are drawn from and the attachment carries,
* the branding is fetched once from `public/`, the browser rasterises the
* views. Non-fatal engine warnings (a logo or a view that failed) are logged.
*/
export async function exportReportToPdf(
report: Report,
sheet: SheetIndex,
index: SheetIndex,
opts: PdfExportOptions,
): Promise<Uint8Array> {
const { locale } = opts
const dict = getDict(locale)
const pdfDoc = await PDFDocument.create()
pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`)
pdfDoc.setAuthor(report.practitioner.name)
pdfDoc.setSubject(dict['pdf.subject'])
pdfDoc.setCreationDate(new Date())
pdfDoc.setModificationDate(new Date())
const fonts = await embedFonts(pdfDoc)
let headerLogoPdf = null
let footerLogoPdf = null
let zqLogoPdfImage = null
let pawsLogoPdf = null
try {
headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo())
} catch (err) {
console.warn('Faunosteo logo embed failed:', err)
}
try {
footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo())
} catch (err) {
console.warn('Faunosteo -com logo embed failed:', err)
}
try {
zqLogoPdfImage = await pdfDoc.embedPng(await loadZenqualityLogo())
} catch (err) {
console.warn('ZenQuality logo embed failed:', err)
}
try {
const resp = await fetch('/Paws_in_harmony.svg')
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text()))
} catch (err) {
console.warn('Paws in Harmony logo embed failed:', err)
}
const headerAssets = { logoPng: headerLogoPdf }
for (let i = 0; i < report.observations.length; i += 1) {
await addObservationPage({
pdfDoc,
report,
observation: report.observations[i]!,
obsIndex: i,
fonts,
sheet,
locale,
headerAssets,
})
}
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
const pages = pdfDoc.getPages()
const footerAssets = {
logoPng: footerLogoPdf,
zqLogoPng: zqLogoPdfImage,
pawsLogoPng: pawsLogoPdf,
}
pages.forEach((page, idx) => {
drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets)
const result = await exportReportArchive({
report,
sheet: buildSheetSnapshot(index.sheet, report),
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
rasterizer: browserRasterizer,
exportedAt: new Date(),
})
await attachReportJson(pdfDoc, report)
return pdfDoc.save()
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
}
return result.pdf
}
-16
View File
@@ -1,16 +0,0 @@
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
export interface EmbeddedFonts {
bodyRegular: PDFFont
bodyBold: PDFFont
headingRegular: PDFFont
}
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
pdfDoc.embedFont(StandardFonts.Helvetica),
pdfDoc.embedFont(StandardFonts.HelveticaBold),
pdfDoc.embedFont(StandardFonts.TimesRoman),
])
return { bodyRegular, bodyBold, headingRegular }
}
+17 -28
View File
@@ -1,15 +1,13 @@
import { PDFDocument } from 'pdf-lib'
import type { ReportMigrationMap } from '@faunosteo/domain'
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
import {
extractReportJson,
IncompatibleReportVersionError,
type ExtractedReport,
} from './attachment'
ArchiveReadError,
readReportArchive,
type ArchiveReadErrorKind,
} from '@faunosteo/pdf'
export type ImportErrorKind =
| 'invalid_pdf'
| 'incompatible_version'
| 'no_attachment'
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
export type ImportErrorKind = ArchiveReadErrorKind
/**
* Localization-agnostic import error. Carries a kind discriminant + an
@@ -26,31 +24,22 @@ export class ImportError extends Error {
}
}
/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
export const MAX_PDF_BYTES = 50 * 1024 * 1024
/**
* Reads a Faunosteo PDF back into a report document (v3, or v2 migrated
* through the reference sheet's map). The outcome says whether a migration
* happened and how many zones or findings it could not place.
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
* migrated through the sheet's map) and, when the file is a Step 6 archive,
* the validated envelope or the reason its snapshot was dropped. Engine
* failures become ImportError kinds, one to one.
*/
export async function importReportFromPdf(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
if (pdfBytes.byteLength > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
let pdfDoc: PDFDocument
): Promise<ArchiveReadOutcome> {
try {
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
} catch {
throw new ImportError('invalid_pdf')
}
try {
return await extractReportJson(pdfDoc, map)
return await readReportArchive(pdfBytes, map)
} catch (err) {
if (err instanceof IncompatibleReportVersionError) {
throw new ImportError('incompatible_version', err.foundVersion)
if (err instanceof ArchiveReadError) {
throw new ImportError(err.kind, err.foundVersion)
}
throw new ImportError('no_attachment')
throw err
}
}
-111
View File
@@ -1,111 +0,0 @@
import { PageSizes, type PDFDocument } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { drawHeader, type HeaderAssets } from './header'
import { wrapLines } from './text'
import { formatDate } from '@/lib/dates'
import {
MARGIN_X,
EYEBROW_Y_OFFSET,
TITLE_Y_OFFSET,
TITLE_RULE_OFFSET,
TITLE_RULE_WIDTH,
SECTION_LABEL_GAP,
COLOR_INK,
COLOR_MUTED,
COLOR_ACCENT,
} from './constants'
const SECTION_TOP_GAP = 28
const SECTION_BLOCK_GAP = 18
const TEXT_LINE_HEIGHT = 14
export async function addConclusionPage(
pdfDoc: PDFDocument,
report: Report,
fonts: EmbeddedFonts,
locale: Locale,
headerAssets: HeaderAssets,
): Promise<void> {
const dict = getDict(locale)
const page = pdfDoc.addPage(PageSizes.A4)
const { width, height } = page.getSize()
const max = width - MARGIN_X * 2
drawHeader(page, report, fonts, locale, headerAssets)
const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET
page.drawText(dict['pdf.eyebrow.synthesis'], {
x: MARGIN_X,
y: eyebrowY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
page.drawText(dict['pdf.title.conclusion'], {
x: MARGIN_X,
y: titleY,
size: 22,
font: fonts.headingRegular,
color: COLOR_INK,
})
page.drawLine({
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
thickness: 2,
color: COLOR_ACCENT,
})
let cursorY = titleY - SECTION_TOP_GAP
const sections: Array<{
label: string
body: string
color?: typeof COLOR_INK
}> = [
{
label: dict['pdf.section.conclusion'],
body: report.conclusion || dict['pdf.empty'],
},
{
label: dict['pdf.section.recommendations'],
body: report.recommendations || dict['pdf.empty'],
},
]
if (report.nextAppointment) {
const txt =
report.nextAppointment.kind === 'date'
? formatDate(report.nextAppointment.date, locale)
: report.nextAppointment.text
sections.push({
label: dict['pdf.section.next_appointment'],
body: txt || dict['pdf.empty'],
color: COLOR_MUTED,
})
}
for (const { label, body, color } of sections) {
page.drawText(label, {
x: MARGIN_X,
y: cursorY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
cursorY -= SECTION_LABEL_GAP + 10
wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
page.drawText(line, {
x: MARGIN_X,
y: cursorY,
size: 11,
font: fonts.bodyRegular,
color: color ?? COLOR_INK,
})
cursorY -= TEXT_LINE_HEIGHT
})
cursorY -= SECTION_BLOCK_GAP
}
}
-19
View File
@@ -1,19 +0,0 @@
import { rgb } from 'pdf-lib'
/**
* Layout and color constants shared across PDF page renderers (header,
* footer, observation page, conclusion page). Only values that are
* byte-identical across all callers live here — a same-named constant
* with a different value per file stays local to that file.
*/
export const MARGIN_X = 36
export const EYEBROW_Y_OFFSET = 95
export const TITLE_Y_OFFSET = 122
export const TITLE_RULE_OFFSET = 12
export const TITLE_RULE_WIDTH = 48
export const SECTION_LABEL_GAP = 4
export const COLOR_INK = rgb(0.12, 0.11, 0.09)
export const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
export const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
-180
View File
@@ -1,180 +0,0 @@
import { rgb, type PDFPage, type PDFImage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { addLinkAnnotation } from './linkAnnotation'
import { MARGIN_X, COLOR_MUTED } from './constants'
const FOOTER_BASE_Y = 20
const FONT_SIZE = 8
export interface FooterAssets {
logoPng: PDFImage | null
zqLogoPng: PDFImage | null
pawsLogoPng: PDFImage | null
}
export function drawFooter(
page: PDFPage,
fonts: EmbeddedFonts,
pageNumber: number,
totalPages: number,
locale: Locale,
assets: FooterAssets,
): void {
const dict = getDict(locale)
const { width } = page.getSize()
const accent = rgb(0.28, 0.56, 0.42)
const logoW = 80
const logoH = 30
const rowY = FOOTER_BASE_Y + 14
const separatorY = rowY + logoH + 6
page.drawLine({
start: { x: MARGIN_X, y: separatorY },
end: { x: width - MARGIN_X, y: separatorY },
thickness: 0.5,
color: rgb(0.85, 0.83, 0.8),
})
if (assets.logoPng) {
page.drawImage(assets.logoPng, {
x: MARGIN_X,
y: rowY,
width: logoW,
height: logoH,
})
addLinkAnnotation(page, {
x: MARGIN_X,
y: rowY,
width: logoW,
height: logoH,
url: 'https://faunosteo.com',
})
}
const poweredLabel = `${dict['footer.powered_by']} `
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(
poweredLabel,
FONT_SIZE,
)
const zqLogoW = 70
const zqLogoH = 16
const zqFallback = 'zenquality.fr'
const zqFallbackW = fonts.bodyRegular.widthOfTextAtSize(zqFallback, FONT_SIZE)
const poweredBlockW = assets.zqLogoPng
? poweredLabelW + zqLogoW
: poweredLabelW + zqFallbackW
const poweredX = (width - poweredBlockW) / 2
const textBaseY = rowY + 6
page.drawText(poweredLabel, {
x: poweredX,
y: textBaseY,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: COLOR_MUTED,
})
const zqX = poweredX + poweredLabelW
if (assets.zqLogoPng) {
page.drawImage(assets.zqLogoPng, {
x: zqX,
y: rowY + 2,
width: zqLogoW,
height: zqLogoH,
})
addLinkAnnotation(page, {
x: zqX,
y: rowY + 2,
width: zqLogoW,
height: zqLogoH,
url: 'https://zenquality.fr',
})
} else {
page.drawText(zqFallback, {
x: zqX,
y: textBaseY,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: accent,
})
addLinkAnnotation(page, {
x: zqX,
y: textBaseY - 2,
width: zqFallbackW,
height: FONT_SIZE + 4,
url: 'https://zenquality.fr',
})
}
const partnerLabel = `${dict['footer.in_partnership']} `
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(
partnerLabel,
FONT_SIZE,
)
const partnerUrl = 'https://www.instagram.com/paws.iin.harmony'
if (assets.pawsLogoPng) {
const pawsLogoH = 16
const pawsLogoW =
pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
page.drawText(partnerLabel, {
x: partnerX,
y: textBaseY,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: COLOR_MUTED,
})
const pawsX = partnerX + partnerLabelW
page.drawImage(assets.pawsLogoPng, {
x: pawsX,
y: rowY + 2,
width: pawsLogoW,
height: pawsLogoH,
})
addLinkAnnotation(page, {
x: pawsX,
y: rowY + 2,
width: pawsLogoW,
height: pawsLogoH,
url: partnerUrl,
})
} else {
const handle = '@paws.iin.harmony'
const handleW = fonts.bodyRegular.widthOfTextAtSize(handle, FONT_SIZE)
const partnerX = width - MARGIN_X - partnerLabelW - handleW
page.drawText(partnerLabel, {
x: partnerX,
y: textBaseY,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: COLOR_MUTED,
})
page.drawText(handle, {
x: partnerX + partnerLabelW,
y: textBaseY,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: accent,
})
addLinkAnnotation(page, {
x: partnerX + partnerLabelW,
y: textBaseY - 2,
width: handleW,
height: FONT_SIZE + 4,
url: partnerUrl,
})
}
const pageText = `${pageNumber} / ${totalPages}`
const pageW = fonts.bodyRegular.widthOfTextAtSize(pageText, FONT_SIZE)
page.drawText(pageText, {
x: (width - pageW) / 2,
y: FOOTER_BASE_Y + 2,
size: FONT_SIZE,
font: fonts.bodyRegular,
color: COLOR_MUTED,
})
}
-100
View File
@@ -1,100 +0,0 @@
import type { PDFPage, PDFImage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { formatDate } from '@/lib/dates'
import { addLinkAnnotation } from './linkAnnotation'
import { MARGIN_X, COLOR_INK, COLOR_MUTED } from './constants'
const TOP_Y = 800
const LOGO_WIDTH = 100
const LOGO_HEIGHT = 38
export interface HeaderAssets {
logoPng: PDFImage | null
}
export function drawHeader(
page: PDFPage,
report: Report,
fonts: EmbeddedFonts,
locale: Locale,
assets: HeaderAssets,
): void {
const dict = getDict(locale)
const { width } = page.getSize()
const y = TOP_Y
const left = [
report.practitioner.name,
report.practitioner.cabinet,
report.practitioner.contact,
report.practitioner.siret
? `${dict['pdf.siret_prefix']}${report.practitioner.siret}`
: undefined,
].filter(Boolean) as string[]
left.forEach((line, i) => {
page.drawText(line, {
x: MARGIN_X,
y: y - i * 12,
size: i === 0 ? 11 : 9,
font: i === 0 ? fonts.bodyBold : fonts.bodyRegular,
color: i === 0 ? COLOR_INK : COLOR_MUTED,
})
})
if (assets.logoPng) {
const logoX = (width - LOGO_WIDTH) / 2
const logoY = y - LOGO_HEIGHT + 10
page.drawImage(assets.logoPng, {
x: logoX,
y: logoY,
width: LOGO_WIDTH,
height: LOGO_HEIGHT,
})
addLinkAnnotation(page, {
x: logoX,
y: logoY,
width: LOGO_WIDTH,
height: LOGO_HEIGHT,
url: 'https://faunosteo.com',
})
}
const animalLine = [
report.animal.name,
report.animal.breed ? `(${report.animal.breed})` : '',
report.animal.age ? `· ${report.animal.age}` : '',
]
.filter(Boolean)
.join(' ')
const right = [
animalLine,
`${dict['pdf.owner_prefix']}${report.owner.name}`,
formatDate(report.date, locale),
]
right.forEach((line, i) => {
const size = i === 0 ? 11 : 9
const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular
const w = font.widthOfTextAtSize(line, size)
page.drawText(line, {
x: width - MARGIN_X - w,
y: y - i * 12,
size,
font,
color: i === 0 ? COLOR_INK : COLOR_MUTED,
})
})
const separatorY = y - Math.max(left.length * 12, LOGO_HEIGHT) - 8
page.drawLine({
start: { x: MARGIN_X, y: separatorY },
end: { x: width - MARGIN_X, y: separatorY },
thickness: 0.5,
color: COLOR_MUTED,
})
}
-35
View File
@@ -1,35 +0,0 @@
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
export interface LinkRect {
x: number
y: number
width: number
height: number
url: string
}
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
const context = page.doc.context
const actionDict = context.obj({
Type: 'Action',
S: 'URI',
URI: PDFString.of(rect.url),
})
const annotDict = context.obj({
Type: 'Annot',
Subtype: 'Link',
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
Border: [0, 0, 0],
A: actionDict,
})
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
if (annots) {
annots.push(context.register(annotDict))
} else {
const arr = context.obj([context.register(annotDict)])
page.node.set(PDFName.of('Annots'), arr)
}
}
-21
View File
@@ -1,21 +0,0 @@
const FAUNOSTEO_LOGO = '/assets/faunosteo_logo_horizontal-512.png'
const FAUNOSTEO_COM_LOGO = '/assets/faunosteo-horizontal-com-512.png'
const ZENQUALITY_LOGO = '/brand/zenquality-logo-fr.png'
async function fetchPngBytes(path: string): Promise<Uint8Array> {
const resp = await fetch(path)
if (!resp.ok) throw new Error(`Logo fetch failed: HTTP ${resp.status}`)
return new Uint8Array(await resp.arrayBuffer())
}
export async function loadFaunosteoLogo(): Promise<Uint8Array> {
return fetchPngBytes(FAUNOSTEO_LOGO)
}
export async function loadFaunosteoComLogo(): Promise<Uint8Array> {
return fetchPngBytes(FAUNOSTEO_COM_LOGO)
}
export async function loadZenqualityLogo(): Promise<Uint8Array> {
return fetchPngBytes(ZENQUALITY_LOGO)
}
-627
View File
@@ -1,627 +0,0 @@
import {
rgb,
PageSizes,
type PDFDocument,
type PDFPage,
type PDFImage,
} from 'pdf-lib'
import type {
Finding,
Observation,
Report,
ReportZone,
Severity,
} from '@faunosteo/domain'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Locale, Dict } from '@/i18n/types'
import { getDict } from '@/i18n'
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { buildViewSvg } from '@/anatomy/drawing'
import { drawHeader, type HeaderAssets } from './header'
import { rasterizeSvg } from './svgToPng'
import { wrapLines } from './text'
import {
MARGIN_X,
EYEBROW_Y_OFFSET,
TITLE_Y_OFFSET,
TITLE_RULE_OFFSET,
TITLE_RULE_WIDTH,
SECTION_LABEL_GAP,
COLOR_INK,
COLOR_MUTED,
COLOR_ACCENT,
} from './constants'
const MARGIN_BOTTOM = 48
const IMAGE_TOP_GAP = 32
const IMAGE_LABEL_GAP = 14
const IMAGE_BOTTOM_GAP = 14
const IMAGE_COL_GAP = 16
const IMAGE_ROW_GAP = 12
const IMAGE_MIN_CELL_H = 60
const TEXT_TOP_GAP = 10
const TEXT_LINE_HEIGHT = 13
const SECTION_BLOCK_GAP = 10
const COLOR_WHITE = rgb(1, 1, 1)
const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = {
mild: rgb(0.55, 0.65, 0.45),
moderate: rgb(0.85, 0.55, 0.18),
severe: rgb(0.78, 0.2, 0.2),
}
const SECTION_TEXT_SIZE = 10
const SEPARATOR_GLYPH = '•'
const SEPARATOR_SIZE = 14
const SEPARATOR_SIDE_GAP = 5
/** Width of the visible separator block including the empty space on each side. */
function separatorWidth(fonts: EmbeddedFonts): number {
return (
fonts.bodyBold.widthOfTextAtSize(SEPARATOR_GLYPH, SEPARATOR_SIZE) +
SEPARATOR_SIDE_GAP * 2
)
}
/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */
function countSegmentedLines(
items: string[],
fonts: EmbeddedFonts,
maxWidth: number,
): number {
if (items.length === 0) return 1
const sepW = separatorWidth(fonts)
let lines = 1
let x = 0
for (let i = 0; i < items.length; i += 1) {
const itemW = fonts.bodyRegular.widthOfTextAtSize(
items[i]!,
SECTION_TEXT_SIZE,
)
if (x + itemW > maxWidth && x > 0) {
lines += 1
x = 0
}
x += itemW
if (i < items.length - 1) {
if (x + sepW > maxWidth) {
lines += 1
x = 0
} else {
x += sepW
}
}
}
return lines
}
/**
* Renders a list of items separated by a visibly larger accent-coloured
* bullet. Returns the cursor y *below* the last line drawn.
*/
function drawSegmentedText(
page: PDFPage,
items: string[],
startX: number,
startY: number,
maxWidth: number,
fonts: EmbeddedFonts,
): number {
if (items.length === 0) return startY - TEXT_LINE_HEIGHT
const sepW = separatorWidth(fonts)
const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
let x = startX
let y = startY
for (let i = 0; i < items.length; i += 1) {
const item = items[i]!
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
if (x + itemW > startX + maxWidth && x > startX) {
x = startX
y -= TEXT_LINE_HEIGHT
}
page.drawText(item, {
x,
y,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
x += itemW
if (i < items.length - 1) {
if (x + sepW > startX + maxWidth) {
x = startX
y -= TEXT_LINE_HEIGHT
} else {
page.drawText(SEPARATOR_GLYPH, {
x: x + SEPARATOR_SIDE_GAP,
y: y - sepBaselineOffset,
size: SEPARATOR_SIZE,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
x += sepW
}
}
}
return y - TEXT_LINE_HEIGHT
}
const SVG_NS = 'http://www.w3.org/2000/svg'
const HALO_FILTER_ID = 'osteo-halo'
/**
* Adds a Gaussian-blur "halo" filter so the highlighted markers stay
* visible on the whole-animal view once rasterised at print scale.
*/
function ensureHaloFilter(root: SVGSVGElement): void {
const doc = root.ownerDocument
if (root.querySelector(`#${HALO_FILTER_ID}`)) return
let defs = root.querySelector('defs')
if (!defs) {
defs = doc.createElementNS(SVG_NS, 'defs')
root.insertBefore(defs, root.firstChild)
}
const filter = doc.createElementNS(SVG_NS, 'filter')
filter.setAttribute('id', HALO_FILTER_ID)
filter.setAttribute('x', '-100%')
filter.setAttribute('y', '-100%')
filter.setAttribute('width', '300%')
filter.setAttribute('height', '300%')
filter.setAttribute('filterUnits', 'userSpaceOnUse')
const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur')
wide.setAttribute('in', 'SourceGraphic')
wide.setAttribute('stdDeviation', '18')
wide.setAttribute('result', 'haloWide')
filter.appendChild(wide)
const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur')
tight.setAttribute('in', 'SourceGraphic')
tight.setAttribute('stdDeviation', '8')
tight.setAttribute('result', 'haloTight')
filter.appendChild(tight)
const merge = doc.createElementNS(SVG_NS, 'feMerge')
for (const input of [
'haloWide',
'haloWide',
'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
n.setAttribute('in', input)
merge.appendChild(n)
}
filter.appendChild(merge)
defs.appendChild(filter)
}
/**
* The view rendered from the sheet with the observation's zones of that
* view highlighted (legacy picture: accent fill, halo on the main view,
* other markers hidden, no data attributes left).
*/
export function highlightedViewSvg(
sheet: SheetIndex,
viewId: string,
observation: Observation,
): string {
const selected = new Set(
observation.zones
.filter((z) => z.viewId === viewId)
.map((z) => z.annotationId),
)
const root = buildViewSvg(sheet, viewId, new Map())
const applyHalo = sheet.view(viewId)?.kind === 'main'
if (applyHalo) ensureHaloFilter(root)
root.querySelectorAll<Element>('[data-anno-id]').forEach((el) => {
if (selected.has(el.getAttribute('data-anno-id') ?? '')) {
el.setAttribute('fill', '#b85a3f')
el.setAttribute('fill-opacity', '0.85')
if (applyHalo) el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
} else {
el.setAttribute('display', 'none')
}
Array.from(el.attributes)
.filter((a) => a.name.startsWith('data-'))
.forEach((a) => el.removeAttribute(a.name))
})
return new XMLSerializer().serializeToString(root)
}
/** Parameters needed to render one observation page. */
export interface ObservationPageContext {
pdfDoc: PDFDocument
report: Report
observation: Observation
obsIndex: number
fonts: EmbeddedFonts
sheet: SheetIndex
locale: Locale
headerAssets: HeaderAssets
}
interface PageDrawContext {
page: PDFPage
fonts: EmbeddedFonts
width: number
}
interface RenderedImage {
label: string
img: PDFImage
aspect: number
}
interface ObservationSection {
label: string
value: string
}
function drawObservationTitleBlock(
ctx: PageDrawContext,
dict: Dict,
obsIndex: number,
severity: Severity | undefined,
): number {
const { page, fonts } = ctx
const { height } = page.getSize()
const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET
const obsLabel = String(obsIndex + 1).padStart(2, '0')
page.drawText(dict['pdf.eyebrow.observation']!, {
x: MARGIN_X,
y: eyebrowY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
page.drawText(obsLabel, {
x: MARGIN_X,
y: titleY,
size: 22,
font: fonts.headingRegular,
color: COLOR_INK,
})
if (severity) {
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
const sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase()
const sevSize = 9
const padX = 8
const padY = 4
const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + padX * 2
const pillH = sevSize + padY * 2
const pillX = MARGIN_X + numW + 14
const pillY = titleY + 4
page.drawRectangle({
x: pillX,
y: pillY,
width: pillW,
height: pillH,
color: SEVERITY_BG[severity] ?? COLOR_MUTED,
})
page.drawText(sevText, {
x: pillX + padX,
y: pillY + padY,
size: sevSize,
font: fonts.bodyBold,
color: COLOR_WHITE,
})
}
page.drawLine({
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
thickness: 2,
color: COLOR_ACCENT,
})
return titleY
}
/** Every view the observation touches, main first, each rasterised with its highlights. */
async function buildObservationImages(
pdfDoc: PDFDocument,
sheet: SheetIndex,
observation: Observation,
locale: Locale,
dict: Dict,
): Promise<RenderedImage[]> {
const viewIds = [...new Set(observation.zones.map((z) => z.viewId))]
.filter((id) => sheet.view(id))
.sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
)
return Promise.all(
viewIds.map(async (viewId) => {
const view = sheet.view(viewId)!
const label =
view.kind === 'main'
? dict['pdf.view.general']!
: `${dict['pdf.view.detail_prefix']}${pickLabel(view.name, locale).toUpperCase()}`
const png = await rasterizeSvg(
highlightedViewSvg(sheet, viewId, observation),
)
const img = await pdfDoc.embedPng(png)
return {
label,
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
}
}),
)
}
function zoneText(z: ReportZone, sheet: SheetIndex, locale: Locale): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function describeObservationZones(
zones: ReportZone[],
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): string {
return zones
.map((z) => {
const v = z.vertebrae?.length
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
: ''
const side = z.side
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
: ''
return `${zoneText(z, sheet, locale)}${v}${side}`
})
.join(' · ')
}
function findingZoneName(
zoneId: string,
sheet: SheetIndex,
locale: Locale,
): string {
const zone = sheet.findingZone(zoneId)
return zone ? pickLabel(zone.name, locale) : zoneId
}
/** Groups findings by zone+side, one section per group; snapshots give the text. */
function buildFindingsSections(
findings: Finding[],
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): ObservationSection[] {
const byZoneSide = new Map<string, Finding[]>()
for (const f of findings) {
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
}
const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0]!
const side = group[0]?.side
let zoneName = findingZoneName(zoneId, sheet, locale)
if (side)
zoneName = `${zoneName} (${dict[side === 'left' ? 'lateral.left' : 'lateral.right']})`
const value = group
.map((f) => {
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
return f.requiresVetReferral ? `(!) ${lbl}` : lbl
})
.join(' · ')
sections.push({
label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
value,
})
}
return sections
}
function buildObservationSections(
observation: Observation,
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): ObservationSection[] {
const zonesText = describeObservationZones(
observation.zones,
sheet,
locale,
dict,
)
const sections: ObservationSection[] = [
{
label: dict['pdf.section.zones']!,
value: zonesText || dict['pdf.empty']!,
},
...buildFindingsSections(observation.findings, sheet, locale, dict),
]
if (observation.freeTextFindings.length) {
sections.push({
label: dict['pdf.section.free_findings']!,
value: observation.freeTextFindings.join(' · '),
})
}
if (observation.severity) {
sections.push({
label: dict['pdf.section.severity']!,
value: dict[`severity.${observation.severity}`] ?? observation.severity,
})
}
if (observation.comment.trim()) {
sections.push({
label: dict['pdf.section.comment']!,
value: observation.comment.trim(),
})
}
return sections
}
function estimateSectionsHeight(
sections: ObservationSection[],
fonts: EmbeddedFonts,
maxTextW: number,
): number {
let h = TEXT_TOP_GAP
for (const { value } of sections) {
const lineCount = value.includes(' · ')
? countSegmentedLines(value.split(' · '), fonts, maxTextW)
: wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length
h +=
SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
}
return h
}
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
function drawObservationImageGrid(
ctx: PageDrawContext,
rendered: RenderedImage[],
startY: number,
reservedBottom: number,
): number {
const { page, fonts, width } = ctx
let cursorY = startY
if (rendered.length === 0) return cursorY
const isSingle = rendered.length === 1
const cols = isSingle ? 1 : 2
const rows = Math.ceil(rendered.length / cols)
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
const cellW = isSingle ? fullCellW / 2 : fullCellW
const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0
const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom)
const rowBudget = Math.max(
IMAGE_MIN_CELL_H,
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
)
for (let r = 0; r < rows; r += 1) {
const rowItems = rendered.slice(r * cols, r * cols + cols)
const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget))
const rowH = Math.max(0, ...cellHs)
rowItems.forEach((it, c) => {
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
page.drawText(it.label, {
x,
y: cursorY,
size: 8,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
})
cursorY -= IMAGE_LABEL_GAP
rowItems.forEach((it, c) => {
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
page.drawImage(it.img, {
x,
y: cursorY - cellHs[c]!,
width: cellW,
height: cellHs[c]!,
})
})
cursorY -= rowH
if (r < rows - 1) cursorY -= IMAGE_ROW_GAP
}
cursorY -= IMAGE_BOTTOM_GAP
return cursorY
}
function drawObservationSections(
ctx: PageDrawContext,
sections: ObservationSection[],
startY: number,
maxTextW: number,
): number {
const { page, fonts } = ctx
let cursorY = startY
for (const { label, value } of sections) {
page.drawText(label, {
x: MARGIN_X,
y: cursorY,
size: 8,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
cursorY -= SECTION_LABEL_GAP + 9
if (value.includes(' · ')) {
cursorY = drawSegmentedText(
page,
value.split(' · '),
MARGIN_X,
cursorY,
maxTextW,
fonts,
)
} else {
for (const line of wrapLines(
value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
page.drawText(line, {
x: MARGIN_X,
y: cursorY,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
cursorY -= TEXT_LINE_HEIGHT
}
}
cursorY -= SECTION_BLOCK_GAP
}
return cursorY
}
export async function addObservationPage(
ctx: ObservationPageContext,
): Promise<void> {
const {
pdfDoc,
report,
observation,
obsIndex,
fonts,
sheet,
locale,
headerAssets,
} = ctx
const dict = getDict(locale)
const page = pdfDoc.addPage(PageSizes.A4)
const { width } = page.getSize()
drawHeader(page, report, fonts, locale, headerAssets)
const drawCtx: PageDrawContext = { page, fonts, width }
const titleY = drawObservationTitleBlock(
drawCtx,
dict,
obsIndex,
observation.severity,
)
const rendered = await buildObservationImages(
pdfDoc,
sheet,
observation,
locale,
dict,
)
const maxTextW = width - MARGIN_X * 2
const sections = buildObservationSections(observation, sheet, locale, dict)
const reservedBottom =
MARGIN_BOTTOM +
estimateSectionsHeight(sections, fonts, maxTextW) +
IMAGE_BOTTOM_GAP
let cursorY = drawObservationImageGrid(
drawCtx,
rendered,
titleY - IMAGE_TOP_GAP,
reservedBottom,
)
cursorY -= TEXT_TOP_GAP
drawObservationSections(drawCtx, sections, cursorY, maxTextW)
}
-124
View File
@@ -1,124 +0,0 @@
const TARGET_WIDTH = 1200
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
if (bytes[i] !== PNG_SIGNATURE[i]) return false
}
return true
}
function ensureSvgAttributes(
svgString: string,
widthPx: number,
heightPx: number,
): string {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const root = doc.documentElement
if (root.namespaceURI !== 'http://www.w3.org/2000/svg') {
// Some serializers strip xmlns; force the SVG namespace so
// browsers will rasterize the blob URL as an image.
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
}
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
if (!root.getAttribute('height'))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function readViewBox(svgString: string): {
widthPx: number
heightPx: number
} {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600')
.split(/\s+/)
.map(Number)
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
const widthPx = Math.max(1, Math.round(TARGET_WIDTH))
const heightPx = Math.max(1, Math.round(ratio * widthPx))
return { widthPx, heightPx }
}
async function rasterizeWithImageElement(
svgString: string,
widthPx: number,
heightPx: number,
): Promise<HTMLCanvasElement> {
const normalized = ensureSvgAttributes(svgString, widthPx, heightPx)
const svgBlob = new Blob([normalized], {
type: 'image/svg+xml;charset=utf-8',
})
const url = URL.createObjectURL(svgBlob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
try {
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve()
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
})
} finally {
// The Blob URL is single-use — release it once the Image has loaded
// (or failed).
URL.revokeObjectURL(url)
}
const canvas = document.createElement('canvas')
canvas.width = widthPx
canvas.height = heightPx
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
ctx.drawImage(img, 0, 0, widthPx, heightPx)
return canvas
}
async function canvasToPngBytes(
canvas: HTMLCanvasElement,
): Promise<Uint8Array> {
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png')
})
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
const dataUrl = canvas.toDataURL('image/png')
if (!dataUrl.startsWith('data:image/png')) {
throw new Error(
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
)
}
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned a data URL without a payload')
}
const binary = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
if (!startsWithPngSignature(bytes)) {
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
}
return bytes
}
/**
* Rasterizes an SVG string to a PNG byte array using the browser's native
* SVG-to-Image pipeline. The browser parses + draws the SVG via an
* Image/Blob URL pair, which renders identically to what the user sees in
* the inline anatomy canvas.
*
* @param svgString Serialized SVG (must declare `xmlns`)
*/
export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
const { widthPx, heightPx } = readViewBox(svgString)
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
return canvasToPngBytes(canvas)
}
-27
View File
@@ -1,27 +0,0 @@
import type { PDFFont } from 'pdf-lib'
/**
* Greedy word-wrap: splits `text` into lines whose rendered width at
* `size` points stays within `max` for the given font.
*/
export function wrapLines(
text: string,
font: PDFFont,
size: number,
max: number,
): string[] {
const words = text.split(/\s+/)
const lines: string[] = []
let line = ''
for (const w of words) {
const test = line ? `${line} ${w}` : w
if (font.widthOfTextAtSize(test, size) > max && line) {
lines.push(line)
line = w
} else {
line = test
}
}
if (line) lines.push(line)
return lines
}
+46 -7
View File
@@ -1,13 +1,18 @@
import {
readReportDocument,
ReportArchiveEnvelopeSchema,
type Report,
type ReportArchiveEnvelope,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* Where the report document lives between renders. One implementation today
* (the per-tab sessionStorage draft, migrated from v2 on read); the Supabase
* and outbox adapters of later steps implement the same interface.
* Where the session lives between renders. The report draft is mirrored on
* every change; the archive an import brought along (the envelope of a
* Step 6 PDF) is written only when the session starts or ends, so a stale
* draft can still be rebased with the labels of its original sheet. One
* implementation today (per-tab sessionStorage); the Supabase and outbox
* adapters of later steps implement the same interfaces.
*/
export interface ReportPersistence {
@@ -15,12 +20,33 @@ export interface ReportPersistence {
save(report: Report | null): void
}
export interface ArchivePersistence {
load(): ReportArchiveEnvelope | null
save(archive: ReportArchiveEnvelope | null): void
}
export const DRAFT_KEY = 'osteo:draft'
export const ARCHIVE_KEY = 'osteo:archive'
function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
function writeOrRemove(key: string, value: unknown): void {
const store = storage()
if (!store) return
if (value === null) {
store.removeItem(key)
return
}
try {
store.setItem(key, JSON.stringify(value))
} catch (err) {
// Quota exceeded: the session goes on, only the mirror is lost.
if (import.meta.env.DEV) console.warn(`${key} not saved`, err)
}
}
export const sessionStoragePersistence: ReportPersistence = {
load(map) {
const raw = storage()?.getItem(DRAFT_KEY)
@@ -33,9 +59,22 @@ export const sessionStoragePersistence: ReportPersistence = {
}
},
save(report) {
const store = storage()
if (!store) return
if (report) store.setItem(DRAFT_KEY, JSON.stringify(report))
else store.removeItem(DRAFT_KEY)
writeOrRemove(DRAFT_KEY, report)
},
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
load() {
const raw = storage()?.getItem(ARCHIVE_KEY)
if (!raw) return null
try {
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
},
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
}
+86 -31
View File
@@ -1,19 +1,24 @@
import { create } from 'zustand'
import {
rebaseReportOnSheet,
REPORT_VERSION,
type Animal,
type NextAppointment,
type Observation,
type Owner,
type Practitioner,
type RebaseOutcome,
type Report,
type ReportMigrationMap,
type ReportArchiveEnvelope,
type SheetRef,
} from '@faunosteo/domain'
import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
type ReportPersistence,
} from './persistence'
@@ -21,7 +26,10 @@ import {
* In-memory report document (v3) and its editing actions. Observation-level
* zone rules live in services/zoneInteraction; the store only replaces
* documents. The per-tab draft is mirrored through the persistence adapter
* and restored once the sheet (and its migration map) is known.
* and restored once the sheet is known; a draft written on another revision
* of the sheet is rebased on restore. The archive an import brought along
* (STEP6 §14 "App session") is kept beside the report for later operations
* and written only when the session starts or ends.
*/
/** What a new report needs before the store stamps version, id and dates. */
@@ -30,13 +38,26 @@ export type NewReportDraft = Omit<
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
export interface ImportedSession {
report: Report
archive: ReportArchiveEnvelope | null
}
export interface ReportStore {
report: Report | null
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
hydrateReport: (report: Report) => void
/** Restores the per-tab draft; a no-op when a report is already open. */
restoreDraft: (map: ReportMigrationMap) => void
/** Opens an imported report (already rebased) with its archive. */
hydrateImport: (session: ImportedSession) => void
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op when a report is already open.
* Returns the rebase outcome, null when nothing was restored.
*/
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
addObservation: () => void
removeObservation: (index: number) => void
moveObservationUp: (index: number) => void
@@ -62,49 +83,79 @@ export function emptyObservation(): Observation {
}
}
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
return {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
}
}
function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
;[next[i], next[j]] = [next[j]!, next[i]!]
return next
}
type Patch = Partial<Pick<ReportStore, 'report' | 'activeObservationIndex'>>
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
}
export function createReportStore(persistence: ReportPersistence) {
const store = create<ReportStore>((set) => ({
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
) {
/** The archive mirror is explicit: these actions are the session's edges. */
const withArchive = (patch: Patch, archive: ReportArchiveEnvelope | null) => {
archives.save(archive)
return { ...patch, archive }
}
const store = create<ReportStore>((set, get) => ({
report: null,
archive: null,
activeObservationIndex: 0,
initReport: (draft, sheet) =>
set({
report: {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
},
activeObservationIndex: 0,
}),
set(
withArchive(
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
null,
),
),
hydrateReport: (report) => set({ report, activeObservationIndex: 0 }),
hydrateReport: (report) =>
set(withArchive({ report, activeObservationIndex: 0 }, null)),
restoreDraft: (map) =>
set((s) => {
if (s.report) return s
const report = persistence.load(map)
return report ? { report, activeObservationIndex: 0 } : s
}),
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
restoreDraft: (index) => {
if (get().report) return null
const draft = persistence.load(index.sheet.migrationMap)
if (!draft) return null
const archive = archives.load()
const rebase = rebaseReportOnSheet(
draft,
index,
archive?.sheetSnapshot ?? null,
)
set({ report: rebase.report, archive, activeObservationIndex: 0 })
return rebase
},
addObservation: () =>
onReport(set, (r) => {
@@ -177,10 +228,14 @@ export function createReportStore(persistence: ReportPersistence) {
delete rest.nextAppointment
return { report: next ? { ...rest, nextAppointment: next } : rest }
}),
reset: () => set({ report: null, activeObservationIndex: 0 }),
reset: () =>
set(withArchive({ report: null, activeObservationIndex: 0 }, null)),
}))
store.subscribe((state) => persistence.save(state.report))
return store
}
export const useReportStore = createReportStore(sessionStoragePersistence)
export const useReportStore = createReportStore(
sessionStoragePersistence,
sessionStorageArchivePersistence,
)
+54 -28
View File
@@ -12,18 +12,32 @@ import {
PDFPage,
PDFString,
} from 'pdf-lib'
import type { Observation, Report } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import type { Observation, Report, SheetSnapshot } from '@faunosteo/domain'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
/**
* Step 6 Phase 0 freeze: what the current PDF pipeline draws, recorded as
* JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md §17). The
* recorder spies on pdf-lib, the link reader parses the saved bytes, the
* view snapshot parses the highlighted SVG. Numbers are rounded to 2
* decimals; nothing ordered by drawing order is sorted.
* Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine,
* recorded as JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md
* §17) that the app export path must still reproduce. The recorder spies on
* pdf-lib, the link reader parses the saved bytes, the view snapshot parses
* the engine's highlighted SVG with the browser DOM. Numbers are rounded to
* 2 decimals; nothing ordered by drawing order is sorted.
*/
/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */
export const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
export const TWO_BY_ONE_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
'base64',
),
)
const HERE = dirname(fileURLToPath(import.meta.url))
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
@@ -174,8 +188,7 @@ const LOGO_FILES: Readonly<Record<string, string>> = {
'/Paws_in_harmony.svg': 'Paws_in_harmony.svg',
}
function serveLogo(input: RequestInfo | URL): Response {
const path = new URL(String(input), 'http://localhost').pathname
function serveLogo(path: string): Response {
const relative = LOGO_FILES[path]
const file = relative ? resolve(PUBLIC_DIR, relative) : null
if (!file || !existsSync(file))
@@ -183,18 +196,27 @@ function serveLogo(input: RequestInfo | URL): Response {
return new Response(new Uint8Array(readFileSync(file)), { status: 200 })
}
/** Stubs fetch for one logo mode; returns the restore function. */
export function installLogoFetch(mode: LogoMode): () => void {
/** Stubs fetch with a path → Response handler; returns the restore function. */
export function installFetch(respond: (path: string) => Response): () => void {
const real = globalThis.fetch
globalThis.fetch = (async (input: RequestInfo | URL) =>
mode === 'logos'
? serveLogo(input)
: new Response('not found', { status: 404 })) as typeof fetch
respond(
new URL(String(input), 'http://localhost').pathname,
)) as typeof fetch
return () => {
globalThis.fetch = real
}
}
/** Stubs fetch for one logo mode; returns the restore function. */
export function installLogoFetch(mode: LogoMode): () => void {
return installFetch((path) =>
mode === 'logos'
? serveLogo(path)
: new Response('not found', { status: 404 }),
)
}
const HIGHLIGHT_FILL = '#b85a3f'
function highlightedOf(el: Element): HighlightedElement {
@@ -236,11 +258,11 @@ function countDataAttributes(root: Element): number {
}
export function snapshotView(
sheet: SheetIndex,
sheet: SheetSnapshot,
observation: Observation,
viewId: string,
): ViewSnapshot {
const svg = highlightedViewSvg(sheet, viewId, observation)
const svg = composeHighlightedViewSvg(sheet, viewId, observation)
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
@@ -261,19 +283,18 @@ export function snapshotView(
/** The views an observation draws, in the pipeline's order: main first, then first appearance. */
export function viewIdsOf(
sheet: SheetIndex,
sheet: SheetSnapshot,
observation: Observation,
): string[] {
const views = new Set(sheet.document.views.map((v) => v.id))
const main = sheet.document.views.find((v) => v.kind === 'main')!.id
return [...new Set(observation.zones.map((z) => z.viewId))]
.filter((id) => sheet.view(id))
.sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
)
.filter((id) => views.has(id))
.sort((a, b) => Number(b === main) - Number(a === main))
}
export function snapshotViews(
sheet: SheetIndex,
sheet: SheetSnapshot,
report: Report,
): ViewSnapshot[] {
return report.observations.flatMap((observation) =>
@@ -283,14 +304,19 @@ export function snapshotViews(
)
}
export function readGolden<T = unknown>(name: string): T {
return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T
}
/** Writes the golden under MAKE_GOLDEN, asserts deep equality otherwise. */
export function checkGolden(name: string, actual: unknown): void {
const path = resolve(GOLDEN_DIR, name)
if (MAKE_GOLDEN) {
mkdirSync(GOLDEN_DIR, { recursive: true })
writeFileSync(path, `${JSON.stringify(actual, null, 2)}\n`)
writeFileSync(
resolve(GOLDEN_DIR, name),
`${JSON.stringify(actual, null, 2)}\n`,
)
return
}
const golden: unknown = JSON.parse(readFileSync(path, 'utf8'))
expect(actual, name).toEqual(golden)
expect(actual, name).toEqual(readGolden(name))
}
+42
View File
@@ -1,8 +1,14 @@
import {
buildSheetSnapshot,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
REPORT_VERSION,
type Branding,
type Observation,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import { defaultPdfLabels } from '@faunosteo/pdf'
import { loadSheetIndex } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
@@ -37,3 +43,39 @@ export function minimalReport(
...patch,
}
}
/** The branding the app loads when every logo fetch fails (credits keep their text). */
export function nologosBranding(): Branding {
return {
siteUrl: 'https://faunosteo.com',
headerLogo: null,
footerLogo: null,
poweredBy: {
logo: null,
url: 'https://zenquality.fr',
fallbackText: 'zenquality.fr',
},
partner: {
logo: null,
url: 'https://www.instagram.com/paws.iin.harmony',
fallbackText: '@paws.iin.harmony',
},
}
}
/** A valid Step 6 envelope for `report`, snapshotted on `sheet` (no logos). */
export function archiveEnvelope(
sheet: SheetIndex,
report: Report,
): ReportArchiveEnvelope {
return {
format: ENVELOPE_FORMAT,
envelopeVersion: ENVELOPE_VERSION,
exportedAt: '2026-10-11T12:00:00.000Z',
locale: 'fr',
report,
sheetSnapshot: buildSheetSnapshot(sheet.sheet, report),
branding: nologosBranding(),
labels: defaultPdfLabels,
}
}
+12 -8
View File
@@ -3,6 +3,9 @@ import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
// The pdf.* keys left the app dicts with Step 6: the engine owns them
// (@faunosteo/pdf defaultPdfLabels, parity tested there).
const REQUIRED = [
'severity.mild',
'severity.moderate',
@@ -11,14 +14,13 @@ const REQUIRED = [
'home.import.error_invalid_pdf',
'home.import.error_no_attachment',
'home.import.error_generic',
'pdf.section.zones',
'pdf.section.findings_prefix',
'pdf.section.free_findings',
'pdf.section.severity',
'pdf.section.comment',
'pdf.view.general',
'pdf.view.detail_prefix',
'pdf.empty',
'home.import.error_attachment_stripped',
'home.import.archive_ok',
'home.import.snapshot_reason.unsupported_envelope',
'home.import.snapshot_reason.schema',
'home.import.snapshot_reason.caps',
'home.import.snapshot_reason.integrity',
'home.import.snapshot_reason.sheet_mismatch',
'sheet.status.draft',
'sheet.loading',
'vertebra.range_note',
@@ -27,6 +29,8 @@ const REQUIRED = [
const PLACEHOLDERS: Record<string, string> = {
'home.import.error_incompatible_version': '{version}',
'home.import.migrated': '{count}',
'home.import.rebased': '{count}',
'home.import.snapshot_rejected': '{reason}',
'vertebra.extend_to': '{max}',
}
+11 -10
View File
@@ -19,15 +19,11 @@ import {
loadLegacyBaseline,
} from '../helpers/legacyLeaves'
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => ONE_PX_PNG),
}))
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
})
let sheet: SheetIndex
let report: Report
@@ -35,6 +31,9 @@ let findings: Finding[]
let unresolvedFindings: number
beforeAll(async () => {
// No logo served: the branding loader leaves every slot empty.
globalThis.fetch = (async () =>
new Response('not found', { status: 404 })) as typeof fetch
sheet = await loadTestSheet()
const leaves = legacyLeaves(loadLegacyBaseline())
const v2 = leavesAsV2Report(leaves)
@@ -60,10 +59,12 @@ describe('the 612 legacy leaves in the application', () => {
}
})
it('keeps every finding, resolved or not, through a v3 PDF export and import', async () => {
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(back.migrated).toBe(false)
expect(back.origin).toBe('envelope_v1')
expect(back.archive).not.toBeNull()
expect(back.report).toEqual(report)
const again = back.report.observations.flatMap((o) => o.findings)
expect(again.filter((f) => f.unresolved)).toHaveLength(29)
@@ -1,28 +0,0 @@
import { describe, it, expect } from 'vitest'
import { inflateFlate } from '@/pdf/attachment'
async function deflate(data: Uint8Array): Promise<Uint8Array> {
const stream = new Blob([data as BlobPart])
.stream()
.pipeThrough(new CompressionStream('deflate'))
return new Uint8Array(await new Response(stream).arrayBuffer())
}
describe('inflateFlate decompression cap', () => {
it('inflates a normal-size payload', async () => {
const payload = new TextEncoder().encode(
JSON.stringify({ version: 2, hello: 'world' }),
)
const out = await inflateFlate(await deflate(payload))
expect(out).not.toBeNull()
expect(new TextDecoder().decode(out!)).toContain('hello')
})
it('returns null for a decompression bomb above the cap', async () => {
// 24 MB of zeros deflates to a few KB but inflates past the 16 MB cap
const bomb = await deflate(new Uint8Array(24 * 1024 * 1024))
expect(bomb.byteLength).toBeLessThan(1024 * 1024)
const out = await inflateFlate(bomb)
expect(out).toBeNull()
})
})
@@ -1,50 +0,0 @@
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { attachReportJson, extractReportJson } from '@/pdf/attachment'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('PDF attachment roundtrip', () => {
it('attaches and extracts the v3 report JSON', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await attachReportJson(
doc,
minimalReport(sheet, { conclusion: 'tout va bien' }),
)
const bytes = await doc.save()
const reopened = await PDFDocument.load(bytes)
const out = await extractReportJson(reopened, sheet.sheet.migrationMap)
expect(out.report.conclusion).toBe('tout va bien')
expect(out.report.animal.name).toBe('Mistral')
expect(out.report.version).toBe(3)
expect(out.migrated).toBe(false)
})
it('throws on PDFs without the attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const bytes = await doc.save()
const reopened = await PDFDocument.load(bytes)
await expect(
extractReportJson(reopened, sheet.sheet.migrationMap),
).rejects.toThrow()
})
})
describe('size caps', () => {
it('refuses an oversized PDF before parsing it', async () => {
const { importReportFromPdf, ImportError, MAX_PDF_BYTES } =
await import('@/pdf/import')
const huge = new Uint8Array(MAX_PDF_BYTES + 1)
await expect(
importReportFromPdf(huge, sheet.sheet.migrationMap),
).rejects.toBeInstanceOf(ImportError)
})
})
@@ -0,0 +1,81 @@
/**
* Replaces pdf.svgToPng.test.ts: the browser rasterizer adapter stamps the
* engine's size on the SVG root, draws through Image/canvas and returns PNG
* bytes, with the toDataURL fallback when toBlob yields nothing.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { browserRasterizer } from '@/pdf/browserRasterizer'
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00,
])
const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>'
const SIZE = { widthPx: 10, heightPx: 6 }
class MockImage {
decoding: 'sync' | 'async' | 'auto' = 'auto'
crossOrigin: string | null = null
onload: (() => void) | null = null
onerror: ((err?: unknown) => void) | null = null
private _src = ''
get src(): string {
return this._src
}
set src(value: string) {
this._src = value
queueMicrotask(() => this.onload?.())
}
}
const blobs: Blob[] = []
function mockCanvas(toBlob: (cb: BlobCallback) => void): HTMLCanvasElement {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = toBlob as HTMLCanvasElement['toBlob']
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
return canvas
}
describe('browserRasterizer', () => {
beforeEach(() => {
blobs.length = 0
vi.stubGlobal('Image', MockImage)
vi.stubGlobal('URL', {
createObjectURL: (blob: Blob) => {
blobs.push(blob)
return 'blob:mock'
},
revokeObjectURL: () => undefined,
})
})
it('returns PNG bytes for a valid SVG, sized by the engine', async () => {
const canvas = mockCanvas((cb) =>
cb(new Blob([PNG_BYTES], { type: 'image/png' })),
)
const out = await browserRasterizer(SVG, SIZE)
expect(out).toBeInstanceOf(Uint8Array)
expect(Array.from(out.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47])
expect([canvas.width, canvas.height]).toEqual([10, 6])
const served = await blobs[0]!.text()
expect(served).toContain('width="10"')
expect(served).toContain('height="6"')
})
it('falls back to toDataURL when toBlob returns null', async () => {
const canvas = mockCanvas((cb) => cb(null))
canvas.toDataURL = () =>
'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64')
const out = await browserRasterizer(SVG, SIZE)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
})
})
+203
View File
@@ -0,0 +1,203 @@
/**
* T2 and user scenario 3 (STEP6 §7): the archive the app exports is
* self-sufficient. Once exported, the catalog may change its labels and
* geometry and the deployment may ship other logos: a re-export from the
* envelope alone reproduces the first export, not the current resources.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
afterAll,
afterEach,
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetIndex,
buildSheetSnapshot,
ReportSchema,
type FindingCategory,
type FindingNode,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import { exportFromEnvelope, readReportArchive } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { loadBranding } from '@/pdf/branding'
import type { LoadedSheet } from '@/sheets/provider'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
FIXTURES_DIR,
installFetch,
installLogoFetch,
ONE_PX_PNG,
readLinks,
recordDrawing,
snapshotViews,
type ImageEntry,
type LinkEntry,
type TextEntry,
} from '../helpers/goldens'
// Same fixed raster for every view and logo: images then depend on the
// branding and the layout only.
vi.mock('@/pdf/browserRasterizer', async () => {
const { TWO_BY_ONE_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) }
})
let sheet: SheetIndex
let demo: Report
let restoreFetch: () => void = () => undefined
beforeAll(async () => {
sheet = await loadTestSheet()
demo = ReportSchema.parse(
JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'),
),
)
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterEach(() => {
restoreFetch()
restoreFetch = () => undefined
})
afterAll(() => vi.restoreAllMocks())
interface Facts {
texts: TextEntry[]
images: ImageEntry[]
links: LinkEntry[]
}
/** Runs an export under the drawing recorder and reads the links back. */
async function recorded<T extends { pdf: Uint8Array }>(
run: () => Promise<T>,
): Promise<T & Facts> {
const recording = recordDrawing()
try {
const result = await run()
const { texts, images } = recording
return { ...result, texts, images, links: await readLinks(result.pdf) }
} finally {
recording.stop()
}
}
const facts = ({ texts, images, links }: Facts): Facts => ({
texts,
images,
links,
})
/** The app export path, logos served from public/, under the recorder. */
async function appExport(
index: SheetIndex,
): Promise<Facts & { pdf: Uint8Array }> {
const restore = installLogoFetch('logos')
try {
return await recorded(async () => ({
pdf: await exportReportToPdf(demo, index, { locale: 'fr' }),
}))
} finally {
restore()
}
}
async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> {
const outcome = await readReportArchive(pdf, sheet.sheet.migrationMap)
expect(outcome.origin).toBe('envelope_v1')
return outcome.archive!
}
const REEXPORT = {
locale: 'fr' as const,
rasterizer: browserRasterizer,
exportedAt: new Date('2027-01-01T00:00:00.000Z'),
}
function renameNodes(nodes: (FindingCategory | FindingNode)[]): void {
for (const node of nodes) {
node.name = {
fr: `${node.name.fr} (révisé)`,
en: `${node.name.en} (revised)`,
}
renameNodes(node.children)
}
}
/** The catalog after a revision: every label changed, the hip marker moved. */
function revisedSheet(source: LoadedSheet): LoadedSheet {
const next = structuredClone(source)
for (const a of next.document.annotations) {
if (a.name) {
a.name = { fr: `${a.name.fr} (révisé)`, en: `${a.name.en} (revised)` }
}
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx += 100
}
for (const zone of next.document.finding_zones) {
zone.name = {
fr: `${zone.name.fr} (révisé)`,
en: `${zone.name.en} (revised)`,
}
renameNodes(zone.categories)
}
return next
}
describe('the archive survives its resources', () => {
it('T2 catalog changed: the envelope re-exports the archived sheet, not the revised one', async () => {
const first = await appExport(sheet)
const archive = await archiveOf(first.pdf)
// The revision is visible through the app path (labels and geometry)...
const revised = buildSheetIndex(revisedSheet(sheet.sheet))
const onRevised = await appExport(revised)
expect(onRevised.texts).not.toEqual(first.texts)
const revisedViews = snapshotViews(
buildSheetSnapshot(revised.sheet, demo),
demo,
)
const archivedViews = snapshotViews(archive.sheetSnapshot, demo)
expect(revisedViews).not.toEqual(archivedViews)
// ...and absent from a re-export of the envelope alone.
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
expect(again.warnings).toEqual([])
expect(facts(again)).toEqual(facts(first))
expect(
snapshotViews(again.envelope.sheetSnapshot, again.envelope.report),
).toEqual(archivedViews)
}, 60_000)
it('scenario 3 branding changed: the envelope re-exports the archived branding and never fetches', async () => {
const first = await appExport(sheet)
const archive = await archiveOf(first.pdf)
// The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG.
const otherSvg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
const fetchSpy = vi.fn((path: string) =>
path.endsWith('.svg')
? new Response(otherSvg, { status: 200 })
: new Response(ONE_PX_PNG, { status: 200 }),
)
restoreFetch = installFetch(fetchSpy)
const current = await loadBranding()
expect(current.headerLogo).not.toBeNull()
expect(current).not.toEqual(archive.branding)
fetchSpy.mockClear()
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
expect(fetchSpy).not.toHaveBeenCalled()
expect(again.warnings).toEqual([])
expect(facts(again)).toEqual(facts(first))
expect(again.envelope.branding).toEqual(archive.branding)
}, 60_000)
})
+41 -30
View File
@@ -1,15 +1,18 @@
/**
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17): the current PDF
* pipeline recorded as goldens, per report × locale × logo mode. Generated
* once with `MAKE_GOLDEN=1`; without the flag the same file asserts them.
* Never regenerate without a user decision: the Step 6 engine must
* reproduce these files.
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
* application export path: `exportReportToPdf` now runs the engine with the
* bundled sheet snapshotted, the branding fetched from `public/` and the
* browser rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
* images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites
* them, never without a user decision. Never regenerate `report-v3.bare.pdf`:
* it is the Step 5 bare export, an import fixture only.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync, writeFileSync } from 'node:fs'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetSnapshot,
readReportDocument,
ReportSchema,
type Report,
@@ -28,33 +31,22 @@ import {
checkGolden,
FIXTURES_DIR,
installLogoFetch,
MAKE_GOLDEN,
ONE_PX_PNG,
readGolden,
readLinks,
recordDrawing,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
const TWO_BY_ONE_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
'base64',
),
)
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => raster.png),
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => raster.png),
}))
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
@@ -184,20 +176,39 @@ describe.each(REPORTS)('goldens of %s', (name) => {
}, 30_000)
})
it('highlighted views', () => {
checkGolden(`views.${name}.json`, snapshotViews(sheet, reports[name]))
// Hidden markers are absent in the engine (the browser hid them with
// display="none") and the layer <g> carries no data-* any more: `titles`
// shrinks to the highlighted markers plus the asset's own, and
// `dataAttributes` drops from 2 to 0. Everything else must match.
it('highlighted views: same facts but titles and data attributes', () => {
const snapshot = buildSheetSnapshot(sheet.sheet, reports[name])
const actual = snapshotViews(snapshot, reports[name])
const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`)
const comparable = (v: ViewSnapshot) => ({
observationId: v.observationId,
viewId: v.viewId,
viewBox: v.viewBox,
halo: v.halo,
highlighted: v.highlighted,
nonHighlightedVisible: v.nonHighlightedVisible,
})
expect(actual.map(comparable)).toEqual(expected.map(comparable))
for (const view of actual) {
expect(view.dataAttributes).toBe(0)
expect(view.titles).toBeGreaterThanOrEqual(view.highlighted.length)
}
for (const view of expected) expect(view.dataAttributes).toBe(2)
})
})
describe('report-v3.bare.pdf', () => {
it('is the demo report exported without logos and imports back unchanged', async () => {
if (MAKE_GOLDEN) {
const { bytes } = await exportWith(reports.demo, 'nologos', 'fr')
writeFileSync(BARE_PDF, bytes)
}
it('is the demo report exported bare by Step 5 and imports with no archive', async () => {
const bytes = new Uint8Array(readFileSync(BARE_PDF))
const outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(outcome.origin).toBe('bare_v3')
expect(outcome.migrated).toBe(false)
expect(outcome.archive).toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
expect(outcome.report).toEqual(reports.demo)
})
})
+47
View File
@@ -0,0 +1,47 @@
/**
* Replaces pdf.attachment.test.ts and pdf.attachment.inflate.test.ts on the
* engine read API: the typed ImportError kinds the home route maps. The
* attachment roundtrip moved to pdf.roundtrip.test.ts ("attaches the
* envelope and roundtrips") and the engine's tests/read.test.ts (T4); the
* inflate bomb cap lives in the engine's tests/security.test.ts.
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
async function pdfWithoutAttachment(keywords?: string[]): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
if (keywords) doc.setKeywords(keywords)
return doc.save()
}
async function rejectsWith(bytes: Uint8Array, kind: string): Promise<void> {
const promise = importReportFromPdf(bytes, sheet.sheet.migrationMap)
await expect(promise).rejects.toBeInstanceOf(ImportError)
await expect(promise).rejects.toMatchObject({ kind })
}
describe('importReportFromPdf error kinds', () => {
it('no_attachment for a PDF without the attachment', async () => {
await rejectsWith(await pdfWithoutAttachment(), 'no_attachment')
})
it('attachment_stripped for a stamped archive whose attachment was removed', async () => {
await rejectsWith(
await pdfWithoutAttachment(['faunosteo-archive/1']),
'attachment_stripped',
)
})
it('invalid_pdf for an oversized file, before parsing it', async () => {
await rejectsWith(new Uint8Array(MAX_PDF_BYTES + 1), 'invalid_pdf')
})
})
+34 -25
View File
@@ -1,8 +1,8 @@
/**
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the v3 pipeline on
* the bundled sheet (drawn strings from the document, attachment v3,
* roundtrip FR/EN) and the import of the frozen v2 archive PDFs, migrated
* without silent loss.
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application
* export path on the engine with the bundled sheet (drawn strings from the
* document, envelope attachment, roundtrip FR/EN) and the import of the
* frozen v2 archive PDFs, migrated without silent loss.
*/
import {
describe,
@@ -17,25 +17,22 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation } from '@faunosteo/domain'
import { buildSheetSnapshot, type Observation } from '@faunosteo/domain'
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { formatDate } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => ONE_PX_PNG),
}))
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
})
/** The static PDF strings now belong to the engine's label set. */
const { fr, en } = defaultPdfLabels
const HERE = dirname(fileURLToPath(import.meta.url))
const fixture = (name: string) =>
@@ -145,24 +142,34 @@ describe('export on a full v3 report (FR)', () => {
)
})
it('attaches v3 and roundtrips in both locales', async () => {
it('attaches the envelope and roundtrips in both locales', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportReportToPdf(report, sheet, { locale })
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(out.migrated).toBe(false)
expect(out.origin).toBe('envelope_v1')
expect(out.report).toEqual(report)
expect(out.archive?.locale).toBe(locale)
expect(out.archive?.sheetSnapshot.ref.documentSha256).toBe(
sheet.sheet.ref.documentSha256,
)
}
})
it('highlights the observation zones of a view and hides the other markers', () => {
const svg = highlightedViewSvg(sheet, 'main', fullObservation())
// The engine draws only the observation's markers (the browser pipeline
// hid the others with display="none"); the view facts are frozen in
// pdf.goldens.test.ts "highlighted views".
it('highlights the observation zones of a view and omits the other markers', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const snapshot = buildSheetSnapshot(sheet.sheet, report)
const svg = composeHighlightedViewSvg(snapshot, 'main', fullObservation())
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
expect(svg).toContain('url(#osteo-halo)')
expect(svg).toContain('display="none"')
expect(svg).not.toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
const head = highlightedViewSvg(sheet, 'head', fullObservation())
const head = composeHighlightedViewSvg(snapshot, 'head', fullObservation())
expect(head).toContain('viewBox="60 100 500 380"')
expect(head).not.toContain('osteo-halo')
})
@@ -252,12 +259,13 @@ describe('PDF content on a two-observation report', () => {
expect(header).toBeGreaterThanOrEqual(pages)
})
it('sets the PDF metadata', async () => {
it('sets the PDF metadata and the archive keyword', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(doc.getAuthor()).toBe('Dr. Dupont')
expect(doc.getSubject()).toBe(fr['pdf.subject'])
expect(doc.getKeywords()).toContain('faunosteo-archive/1')
})
it('fetches the logos at export time', async () => {
@@ -269,7 +277,7 @@ describe('PDF content on a two-observation report', () => {
).toBe(true)
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo state v3"', async () => {
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
@@ -282,7 +290,7 @@ describe('PDF content on a two-observation report', () => {
[...text]
.map((c) => c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0'))
.join('')
expect(filespec).toContain(utf16('Faunosteo state v3'))
expect(filespec).toContain(utf16('Faunosteo report archive v1'))
const embedded = objects.find((o) => o.includes('/Type /EmbeddedFile'))!
expect(embedded).toContain('/Filter /FlateDecode')
})
@@ -365,6 +373,7 @@ describe('import of the frozen v2 archive PDFs', () => {
)
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
expect(again.origin).toBe('envelope_v1')
})
it('keeps a v2 finding whose node was removed and a zone whose id is unknown, both flagged', async () => {
-80
View File
@@ -1,80 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { rasterizeSvg } from '@/pdf/render/svgToPng'
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00,
])
class MockImage {
decoding: 'sync' | 'async' | 'auto' = 'auto'
crossOrigin: string | null = null
onload: (() => void) | null = null
onerror: ((err?: unknown) => void) | null = null
private _src = ''
get src(): string {
return this._src
}
set src(value: string) {
this._src = value
queueMicrotask(() => this.onload?.())
}
}
describe('rasterizeSvg', () => {
beforeEach(() => {
vi.stubGlobal('Image', MockImage)
vi.stubGlobal('URL', {
createObjectURL: () => 'blob:mock',
revokeObjectURL: () => undefined,
})
})
it('returns PNG bytes for a valid SVG', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
cb(new Blob([PNG_BYTES], { type: 'image/png' }))
}) as HTMLCanvasElement['toBlob']
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
)
expect(out).toBeInstanceOf(Uint8Array)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
expect(out[2]).toBe(0x4e)
expect(out[3]).toBe(0x47)
})
it('falls back to toDataURL when toBlob returns null', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
cb(null)
}) as HTMLCanvasElement['toBlob']
canvas.toDataURL = () =>
'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64')
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
})
})
@@ -0,0 +1,241 @@
/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with
* `importReportFromPdf` mocked. Same sheet: archive kept in the store and
* mirrored, archive_ok alert. Other sheet: the report is rebased on the
* loaded sheet (unresolved flags, labels from the archived snapshot, sheet
* ref updated) and the alert says so with the count. Snapshot rejected: the
* reason label. Attachment stripped: its error message.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterEach,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type {
Annotation,
ArchiveReadOutcome,
Report,
ReportArchiveEnvelope,
} from '@faunosteo/domain'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
const OTHER_SHA = 'b'.repeat(64)
/** An outcome carrying a kept envelope (v3, nothing migrated). */
function archived(
report: Report,
archive: ReportArchiveEnvelope | null,
patch: Partial<ArchiveReadOutcome> = {},
): ArchiveReadOutcome {
return {
report,
origin: 'envelope_v1',
migrated: false,
unresolvedZones: 0,
unresolvedFindings: 0,
archive,
...patch,
}
}
function reportWithHip(): Report {
return minimalReport(sheet, {
observations: [
{
id: 'o1',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
}
/**
* A report written on another revision of the sheet: a zone and a finding
* path the loaded sheet does not hold, next to a zone it does. Its archived
* snapshot names the lost zone so the rebase can fill the label.
*/
function staleReportAndArchive(): {
report: Report
archive: ReportArchiveEnvelope
} {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o-stale',
zones: [
{ annotationId: 'point-gone', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'gone'],
labelFrSnapshot: 'Constat disparu',
labelEnSnapshot: 'Gone finding',
},
],
freeTextFindings: [],
comment: '',
},
],
})
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
const gone: Annotation = {
...sheet.annotation('hip')!,
id: 'point-gone',
name: { fr: 'Point disparu', en: 'Gone point' },
} as Annotation
archive.sheetSnapshot.document.annotations.push(gone)
return { report, archive }
}
async function mountAndPickPdf(): Promise<void> {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const input = document.querySelector('input[type="file"]')!
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(input, { target: { files: [file] } })
}
const alertMock = () => vi.mocked(window.alert)
const alertText = () => alertMock().mock.calls[0]![0] as string
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import of a Step 6 archive', () => {
it('same sheet: keeps the archive in the store and its mirror, alerts archive_ok, no rebase', async () => {
const report = reportWithHip()
const archive = archiveEnvelope(sheet, report)
importMock.mockResolvedValue(archived(report, archive))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const state = useReportStore.getState()
expect(state.report).toEqual(report)
expect(state.archive).toEqual(archive)
expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe(
report.id,
)
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertText()).toBe(fr['home.import.archive_ok'])
})
it('other sheet: rebases onto the loaded sheet, labels from the archived snapshot, alert with the count', async () => {
const { report, archive } = staleReportAndArchive()
importMock.mockResolvedValue(archived(report, archive))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
expect(opened.sheet).toEqual(sheet.sheet.ref)
const [gone, hip] = opened.observations[0]!.zones
expect(gone).toMatchObject({
unresolved: true,
labelFrSnapshot: 'Point disparu',
labelEnSnapshot: 'Gone point',
})
expect(hip!.unresolved).toBeUndefined()
expect(opened.observations[0]!.findings[0]).toMatchObject({
unresolved: true,
labelFrSnapshot: 'Constat disparu',
})
// The archive stays as exported, never rebased.
expect(useReportStore.getState().archive).toEqual(archive)
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertText()).toBe(
[
fr['home.import.archive_ok'],
fr['home.import.rebased']!.replace('{count}', '2'),
].join('\n\n'),
)
})
it('snapshot rejected: the report opens, the alert names the reason, no archive kept', async () => {
const report = reportWithHip()
importMock.mockResolvedValue(
archived(report, null, { snapshotRejected: 'caps' }),
)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertText()).toBe(
fr['home.import.snapshot_rejected']!.replace(
'{reason}',
fr['home.import.snapshot_reason.caps']!,
),
)
})
it('attachment_stripped → its error message, nothing opened', async () => {
importMock.mockRejectedValue(new ImportError('attachment_stripped'))
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(
fr['home.import.error_attachment_stripped'],
)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
expect(alertMock()).not.toHaveBeenCalled()
})
})
@@ -21,6 +21,7 @@ import {
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { ArchiveReadOutcome } from '@faunosteo/domain'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
@@ -42,7 +43,11 @@ beforeAll(async () => {
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
})
@@ -51,14 +56,16 @@ afterEach(() => {
vi.unstubAllGlobals()
})
/** The outcome shape importReportFromPdf resolves with. */
/** The outcome shape importReportFromPdf resolves with (bare report, no archive). */
function outcome(patch: {
migrated: boolean
unresolvedZones?: number
unresolvedFindings?: number
}) {
}): ArchiveReadOutcome {
return {
report: minimalReport(sheet),
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
+40 -7
View File
@@ -1,14 +1,19 @@
/**
* The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF,
* on a synthetic v2 report with removed and unknown items, and on a v3 report.
* on a synthetic v2 report with removed and unknown items, on a v3 report
* and on a Step 6 envelope (archive header line).
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { readReportDocument, type ReportV2 } from '@faunosteo/domain'
import { readAttachedDocument } from '@/pdf/attachment'
import {
readArchiveDocument,
readReportDocument,
type ReportV2,
} from '@faunosteo/domain'
import { readAttachedDocument } from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import {
compareReport,
@@ -18,7 +23,7 @@ import {
renderSummary,
UNRESOLVED,
} from '../../scripts/compare/report'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OPTS = { locale: 'fr' as const, full: false }
@@ -32,9 +37,8 @@ function minimalV2(): ReportV2 {
}
function compareRaw(raw: unknown, full = false) {
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
const migrated = (raw as { version: number }).version !== 3
return compareReport(raw, outcome, migrated, sheet, { ...OPTS, full })
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, { ...OPTS, full })
}
beforeAll(async () => {
@@ -165,6 +169,35 @@ describe('compareReport on unresolved items', () => {
expect(c.counts.unresolvedFindings).toBe(1)
})
it('prints the archive line of an envelope: snapshot kept, or rejected with its reason', () => {
const envelope = archiveEnvelope(
sheet,
minimalReport(sheet, {
observations: [
{
id: 'o-env',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
const kept = compareRaw(envelope)
expect(kept.source).toBe('v3')
expect(kept.header).toContain('archive v1 (snapshot kept)')
const text = renderComparison('env.pdf', kept).join('\n')
expect(text).toContain('hip@main left "Hanche (coxo-fémorale)"')
const rejected = compareRaw({ ...envelope, envelopeVersion: 2 })
expect(rejected.header).toContain(
'archive v1 (snapshot rejected: unsupported_envelope)',
)
expect(compareRaw(envelope.report).header).not.toContain(
'archive v1 (snapshot kept)',
)
})
it('warns when a v3 report was written on another sheet document', () => {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'b'.repeat(64) },
+159 -14
View File
@@ -1,17 +1,31 @@
/**
* Replaces state.reportStore / state.reportStore.restore / .setters /
* state.draftMirror: the v3 store, its actions, the sessionStorage mirror
* and the migration of a v2 draft on restore.
* state.draftMirror: the v3 store, its actions, the sessionStorage mirror,
* the migration of a v2 draft on restore, and (Step 6) the archive kept
* beside the report and the rebase of a stale draft.
*/
import { beforeAll, beforeEach, describe, expect, it } from 'vitest'
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import {
createReportStore,
useReportStore,
emptyObservation,
} from '@/state/reportStore'
import { DRAFT_KEY, sessionStoragePersistence } from '@/state/persistence'
import {
ARCHIVE_KEY,
DRAFT_KEY,
sessionStoragePersistence,
} from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
import fullV2 from '../fixtures/report-v2.full.json'
let sheet: SheetIndex
@@ -20,8 +34,13 @@ beforeAll(async () => {
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
afterEach(() => vi.restoreAllMocks())
const draft = () => ({
date: '2026-10-10',
@@ -117,12 +136,12 @@ describe('sessionStorage mirror and restore', () => {
it('restores a v3 draft, and migrates a v2 draft left by the previous version', () => {
const v3 = minimalReport(sheet, { conclusion: 'kept' })
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(v3))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
useReportStore.getState().restoreDraft(sheet)
expect(useReportStore.getState().report?.conclusion).toBe('kept')
useReportStore.setState({ report: null })
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(fullV2))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
useReportStore.getState().restoreDraft(sheet)
const restored = useReportStore.getState().report!
expect(restored.version).toBe(3)
expect(
@@ -139,16 +158,16 @@ describe('sessionStorage mirror and restore', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
useReportStore.getState().restoreDraft(sheet)
expect(useReportStore.getState().report).toBe(before)
})
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore({
load: () => null,
save: (r) => saved.push(r),
})
const store = createReportStore(
{ load: () => null, save: (r) => saved.push(r) },
{ load: () => null, save: () => undefined },
)
store.getState().initReport(draft(), sheet.sheet.ref)
expect(saved.at(-1)).toMatchObject({ version: 3 })
})
@@ -173,7 +192,133 @@ describe('store edge cases', () => {
})
it('restoreDraft with no draft leaves the store empty', () => {
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
useReportStore.getState().restoreDraft(sheet)
expect(useReportStore.getState().report).toBeNull()
})
})
describe('archive of an imported Step 6 PDF', () => {
const OTHER_SHA = 'b'.repeat(64)
it('hydrateImport keeps the archive and mirrors it under osteo:archive', () => {
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
expect(useReportStore.getState().archive).toEqual(archive)
expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe(
report.id,
)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).id).toBe(report.id)
})
it('the archive is written at the session edges only, never on an edit', () => {
const archiveSaves: unknown[] = []
const store = createReportStore(
{ load: () => null, save: () => undefined },
{ load: () => null, save: (a) => archiveSaves.push(a) },
)
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
store.getState().hydrateImport({ report, archive })
expect(archiveSaves).toEqual([archive])
store.getState().setConclusion('edited')
store.getState().addObservation()
store.getState().setRecommendations('again')
expect(archiveSaves).toHaveLength(1)
expect(store.getState().report?.conclusion).toBe('edited')
store.getState().reset()
expect(archiveSaves).toEqual([archive, null])
})
it('restoreDraft brings the archive back with the draft', () => {
const report = minimalReport(sheet, { conclusion: 'kept' })
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
// Emptying the state clears the draft mirror, not the archive mirror.
useReportStore.setState({ report: null, archive: null })
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).not.toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(report))
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({ rebased: false })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toEqual(archive)
})
it.each([
[
'initReport',
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref),
],
[
'hydrateReport',
() => useReportStore.getState().hydrateReport(minimalReport(sheet)),
],
['reset', () => useReportStore.getState().reset()],
])('%s clears the archive and removes its mirror', (_name, act) => {
const report = minimalReport(sheet)
useReportStore
.getState()
.hydrateImport({ report, archive: archiveEnvelope(sheet, report) })
act()
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
it('restoreDraft rebases a draft written on another revision of the sheet, labels from the archived snapshot', () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o-stale',
zones: [
{ annotationId: 'point-gone', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
const archive = archiveEnvelope(sheet, stale)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
archive.sheetSnapshot.document.annotations.push({
...sheet.annotation('hip')!,
id: 'point-gone',
name: { fr: 'Point disparu', en: 'Gone point' },
} as Annotation)
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(stale))
sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify(archive))
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({
rebased: true,
unresolvedZones: 1,
unresolvedFindings: 0,
})
const restored = useReportStore.getState().report!
expect(restored.sheet).toEqual(sheet.sheet.ref)
expect(restored.observations[0]!.zones[0]).toMatchObject({
unresolved: true,
labelFrSnapshot: 'Point disparu',
})
expect(restored.observations[0]!.zones[1]!.unresolved).toBeUndefined()
expect(useReportStore.getState().archive).toEqual(archive)
// The mirror now holds the rebased draft.
expect(
JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256,
).toBe(sheet.sheet.ref.documentSha256)
})
it('ignores a corrupt or foreign osteo:archive', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
useReportStore.getState().restoreDraft(sheet)
expect(useReportStore.getState().report).not.toBeNull()
expect(useReportStore.getState().archive).toBeNull()
useReportStore.setState({ report: null })
sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify({ hello: 'world' }))
useReportStore.getState().restoreDraft(sheet)
expect(useReportStore.getState().archive).toBeNull()
})
})
+2 -1
View File
@@ -20,7 +20,8 @@ export async function inflateFlate(
): Promise<Uint8Array | null> {
if (typeof DecompressionStream === 'undefined') return null
try {
const stream = new Blob([bytes])
// The cast compiles under both the engine (node) and the app (DOM) libs.
const stream = new Blob([bytes as Uint8Array<ArrayBuffer>])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
const reader = stream.getReader()
+3
View File
@@ -26,6 +26,9 @@ importers:
'@faunosteo/domain':
specifier: workspace:*
version: link:../../packages/domain
'@faunosteo/pdf':
specifier: workspace:*
version: link:../../packages/pdf
'@faunosteo/supabase':
specifier: workspace:*
version: link:../../packages/supabase