8.0 KiB
8.0 KiB
CONTRACT — step-06 phase 3 engine
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: active (phases 1 and 2 landed)
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3
REQUEST (IMMUTABLE)
Create packages/pdf (@faunosteo/pdf): the browser-free PDF engine that exports a report archive from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, exportedAt) and reads an archive back (layered reading). Render code moves from apps/app/src/pdf with its behaviour frozen by the Phase 0 goldens. The app is NOT wired in this phase (Phase 4); apps/app/src is not modified.
ACCEPTANCE CRITERIA
- Package scaffold:
packages/pdf/{package.json,tsconfig.json,vitest.config.ts,eslint.config.js,src/,tests/}following packages/domain conventions; dependenciespdf-lib ^1.17.1,@pdf-lib/standard-fonts ^1.0.0(forEncodings.WinAnsi),@faunosteo/domain workspace:*,@faunosteo/anatomy workspace:*,@xmldom/xmldom ^0.9.8; devDependencies as domain plus@resvg/resvg-js(latest 2.x) and@pdf-lib/upng ^1.0.1(PNG decode in tests); tsconfiglib: ["ES2022"],types: ["node","vitest/globals"]; eslint onsrc/**:no-restricted-globalsfor fetch, window, document, Image, DOMParser, XMLSerializer, navigator, Buffer, process, require andno-restricted-importsfor patterns@/*,react*,node:*; vitestenvironment: 'node'. Dockerfile copiespackages/pdf/package.json;packages/README.mdrow updated. CHECK: cd packages/pdf && corepack pnpm typecheck && corepack pnpm lint && echo ok EXPECT: ok - Public API of
packages/pdf/src/index.tsexactly spec §13:exportReportArchive,exportFromEnvelope,readReportArchive,readAttachedDocument,ArchiveReadError(kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version),ArchiveExportError(kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages),Rasterizer,ExportInput,ExportResult,ExportWarning,PdfLocale,defaultPdfLabels,PDF_KEYWORD,MAX_PDF_BYTES,MAX_ATTACHMENT_BYTES, pluscomposeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): stringfor tests and the app. - Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images:
kind 'png'→ base64 decoded withatob→embedPng;kind 'svg'→ sanitised + rasterised at width 1200 (height from its viewBox, same clamp) →embedPng; each slot fails alone (logo_failedwarning); view raster failure → page without image +view_raster_failed; parallel rasterisation, sequential embedding in view order;exportedAtdrives every date;setKeywords([PDF_KEYWORD]); envelope attached pretty-printed asosteo-report.json, descriptionFaunosteo report archive v1. - Goldens (T3):
tests/goldens.test.tsreproduces every Phase 0 golden underapps/app/tests/fixtures/goldens/step6/for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by readingapps/app/tests/helpers/legacyLeaves.tslogic, copy what you need intotests/helpers/), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical (Phase 0 recorded images and links PER LOCALE:images.<report>.<locale>.<logos>.json,links.<report>.<locale>.<logos>.json, because the footer centres the powered-by block on the label width); views facts identical excepttitlesanddataAttributes(hidden markers are absent in the engine and the layer<g>loses itsdata-layer/data-view-id: asserttitles≥ highlighted count anddataAttributes === 0instead of the golden's 2). Logo modes:nologos= Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG;logos= Branding built from the realapps/app/publicfiles (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG for views AND for the partner SVG (same constants and the same single stub as Phase 0, seeapps/app/tests/helpers/goldens.ts). Compose throughcomposeViewSvgfrom@faunosteo/anatomy/render(genericroot: ComposeElement, xmldomElementsatisfies it) withhighlight: { annotationIds, halo: view.kind === 'main' }. Any mismatch is a visible change: do not "fix" the golden; report it. CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3 EXPECT: Tests .* passed - T1 no-sheet re-export (
tests/reexport.test.ts): export demo from a snapshot built withbuildSheetSnapshoton the draft loaded fromsupabase/seed/anatomical-sheets/equine/draft/→readReportArchive→exportFromEnvelope→ identical text/images/views facts; envelope deep-equal minusexportedAt; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope). - Read (
tests/read.test.ts, T4 T5 T6): roundtrip envelope →readReportArchive→archivedeep-equals the exported envelope,origin 'envelope_v1';apps/app/tests/fixtures/report-v2.full.pdfandreport-v2.minimal.pdf→'v2', migrated, then re-export → import again equals; the 612-leaf v2 report (recipe from legacyLeaves) → 29 unresolved findings kept through export/import;report-v3.bare.pdf→'bare_v3',archive null; envelope v2 wrapper → report kept +snapshotRejected 'unsupported_envelope'; envelope v1 with report v4 →incompatible_versionfoundVersion 4; bareversion: 7→ 7; a PDF withKeywordscontainingfaunosteo-archiveand no attachment →attachment_stripped; a foreign PDF →no_attachment; the Filespec namedosteo-report.jsonis chosen over an earlier unrelatedEmbeddedFilein a crafted PDF; > 50 MiB →invalid_pdf. - Security (
tests/security.test.ts, T8): 5 assets, a 3 MiB asset, depth 9, 1,025 annotations, a view chain cycle, a danglingsvg_asset_id,sheet_mismatch→ report imported andsnapshotRejectedwith the right reason; hostile SVG assets (<script>,onload,javascript:href, external<image>,<!ENTITY>,<style>withurl(http…), 257<use>, rootviewBox="0 0 1 100000") → removed / refused / clamped as spec §15, the export still succeeds for the removable ones with the hostile parts gone, andassertSnapshotrefuses the oversized ones at export with a typed error and no file;__proto__ids harmless; 24 MB inflate bomb → null (move the existing test);horse.svgandPaws_in_harmony.svgsanitise withremoved: []and a serialisation byte-identical to the parsed input. - Text (
tests/text.test.ts, T9):safeTextkeeps en dash, em dash, accented letters,•,·; replaces⚠,→, an emoji by?; strips\t, U+2028, ESC;wrapLinesand every drawText go through it (a report with⚠in a comment exports without throwing);formatDatereturns a non-ISO input unchanged. - Raster (
tests/raster.test.ts, T10, resvg): a realRasterizerbuilt on@resvg/resvg-js(fitTo width) renders the demo report's main and head highlighted views: PNG width = 1200, height = requested ±1, pixels within ±24 of#b85a3fpresent, non-white ratio in [0.01, 0.9]; a rasterizer that throws yields a PDF whose page has no image and oneview_raster_failedwarning. - Size (T7): demo envelope attachment stored bytes (the EmbeddedFile stream
contents.lengthfound throughenumerateIndirectObjects) < 250,000; the test prints stored and raw sizes fornologosandlogosbrandings. - Everything green:
corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:runin packages/pdf, andcorepack pnpm -r typecheckat the root;apps/app/srcuntouched. CHECK: git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l EXPECT: 0
FILE SCOPE
packages/pdf/** (new), Dockerfile (one COPY line), packages/README.md (one row), pnpm-lock.yaml (install). Nothing under apps/app/src, packages/domain, packages/anatomy.