From 293a6e0b3693af63ffdeb2029310113262b0f129 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 16:09:39 +0200 Subject: [PATCH] fix(pdf): bundle the branding assets into the app (no fetch at export), export returns its warnings and the editor reports missing elements --- CLAUDE.md | 9 ++- apps/app/src/app/routes/EditorRoute.tsx | 18 ++++- .../brand}/faunosteo-horizontal-com-512.png | Bin .../brand/faunosteo-logo-horizontal-512.png} | Bin .../assets/brand/paws-in-harmony.svg} | 0 .../assets}/brand/zenquality-logo-fr.png | Bin apps/app/src/components/brand/Footer.tsx | 3 +- apps/app/src/i18n/en.ts | 2 + apps/app/src/i18n/fr.ts | 2 + apps/app/src/pdf/branding.ts | 71 +++++------------- apps/app/src/pdf/export.ts | 20 +++-- apps/app/tests/fixtures/README.md | 4 +- apps/app/tests/helpers/goldens.ts | 57 +++++--------- apps/app/tests/unit/migration.leaves.test.ts | 7 +- apps/app/tests/unit/pdf.export.app.test.ts | 54 +++++++------ apps/app/tests/unit/pdf.goldens.test.ts | 16 ++-- apps/app/tests/unit/pdf.roundtrip.test.ts | 62 +++++++++------ .../unit/routes.EditorRoute.export.test.tsx | 27 +++++-- docs/PDF-FORMAT.md | 2 + packages/pdf/tests/helpers/draft.ts | 2 + packages/pdf/tests/helpers/goldens.ts | 22 +++--- packages/pdf/tests/security.test.ts | 6 +- 22 files changed, 199 insertions(+), 185 deletions(-) rename apps/app/{public/assets => src/assets/brand}/faunosteo-horizontal-com-512.png (100%) rename apps/app/{public/assets/faunosteo_logo_horizontal-512.png => src/assets/brand/faunosteo-logo-horizontal-512.png} (100%) rename apps/app/{public/Paws_in_harmony.svg => src/assets/brand/paws-in-harmony.svg} (100%) rename apps/app/{public => src/assets}/brand/zenquality-logo-fr.png (100%) diff --git a/CLAUDE.md b/CLAUDE.md index b0cea08c..65e20226 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -153,10 +153,11 @@ pnpm format # Prettier write ``` faunosteo/ ├─ apps/app/ ← @faunosteo/app (everything below until packages/) -├─ public/ ← logos only (no anatomy asset: the sheet is bundled) +├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset) ├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none) ├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts) ├─ src/ +│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched │ ├─ app/ │ │ ├─ App.tsx ← root router │ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx @@ -187,7 +188,7 @@ faunosteo/ │ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx │ ├─ 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 +│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → 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 @@ -258,12 +259,12 @@ SVG interaction PDF export (app side: apps/app/src/pdf, engine: packages/pdf) → exportReportToPdf(report, index, { locale }) - → buildSheetSnapshot(index.sheet, report) + loadBranding() (4 public/ files, each may fail alone) + defaultPdfLabels + → buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels → exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt }) assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard) → per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page → conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1 - → { pdf, envelope, warnings } → browser download + → { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views → exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet) PDF import diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index d43f07a4..491ec754 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -28,11 +28,17 @@ import { } from '@/services/zoneInteraction' import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' +import type { ExportWarning } from '@faunosteo/pdf' import { useT } from '@/i18n/useT' import { DEFAULT_SPECIES_ID } from './NewReportRoute' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' +/** What the PDF lacks, named for the practitioner: logo slots and view ids. */ +function missingItemsOf(warnings: readonly ExportWarning[]): string[] { + return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId)) +} + /** Editor on the reference sheet: wires the canvas, the pickers and the store. */ export default function EditorRoute() { const navigate = useNavigate() @@ -144,14 +150,22 @@ export default function EditorRoute() { if (!report) return setExporting(true) try { - const bytes = await exportReportToPdf(report, index, { locale }) - const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' }) + const { pdf, warnings } = await exportReportToPdf(report, index, { + locale, + }) + const blob = new Blob([pdf as BlobPart], { type: 'application/pdf' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = `bilan-${report.animal.name}-${report.date}.pdf` a.click() URL.revokeObjectURL(url) + const missing = missingItemsOf(warnings) + if (missing.length) { + window.alert( + t('editor.export_warnings').replace('{items}', missing.join(', ')), + ) + } } catch (err) { console.error('PDF export failed', err) window.alert(t('editor.export_failed')) diff --git a/apps/app/public/assets/faunosteo-horizontal-com-512.png b/apps/app/src/assets/brand/faunosteo-horizontal-com-512.png similarity index 100% rename from apps/app/public/assets/faunosteo-horizontal-com-512.png rename to apps/app/src/assets/brand/faunosteo-horizontal-com-512.png diff --git a/apps/app/public/assets/faunosteo_logo_horizontal-512.png b/apps/app/src/assets/brand/faunosteo-logo-horizontal-512.png similarity index 100% rename from apps/app/public/assets/faunosteo_logo_horizontal-512.png rename to apps/app/src/assets/brand/faunosteo-logo-horizontal-512.png diff --git a/apps/app/public/Paws_in_harmony.svg b/apps/app/src/assets/brand/paws-in-harmony.svg similarity index 100% rename from apps/app/public/Paws_in_harmony.svg rename to apps/app/src/assets/brand/paws-in-harmony.svg diff --git a/apps/app/public/brand/zenquality-logo-fr.png b/apps/app/src/assets/brand/zenquality-logo-fr.png similarity index 100% rename from apps/app/public/brand/zenquality-logo-fr.png rename to apps/app/src/assets/brand/zenquality-logo-fr.png diff --git a/apps/app/src/components/brand/Footer.tsx b/apps/app/src/components/brand/Footer.tsx index 84ff2c6b..f41fc4c2 100644 --- a/apps/app/src/components/brand/Footer.tsx +++ b/apps/app/src/components/brand/Footer.tsx @@ -1,5 +1,6 @@ import { useConfig } from '@/app/providers/ConfigProvider' import { useT } from '@/i18n/useT' +import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url' export default function Footer() { const cfg = useConfig() @@ -37,7 +38,7 @@ export default function Footer() { className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium" > Paws in Harmony diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 6ae7debb..8790af36 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -66,6 +66,8 @@ export const en: Dict = { 'editor.export': 'Export as PDF', 'editor.exporting': 'Generating…', 'editor.export_failed': 'PDF generation failed. Retry or contact support.', + 'editor.export_warnings': + 'PDF exported with missing elements: {items}. Check the browser console.', 'editor.edit_infos': 'Edit info', 'editor.edit_dialog_title': 'Edit information', 'editor.disclaimer_title': 'Legal scope of animal osteopathy', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 1f0f5139..ad68956e 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -72,6 +72,8 @@ export const fr: Dict = { 'editor.exporting': 'Génération…', 'editor.export_failed': 'Échec de la génération du PDF. Réessayez ou contactez le support.', + 'editor.export_warnings': + 'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.', 'editor.edit_infos': 'Modifier les infos', 'editor.edit_dialog_title': 'Modifier les informations', 'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale", diff --git a/apps/app/src/pdf/branding.ts b/apps/app/src/pdf/branding.ts index 04adb777..8023773c 100644 --- a/apps/app/src/pdf/branding.ts +++ b/apps/app/src/pdf/branding.ts @@ -1,11 +1,14 @@ import type { Branding, ImageAsset } from '@faunosteo/domain' +import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline' +import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline' +import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline' +import partnerLogoSvg from '@/assets/brand/paws-in-harmony.svg?raw' /** * 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. + * the four logo files bundled with the application (`src/assets/brand`), so + * an export needs no network and no deployed file, plus the credit URLs. The + * result travels inside the archive, so a re-export never needs them again. */ // shortcut: the site URL and the credit constants belong to the runtime @@ -20,62 +23,22 @@ const PARTNER = { 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' +const PNG_DATA_URL_PREFIX = 'data:image/png;base64,' -/** 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 { - const resp = await fetch(url) - if (!resp.ok) throw new Error(`HTTP ${resp.status}`) - return resp -} - -async function pngAsset(url: string): Promise { - const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer()) - return { kind: 'png', base64: bytesToBase64(bytes) } -} - -async function svgAsset(url: string): Promise { - 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, - url: string, -): Promise { - try { - return await load - } catch (err) { - console.warn(`Branding asset ${url} skipped:`, err) - return null +/** A `?inline` PNG import is a base64 data URL; the engine wants the base64 alone. */ +function pngAsset(dataUrl: string): ImageAsset { + if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) { + throw new Error('bundled logo is not a base64 PNG data URL') } + return { kind: 'png', base64: dataUrl.slice(PNG_DATA_URL_PREFIX.length) } } export async function loadBranding(): Promise { - 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 }, + headerLogo: pngAsset(headerLogoDataUrl), + footerLogo: pngAsset(footerLogoDataUrl), + poweredBy: { logo: pngAsset(poweredByLogoDataUrl), ...POWERED_BY }, + partner: { logo: { kind: 'svg', svg: partnerLogoSvg }, ...PARTNER }, } } diff --git a/apps/app/src/pdf/export.ts b/apps/app/src/pdf/export.ts index a555ed9b..d6dadbc4 100644 --- a/apps/app/src/pdf/export.ts +++ b/apps/app/src/pdf/export.ts @@ -1,5 +1,9 @@ import { buildSheetSnapshot, type Report } from '@faunosteo/domain' -import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf' +import { + defaultPdfLabels, + exportReportArchive, + type ExportWarning, +} from '@faunosteo/pdf' import type { Locale } from '@/i18n/types' import type { SheetIndex } from '@/services/sheetIndex' import { loadBranding } from './branding' @@ -9,17 +13,23 @@ export interface PdfExportOptions { locale: Locale } +export interface PdfExportResult { + pdf: Uint8Array + /** Non-fatal engine warnings: a logo or a view that failed to embed. */ + warnings: ExportWarning[] +} + /** * 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. + * the branding comes from the bundled logos, the browser rasterises the + * views. Warnings are logged and returned for the caller to surface. */ export async function exportReportToPdf( report: Report, index: SheetIndex, opts: PdfExportOptions, -): Promise { +): Promise { const result = await exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), @@ -32,5 +42,5 @@ export async function exportReportToPdf( for (const warning of result.warnings) { console.warn('PDF export warning', warning) } - return result.pdf + return { pdf: result.pdf, warnings: result.warnings } } diff --git a/apps/app/tests/fixtures/README.md b/apps/app/tests/fixtures/README.md index c5a979c6..6d9b7020 100644 --- a/apps/app/tests/fixtures/README.md +++ b/apps/app/tests/fixtures/README.md @@ -30,8 +30,8 @@ What the PDF pipeline produced right before the Step 6 refactor, recorded by Reports: `v2full` (`report-v2.full.json` migrated), `demo` (`report-v3.demo.json`), `v2unresolved` (legacy `sphenoid` and `ssb` leaves plus one `frontal` leaf, migrated; zone-less, so its `images` and `views` goldens are empty). Logo modes: `nologos` -(fetch 404, 1×1 rasteriser) and `logos` (fetch serves the four `public/` logo files, -rasteriser stubbed to a 2×1 PNG). +(every branding slot empty, 1×1 rasteriser) and `logos` (the four logo files bundled +under `apps/app/src/assets/brand`, rasteriser stubbed to a 2×1 PNG). Never regenerate these files without a user decision; the Step 6 engine must reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run diff --git a/apps/app/tests/helpers/goldens.ts b/apps/app/tests/helpers/goldens.ts index 4c742eb1..cf31b2cf 100644 --- a/apps/app/tests/helpers/goldens.ts +++ b/apps/app/tests/helpers/goldens.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' import { expect, vi } from 'vitest' @@ -12,8 +12,14 @@ import { PDFPage, PDFString, } from 'pdf-lib' -import type { Observation, Report, SheetSnapshot } from '@faunosteo/domain' +import type { + Branding, + Observation, + Report, + SheetSnapshot, +} from '@faunosteo/domain' import { composeHighlightedViewSvg } from '@faunosteo/pdf' +import { nologosBranding } from './sheet' /** * Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine, @@ -41,7 +47,6 @@ export const TWO_BY_ONE_PNG = Uint8Array.from( const HERE = dirname(fileURLToPath(import.meta.url)) export const FIXTURES_DIR = resolve(HERE, '../fixtures') export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6') -const PUBLIC_DIR = resolve(HERE, '../../public') /** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */ export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1' @@ -179,42 +184,16 @@ export async function readLinks(bytes: Uint8Array): Promise { return out } -const LOGO_FILES: Readonly> = { - '/assets/faunosteo_logo_horizontal-512.png': - 'assets/faunosteo_logo_horizontal-512.png', - '/assets/faunosteo-horizontal-com-512.png': - 'assets/faunosteo-horizontal-com-512.png', - '/brand/zenquality-logo-fr.png': 'brand/zenquality-logo-fr.png', - '/Paws_in_harmony.svg': 'Paws_in_harmony.svg', -} - -function serveLogo(path: string): Response { - const relative = LOGO_FILES[path] - const file = relative ? resolve(PUBLIC_DIR, relative) : null - if (!file || !existsSync(file)) - return new Response('not found', { status: 404 }) - return new Response(new Uint8Array(readFileSync(file)), { status: 200 }) -} - -/** 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) => - 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 }), - ) +/** + * The branding of one logo mode, for a test that mocks `@/pdf/branding`: + * `logos` is the real module (the bundled files), `nologos` every slot + * empty with the credits' fallback texts (the Phase 0 fetch 404). + */ +export async function brandingOf(mode: LogoMode): Promise { + if (mode === 'nologos') return nologosBranding() + const real = + await vi.importActual('@/pdf/branding') + return real.loadBranding() } const HIGHLIGHT_FILL = '#b85a3f' diff --git a/apps/app/tests/unit/migration.leaves.test.ts b/apps/app/tests/unit/migration.leaves.test.ts index aaa74260..4a72ebd5 100644 --- a/apps/app/tests/unit/migration.leaves.test.ts +++ b/apps/app/tests/unit/migration.leaves.test.ts @@ -31,9 +31,6 @@ 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,7 +57,9 @@ describe('the 612 legacy leaves in the application', () => { }) it('keeps every finding, resolved or not, through an archive PDF export and import', async () => { - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const { pdf: 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') diff --git a/apps/app/tests/unit/pdf.export.app.test.ts b/apps/app/tests/unit/pdf.export.app.test.ts index 208a26f0..e62d4eb3 100644 --- a/apps/app/tests/unit/pdf.export.app.test.ts +++ b/apps/app/tests/unit/pdf.export.app.test.ts @@ -19,6 +19,7 @@ import { buildSheetIndex, buildSheetSnapshot, ReportSchema, + type Branding, type FindingCategory, type FindingNode, type Report, @@ -33,8 +34,6 @@ import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet } from '../helpers/sheet' import { FIXTURES_DIR, - installFetch, - installLogoFetch, ONE_PX_PNG, readLinks, recordDrawing, @@ -50,10 +49,17 @@ vi.mock('@/pdf/browserRasterizer', async () => { const { TWO_BY_ONE_PNG } = await import('../helpers/goldens') return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) } }) +// The bundled branding, unless a scenario swaps the deployment's logos. +const branding = vi.hoisted(() => ({ current: null as Branding | null })) +vi.mock('@/pdf/branding', async (importOriginal) => { + const real = await importOriginal() + return { + loadBranding: vi.fn(async () => branding.current ?? real.loadBranding()), + } +}) let sheet: SheetIndex let demo: Report -let restoreFetch: () => void = () => undefined beforeAll(async () => { sheet = await loadTestSheet() @@ -65,8 +71,8 @@ beforeAll(async () => { vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) afterEach(() => { - restoreFetch() - restoreFetch = () => undefined + branding.current = null + vi.unstubAllGlobals() }) afterAll(() => vi.restoreAllMocks()) @@ -96,18 +102,9 @@ const facts = ({ texts, images, links }: Facts): Facts => ({ links, }) -/** The app export path, logos served from public/, under the recorder. */ -async function appExport( - index: SheetIndex, -): Promise { - const restore = installLogoFetch('logos') - try { - return await recorded(async () => ({ - pdf: await exportReportToPdf(demo, index, { locale: 'fr' }), - })) - } finally { - restore() - } +/** The app export path, bundled logos, under the recorder. */ +function appExport(index: SheetIndex): Promise { + return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' })) } async function archiveOf(pdf: Uint8Array): Promise { @@ -181,18 +178,27 @@ describe('the archive survives its resources', () => { const archive = await archiveOf(first.pdf) // The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG. + const onePx = { + kind: 'png' as const, + base64: Buffer.from(ONE_PX_PNG).toString('base64'), + } const otherSvg = '' - const fetchSpy = vi.fn((path: string) => - path.endsWith('.svg') - ? new Response(otherSvg, { status: 200 }) - : new Response(ONE_PX_PNG, { status: 200 }), - ) - restoreFetch = installFetch(fetchSpy) + branding.current = { + ...archive.branding, + headerLogo: onePx, + footerLogo: onePx, + poweredBy: { ...archive.branding.poweredBy!, logo: onePx }, + partner: { + ...archive.branding.partner!, + logo: { kind: 'svg', svg: otherSvg }, + }, + } const current = await loadBranding() expect(current.headerLogo).not.toBeNull() expect(current).not.toEqual(archive.branding) - fetchSpy.mockClear() + const fetchSpy = vi.fn() + vi.stubGlobal('fetch', fetchSpy) const again = await recorded(() => exportFromEnvelope(archive, REEXPORT)) expect(fetchSpy).not.toHaveBeenCalled() diff --git a/apps/app/tests/unit/pdf.goldens.test.ts b/apps/app/tests/unit/pdf.goldens.test.ts index 5810f8c6..b0952259 100644 --- a/apps/app/tests/unit/pdf.goldens.test.ts +++ b/apps/app/tests/unit/pdf.goldens.test.ts @@ -1,8 +1,9 @@ /** * 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, + * bundled sheet snapshotted, the bundled branding (mocked to every slot empty + * for the `nologos` mode, the real module for `logos`) 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. @@ -30,7 +31,6 @@ import { import { checkGolden, FIXTURES_DIR, - installLogoFetch, ONE_PX_PNG, readGolden, readLinks, @@ -48,6 +48,11 @@ const raster = vi.hoisted(() => ({ png: new Uint8Array() })) vi.mock('@/pdf/browserRasterizer', () => ({ browserRasterizer: vi.fn(async () => raster.png), })) +const logoMode = vi.hoisted(() => ({ current: 'nologos' as LogoMode })) +vi.mock('@/pdf/branding', async () => { + const { brandingOf } = await import('../helpers/goldens') + return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) } +}) const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const type ReportName = (typeof REPORTS)[number] @@ -103,15 +108,14 @@ async function exportWith( locale: Locale, ): Promise { raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG - const restoreFetch = installLogoFetch(mode) + logoMode.current = mode const recording = recordDrawing() try { - const bytes = await exportReportToPdf(report, sheet, { locale }) + const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale }) const { texts, images } = recording return { bytes, texts, images, links: await readLinks(bytes) } } finally { recording.stop() - restoreFetch() } } diff --git a/apps/app/tests/unit/pdf.roundtrip.test.ts b/apps/app/tests/unit/pdf.roundtrip.test.ts index 3bc756a7..04afe9f5 100644 --- a/apps/app/tests/unit/pdf.roundtrip.test.ts +++ b/apps/app/tests/unit/pdf.roundtrip.test.ts @@ -17,11 +17,16 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' -import { buildSheetSnapshot, type Observation } from '@faunosteo/domain' +import { + buildSheetSnapshot, + type Observation, + type Report, +} from '@faunosteo/domain' import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf' import { exportReportToPdf } from '@/pdf/export' import { importReportFromPdf, ImportError } from '@/pdf/import' import { formatDate } from '@/lib/dates' +import type { Locale } from '@/i18n/types' import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet, minimalReport } from '../helpers/sheet' @@ -34,29 +39,25 @@ vi.mock('@/pdf/browserRasterizer', async () => { /** The static PDF strings now belong to the engine's label set. */ const { fr, en } = defaultPdfLabels +/** The bytes of an app export (its warnings are not under test here). */ +async function exportPdf(report: Report, locale: Locale): Promise { + return (await exportReportToPdf(report, sheet, { locale })).pdf +} + const HERE = dirname(fileURLToPath(import.meta.url)) const fixture = (name: string) => new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name))) let sheet: SheetIndex let drawn: string[] = [] -const fetched: string[] = [] -const realFetch = globalThis.fetch beforeAll(async () => { sheet = await loadTestSheet() - globalThis.fetch = (async (input: RequestInfo | URL) => { - fetched.push(String(input)) - return new Response('not found', { status: 404 }) - }) as typeof fetch vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) -afterAll(() => { - globalThis.fetch = realFetch -}) +afterAll(() => vi.restoreAllMocks()) beforeEach(() => { drawn = [] - fetched.length = 0 vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function ( this: PDFPage, text: string, @@ -118,7 +119,7 @@ describe('export on a full v3 report (FR)', () => { observations: [fullObservation()], conclusion: 'ok', }) - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = await exportPdf(report, 'fr') const doc = await PDFDocument.load(bytes) expect(doc.getPageCount()).toBe(2) const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!) @@ -145,7 +146,7 @@ describe('export on a full v3 report (FR)', () => { 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 bytes = await exportPdf(report, locale) const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap) expect(out.migrated).toBe(false) expect(out.origin).toBe('envelope_v1') @@ -242,7 +243,7 @@ describe('PDF content on a two-observation report', () => { it('draws free findings, comments, the conclusion page and the header on every page', async () => { const report = fullReport() - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = await exportPdf(report, 'fr') const pages = (await PDFDocument.load(bytes)).getPageCount() expect(drawn).toContain(fr['pdf.section.free_findings']) expect(joined()).toContain('Sensibilité au garrot') @@ -260,7 +261,7 @@ describe('PDF content on a two-observation report', () => { }) it('sets the PDF metadata and the archive keyword', async () => { - const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) + const bytes = await exportPdf(fullReport(), 'fr') const doc = await PDFDocument.load(bytes) expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`) expect(doc.getAuthor()).toBe('Dr. Dupont') @@ -268,17 +269,28 @@ describe('PDF content on a two-observation report', () => { expect(doc.getKeywords()).toContain('faunosteo-archive/1') }) - it('fetches the logos at export time', async () => { - await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) - expect( - fetched.some( - (u) => u.endsWith('.png') || u.endsWith('Paws_in_harmony.svg'), - ), - ).toBe(true) + it('embeds the four bundled logos without any network request', async () => { + const fetchSpy = vi.fn() + vi.stubGlobal('fetch', fetchSpy) + try { + const { pdf, warnings } = await exportReportToPdf(fullReport(), sheet, { + locale: 'fr', + }) + expect(fetchSpy).not.toHaveBeenCalled() + expect(warnings).toEqual([]) + const out = await importReportFromPdf(pdf, sheet.sheet.migrationMap) + const branding = out.archive!.branding + expect(branding.headerLogo?.kind).toBe('png') + expect(branding.footerLogo?.kind).toBe('png') + expect(branding.poweredBy?.logo?.kind).toBe('png') + expect(branding.partner?.logo?.kind).toBe('svg') + } finally { + vi.unstubAllGlobals() + } }) 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 bytes = await exportPdf(fullReport(), 'fr') const doc = await PDFDocument.load(bytes) const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o), @@ -368,7 +380,7 @@ describe('import of the frozen v2 archive PDFs', () => { ) // Re-export and re-import: stable. const again = await importReportFromPdf( - await exportReportToPdf(report, sheet, { locale: 'fr' }), + await exportPdf(report, 'fr'), sheet.sheet.migrationMap, ) expect(again.report).toEqual(report) @@ -440,7 +452,7 @@ describe('import of the frozen v2 archive PDFs', () => { expect(out.unresolvedZones).toBe(1) // The migrated document is a valid v3 document: exporting it again keeps the flags. const again = await importReportFromPdf( - await exportReportToPdf(out.report, sheet, { locale: 'en' }), + await exportPdf(out.report, 'en'), sheet.sheet.migrationMap, ) expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true) diff --git a/apps/app/tests/unit/routes.EditorRoute.export.test.tsx b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx index 1037c6bd..24a1e274 100644 --- a/apps/app/tests/unit/routes.EditorRoute.export.test.tsx +++ b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx @@ -1,8 +1,8 @@ /** * Step 6 Phase 0 characterisation of the export flow on the editor route, * with `exportReportToPdf` mocked: the call shape (store report, loaded - * index, locale), the download name and the failure alert. Phase 4 adapts - * only the mocked module path and the call-shape assertion. + * index, locale), the download name, the failure alert and the alert that + * names what the exported PDF lacks when the engine warned. */ import { describe, @@ -27,6 +27,7 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet' vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() })) const exportMock = vi.mocked(exportReportToPdf) +const PDF_BYTES = new Uint8Array([37, 80, 68, 70]) let sheet: SheetIndex const downloads: string[] = [] @@ -74,7 +75,7 @@ async function mountAndExport(label: string): Promise { describe('EditorRoute export', () => { it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => { - exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70])) + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) await mountAndExport(fr['editor.export']!) await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) const [report, index, options] = exportMock.mock.calls[0]! @@ -85,14 +86,14 @@ describe('EditorRoute export', () => { it('passes the active locale (EN)', async () => { useLocaleStore.setState({ locale: 'en' }) - exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70])) + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) await mountAndExport(en['editor.export']!) await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' }) }) it('downloads bilan--.pdf through a blob URL it then revokes', async () => { - exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70])) + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) await mountAndExport(fr['editor.export']!) await waitFor(() => expect(downloads).toHaveLength(1)) expect(downloads[0]).toBe('bilan-Mistral-2026-10-10.pdf') @@ -103,6 +104,22 @@ describe('EditorRoute export', () => { expect(window.alert).not.toHaveBeenCalled() }) + it('downloads then alerts editor.export_warnings naming the failed logo slots and views', async () => { + exportMock.mockResolvedValue({ + pdf: PDF_BYTES, + warnings: [ + { kind: 'logo_failed', slot: 'headerLogo' }, + { kind: 'view_raster_failed', observationId: 'obs-1', viewId: 'head' }, + ], + }) + await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(window.alert).toHaveBeenCalledTimes(1)) + expect(downloads).toEqual(['bilan-Mistral-2026-10-10.pdf']) + expect(window.alert).toHaveBeenCalledWith( + 'PDF exporté avec des éléments manquants : headerLogo, head. Vérifiez la console du navigateur.', + ) + }) + it('alerts editor.export_failed when the export rejects', async () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) exportMock.mockRejectedValue(new Error('render exploded')) diff --git a/docs/PDF-FORMAT.md b/docs/PDF-FORMAT.md index 436edbd7..76dc66ca 100644 --- a/docs/PDF-FORMAT.md +++ b/docs/PDF-FORMAT.md @@ -84,6 +84,8 @@ rules as the catalog): | `assets` | the SVG text of every asset a view reaches, with the catalog's content hash when known | `branding` is the exact set of images, URLs and credit texts used at export; +the application builds it from logos bundled at build time +(`apps/app/src/assets/brand`), so the export makes no network request. `labels` is the engine dictionary in both languages. A re-export of the archive uses these three blocks and nothing from the current application, so a new logo, a reworded heading or a curated sheet never changes how an old diff --git a/packages/pdf/tests/helpers/draft.ts b/packages/pdf/tests/helpers/draft.ts index 276285b8..e273f08c 100644 --- a/packages/pdf/tests/helpers/draft.ts +++ b/packages/pdf/tests/helpers/draft.ts @@ -27,6 +27,8 @@ export const LEGACY_BASELINE = resolve( export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures') export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6') export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public') +/** The logo files the app bundles into its export branding. */ +export const BRAND_ASSETS_DIR = resolve(REPO_ROOT, 'apps/app/src/assets/brand') export function readJson(path: string): T { return JSON.parse(readFileSync(path, 'utf8')) as T diff --git a/packages/pdf/tests/helpers/goldens.ts b/packages/pdf/tests/helpers/goldens.ts index d9e33f61..3ae96650 100644 --- a/packages/pdf/tests/helpers/goldens.ts +++ b/packages/pdf/tests/helpers/goldens.ts @@ -19,7 +19,7 @@ import type { SheetSnapshot, } from '@faunosteo/domain' import { composeHighlightedViewSvg, type Rasterizer } from '../../src' -import { GOLDEN_DIR, PUBLIC_DIR } from './draft' +import { BRAND_ASSETS_DIR, GOLDEN_DIR } from './draft' /** * Step 6 Phase 0 goldens, replayed on the engine: the same recorder on @@ -60,8 +60,8 @@ const PARTNER = { fallbackText: '@paws.iin.harmony', } -function publicPng(relative: string): { kind: 'png'; base64: string } { - const bytes = readFileSync(resolve(PUBLIC_DIR, relative)) +function brandPng(file: string): { kind: 'png'; base64: string } { + const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file)) return { kind: 'png', base64: Buffer.from(bytes).toString('base64') } } @@ -76,20 +76,20 @@ export function nologosBranding(): Branding { } } -/** The four real `public/` files (Phase 0 fetch stub). */ +/** The four real logo files the app bundles (served by a fetch stub in Phase 0). */ export function logosBranding(): Branding { return { siteUrl: SITE_URL, - headerLogo: publicPng('assets/faunosteo_logo_horizontal-512.png'), - footerLogo: publicPng('assets/faunosteo-horizontal-com-512.png'), - poweredBy: { - logo: publicPng('brand/zenquality-logo-fr.png'), - ...POWERED_BY, - }, + headerLogo: brandPng('faunosteo-logo-horizontal-512.png'), + footerLogo: brandPng('faunosteo-horizontal-com-512.png'), + poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY }, partner: { logo: { kind: 'svg', - svg: readFileSync(resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'), 'utf8'), + svg: readFileSync( + resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'), + 'utf8', + ), }, ...PARTNER, }, diff --git a/packages/pdf/tests/security.test.ts b/packages/pdf/tests/security.test.ts index cf88be88..1b33da62 100644 --- a/packages/pdf/tests/security.test.ts +++ b/packages/pdf/tests/security.test.ts @@ -33,7 +33,7 @@ import { addLinkAnnotation } from '../src/render/linkAnnotation' import { parseSvg, serializeSvg } from '../src/svg/parse' import { sanitizeSvgRoot } from '../src/svg/sanitize' import { rasterSizeOf } from '../src/svg/view' -import { DRAFT_DIR, PUBLIC_DIR } from './helpers/draft' +import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft' import { FIXED_EXPORTED_AT, logosBranding, @@ -391,10 +391,10 @@ describe('hostile SVG assets', () => { expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 }) }) - it('horse.svg and Paws_in_harmony.svg pass with nothing removed and an identical serialisation', () => { + it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => { for (const file of [ resolve(DRAFT_DIR, 'assets/horse.svg'), - resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'), + resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'), ]) { const text = readFileSync(file, 'utf8') const pristine = serializeSvg(parseSvg(text))