diff --git a/Dockerfile b/Dockerfile index e5ae5525..e66a3733 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,6 +13,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ COPY apps/app/package.json apps/app/ COPY packages/domain/package.json packages/domain/ COPY packages/anatomy/package.json packages/anatomy/ +COPY packages/pdf/package.json packages/pdf/ COPY packages/supabase/package.json packages/supabase/ RUN pnpm install --frozen-lockfile diff --git a/packages/README.md b/packages/README.md index 96f5fd0d..527ad1b9 100644 --- a/packages/README.md +++ b/packages/README.md @@ -10,7 +10,7 @@ Planned packages and the step that creates each one: |---|---|---| | `@faunosteo/domain` | Zod schemas: anatomical sheet document + integrity rules (**created**, Step 4); report document, entitlement capabilities later | Step 4 (sheet model) | | `@faunosteo/anatomy` | legacy importer (**created**, Step 4b), curation pipeline: changeset → working draft + report migration map (**created**, Steps 4c/5), pure annotation-layer renderer `@faunosteo/anatomy/render` shared with the app (**created**, Step 5) | Step 4b (importer) | -| `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) | +| `@faunosteo/pdf` | browser-free PDF engine (**created**, Step 6): report archive export from explicit inputs (report, sheet snapshot, branding, labels, rasterizer), layered archive reading, SVG sanitiser, page renderers | Step 6 (PDF archives) | | `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) | | `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite, sheet publish gate | **created**, Step 3 | | `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web | diff --git a/packages/pdf/eslint.config.js b/packages/pdf/eslint.config.js new file mode 100644 index 00000000..f3859bf0 --- /dev/null +++ b/packages/pdf/eslint.config.js @@ -0,0 +1,48 @@ +import globals from 'globals' +import tseslint from 'typescript-eslint' + +/** + * The engine must run without a browser and without Node-only APIs + * (STEP6 §3.3): the restricted globals and imports apply to `src/**` only, + * tests may read fixtures with node:fs. + */ +const BROWSER_OR_NODE_GLOBALS = [ + 'fetch', + 'window', + 'document', + 'Image', + 'DOMParser', + 'XMLSerializer', + 'navigator', + 'Buffer', + 'process', + 'require', +] + +export default tseslint.config( + { ignores: ['node_modules/**'] }, + { + files: ['**/*.ts'], + extends: [...tseslint.configs.recommended], + languageOptions: { + globals: { ...globals.node, ...globals.es2022 }, + }, + rules: { + '@typescript-eslint/no-explicit-any': 'warn', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + }, + }, + { + files: ['src/**/*.ts'], + rules: { + 'no-restricted-globals': ['error', ...BROWSER_OR_NODE_GLOBALS], + 'no-restricted-imports': [ + 'error', + { patterns: ['@/*', 'react*', 'node:*'] }, + ], + }, + }, +) diff --git a/packages/pdf/package.json b/packages/pdf/package.json new file mode 100644 index 00000000..f44abaee --- /dev/null +++ b/packages/pdf/package.json @@ -0,0 +1,37 @@ +{ + "name": "@faunosteo/pdf", + "version": "0.1.0", + "private": true, + "description": "Faunosteo PDF engine: exports a report archive (pages + envelope attachment) from explicit inputs and reads an archive back, without a browser", + "license": "MIT", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest", + "test:run": "vitest run", + "lint": "eslint . --max-warnings 0", + "build": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@faunosteo/anatomy": "workspace:*", + "@faunosteo/domain": "workspace:*", + "@pdf-lib/standard-fonts": "^1.0.0", + "@xmldom/xmldom": "^0.9.8", + "pdf-lib": "^1.17.1" + }, + "devDependencies": { + "@pdf-lib/upng": "^1.0.1", + "@resvg/resvg-js": "^2.6.2", + "@types/node": "^20.19.41", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "typescript": "^5.7.2", + "typescript-eslint": "^8.19.0", + "vitest": "^3.2.7" + } +} diff --git a/packages/pdf/src/attachment/inflate.ts b/packages/pdf/src/attachment/inflate.ts new file mode 100644 index 00000000..3d4f477e --- /dev/null +++ b/packages/pdf/src/attachment/inflate.ts @@ -0,0 +1,43 @@ +/** + * Hard ceiling on an attachment, inflated or not: a report archive weighs a + * few hundred KB; anything bigger is a decompression bomb or corruption. + */ +export const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024 + +function concat(chunks: Uint8Array[], total: number): Uint8Array { + const out = new Uint8Array(total) + let offset = 0 + for (const chunk of chunks) { + out.set(chunk, offset) + offset += chunk.byteLength + } + return out +} + +/** FlateDecode under the cap. Null on failure or when the cap is exceeded. */ +export async function inflateFlate( + bytes: Uint8Array, +): Promise { + if (typeof DecompressionStream === 'undefined') return null + try { + const stream = new Blob([bytes]) + .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_ATTACHMENT_BYTES) { + await reader.cancel() + return null + } + chunks.push(value) + } + return concat(chunks, total) + } catch { + return null + } +} diff --git a/packages/pdf/src/attachment/read.ts b/packages/pdf/src/attachment/read.ts new file mode 100644 index 00000000..ff8c1a56 --- /dev/null +++ b/packages/pdf/src/attachment/read.ts @@ -0,0 +1,105 @@ +import { + PDFDict, + PDFHexString, + PDFName, + PDFRawStream, + PDFStream, + PDFString, + type PDFDocument, +} from 'pdf-lib' +import { ArchiveReadError } from '../errors' +import { inflateFlate, MAX_ATTACHMENT_BYTES } from './inflate' + +/** + * Finds the Faunosteo attachment of a loaded PDF: the Filespec whose file + * name starts with `osteo-report` first, else the first embedded file + * (today's behaviour, kept as the fallback). pdf-lib 1.17 exposes no + * attachment API, so this walks the indirect objects. + */ + +export const ATTACHMENT_NAME_PREFIX = 'osteo-report' +export const PDF_KEYWORD = 'faunosteo-archive/1' + +const TYPE = PDFName.of('Type') +const F = PDFName.of('F') + +function textOf(value: unknown): string | null { + if (value instanceof PDFString || value instanceof PDFHexString) { + return value.decodeText() + } + return null +} + +/** The embedded stream of a `/Filespec` named for a Faunosteo report. */ +function namedFilespecStream(dict: PDFDict): PDFStream | null { + if (dict.get(TYPE) !== PDFName.of('Filespec')) return null + const name = textOf(dict.lookup(F)) + if (name === null || !name.startsWith(ATTACHMENT_NAME_PREFIX)) return null + const files = dict.lookup(PDFName.of('EF')) + if (!(files instanceof PDFDict)) return null + const stream = files.lookup(F) + return stream instanceof PDFStream ? stream : null +} + +/** Today's heuristic: an `/EmbeddedFile` stream or a JSON-subtyped one. */ +function looksLikeEmbeddedJson(stream: PDFStream): boolean { + const type = String(stream.dict.lookup(TYPE) ?? '') + const subtype = String(stream.dict.lookup(PDFName.of('Subtype')) ?? '') + return ( + type.includes('EmbeddedFile') || + subtype.includes('application/json') || + subtype.includes('application#2Fjson') + ) +} + +function locateAttachment(pdfDoc: PDFDocument): PDFStream | null { + const objects = pdfDoc.context.enumerateIndirectObjects() + for (const [, object] of objects) { + if (!(object instanceof PDFDict)) continue + const stream = namedFilespecStream(object) + if (stream) return stream + } + for (const [, object] of objects) { + if (object instanceof PDFStream && looksLikeEmbeddedJson(object)) { + return object + } + } + return null +} + +/** Stream bytes, inflated when Flate-encoded; null when unreadable or over the cap. */ +async function attachmentBytes(stream: PDFStream): Promise { + const contents = + stream instanceof PDFRawStream ? stream.contents : stream.getContents() + if (contents.byteLength > MAX_ATTACHMENT_BYTES) return null + const filter = String(stream.dict.lookup(PDFName.of('Filter')) ?? '') + if (!filter.includes('FlateDecode')) return contents + return inflateFlate(contents) +} + +/** A PDF stamped as an archive but holding no attachment lost it in a viewer. */ +function missingAttachmentError(pdfDoc: PDFDocument): ArchiveReadError { + const stamped = (pdfDoc.getKeywords() ?? '').includes('faunosteo-archive') + return new ArchiveReadError(stamped ? 'attachment_stripped' : 'no_attachment') +} + +/** + * The raw JSON carried by the PDF, whatever its shape (bare report of any + * version or archive envelope), before any validation: what the archive + * check tool shows next to the read result. Throws ArchiveReadError. + */ +export async function readAttachedDocument( + pdfDoc: PDFDocument, +): Promise { + const stream = locateAttachment(pdfDoc) + if (!stream) throw missingAttachmentError(pdfDoc) + const bytes = await attachmentBytes(stream) + if (!bytes || bytes.byteLength > MAX_ATTACHMENT_BYTES) { + throw new ArchiveReadError('no_attachment') + } + try { + return JSON.parse(new TextDecoder().decode(bytes)) as unknown + } catch { + throw new ArchiveReadError('no_attachment') + } +} diff --git a/packages/pdf/src/attachment/write.ts b/packages/pdf/src/attachment/write.ts new file mode 100644 index 00000000..b328ac51 --- /dev/null +++ b/packages/pdf/src/attachment/write.ts @@ -0,0 +1,19 @@ +import { AFRelationship, type PDFDocument } from 'pdf-lib' + +export const ATTACHMENT_FILENAME = 'osteo-report.json' +export const ATTACHMENT_DESCRIPTION = 'Faunosteo report archive v1' + +/** The envelope bytes as a native embedded file; every date is `exportedAt`. */ +export async function attachEnvelope( + pdfDoc: PDFDocument, + bytes: Uint8Array, + exportedAt: Date, +): Promise { + await pdfDoc.attach(bytes, ATTACHMENT_FILENAME, { + mimeType: 'application/json', + description: ATTACHMENT_DESCRIPTION, + creationDate: exportedAt, + modificationDate: exportedAt, + afRelationship: AFRelationship.Data, + }) +} diff --git a/packages/pdf/src/branding.ts b/packages/pdf/src/branding.ts new file mode 100644 index 00000000..e76f0c9e --- /dev/null +++ b/packages/pdf/src/branding.ts @@ -0,0 +1,91 @@ +import type { PDFDocument, PDFImage } from 'pdf-lib' +import type { Branding, Credit, ImageAsset } from '@faunosteo/domain' +import type { ExportWarning, Rasterizer } from './types' +import { renderBrandingSvg } from './svg/view' + +/** + * The branding images embedded once per document. A PNG is decoded from + * its base64; an SVG is sanitised and rasterised at the view width. Each + * slot fails alone: the page prints the credit's fallback text instead and + * the export reports a `logo_failed` warning. + */ + +export type LogoSlot = Extract['slot'] + +export interface CreditAsset { + image: PDFImage | null + url: string + fallbackText: string +} + +export interface BrandingImages { + siteUrl: string + header: PDFImage | null + footer: PDFImage | null + poweredBy: CreditAsset | null + partner: CreditAsset | null +} + +function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64) + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i) + return bytes +} + +async function embedImage( + pdfDoc: PDFDocument, + asset: ImageAsset, + rasterizer: Rasterizer, +): Promise { + if (asset.kind === 'png') return pdfDoc.embedPng(base64ToBytes(asset.base64)) + const { svg, size } = renderBrandingSvg(asset.svg) + return pdfDoc.embedPng(await rasterizer(svg, size)) +} + +interface Embedder { + pdfDoc: PDFDocument + rasterizer: Rasterizer + warnings: ExportWarning[] +} + +async function embedSlot( + embedder: Embedder, + slot: LogoSlot, + asset: ImageAsset | null, +): Promise { + if (!asset) return null + try { + return await embedImage(embedder.pdfDoc, asset, embedder.rasterizer) + } catch { + embedder.warnings.push({ kind: 'logo_failed', slot }) + return null + } +} + +async function embedCredit( + embedder: Embedder, + slot: LogoSlot, + credit: Credit | null, +): Promise { + if (!credit) return null + return { + image: await embedSlot(embedder, slot, credit.logo), + url: credit.url, + fallbackText: credit.fallbackText, + } +} + +/** Embeds the four slots in a fixed order: header, footer, powered-by, partner. */ +export async function embedBranding( + embedder: Embedder, + branding: Branding, +): Promise { + return { + siteUrl: branding.siteUrl, + header: await embedSlot(embedder, 'headerLogo', branding.headerLogo), + footer: await embedSlot(embedder, 'footerLogo', branding.footerLogo), + poweredBy: await embedCredit(embedder, 'poweredBy', branding.poweredBy), + partner: await embedCredit(embedder, 'partner', branding.partner), + } +} diff --git a/packages/pdf/src/errors.ts b/packages/pdf/src/errors.ts new file mode 100644 index 00000000..dde9c6a3 --- /dev/null +++ b/packages/pdf/src/errors.ts @@ -0,0 +1,53 @@ +/** + * Typed failures of the engine. The app maps the kinds to its messages; no + * message here echoes untrusted input. + */ + +export type ArchiveReadErrorKind = + | 'invalid_pdf' + | 'no_attachment' + | 'attachment_stripped' + | 'incompatible_version' + +export class ArchiveReadError extends Error { + constructor( + public readonly kind: ArchiveReadErrorKind, + /** The report version found, for `incompatible_version`. */ + public readonly foundVersion?: number | null, + ) { + super(kind) + this.name = 'ArchiveReadError' + } +} + +export type ArchiveExportErrorKind = + | 'snapshot_invalid' + | 'snapshot_too_large' + | 'sheet_mismatch' + | 'too_many_pages' + +export class ArchiveExportError extends Error { + constructor( + public readonly kind: ArchiveExportErrorKind, + detail = '', + ) { + super(detail ? `${kind}: ${detail}` : kind) + this.name = 'ArchiveExportError' + } +} + +export type SvgRejection = + | 'doctype' + | 'malformed' + | 'not_svg' + | 'too_many_elements' + | 'too_deep' + | 'too_many_uses' + +/** An SVG text the sanitiser refuses outright (STEP6 §15). */ +export class SvgRejectedError extends Error { + constructor(public readonly reason: SvgRejection) { + super(`svg rejected: ${reason}`) + this.name = 'SvgRejectedError' + } +} diff --git a/packages/pdf/src/export.ts b/packages/pdf/src/export.ts new file mode 100644 index 00000000..3c5e2afb --- /dev/null +++ b/packages/pdf/src/export.ts @@ -0,0 +1,208 @@ +import { PDFDocument } from 'pdf-lib' +import { + assertSnapshot, + buildSheetIndex, + ENVELOPE_FORMAT, + ENVELOPE_VERSION, + snapshotIndexSource, + SnapshotError, + type Report, + type ReportArchiveEnvelope, + type SheetIndex, + type SheetSnapshot, +} from '@faunosteo/domain' +import { attachEnvelope } from './attachment/write' +import { MAX_ATTACHMENT_BYTES } from './attachment/inflate' +import { PDF_KEYWORD } from './attachment/read' +import { embedBranding, type BrandingImages } from './branding' +import { ArchiveExportError, SvgRejectedError } from './errors' +import { addConclusionPage } from './render/conclusionPage' +import type { RenderContext } from './render/context' +import { embedFonts } from './render/fonts' +import { drawFooter } from './render/footer' +import { addObservationPage } from './render/observationPage' +import { cleanSvgRoot } from './svg/view' +import type { + ExportInput, + ExportResult, + ExportWarning, + PdfLocale, + Rasterizer, +} from './types' + +/** + * Exports a report archive from explicit inputs and nothing else: the + * report, the sheet snapshot it was written on, the branding, the labels, + * the locale, a rasterizer and the export time (STEP6 §14 "Export"). The + * attachment embeds exactly what the pages were rendered from, so the file + * re-exports without the current catalog, assets or configuration. + */ + +export const PAGE_CAPS = { + observations: 500, + viewsPerObservation: 8, +} as const + +/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */ +function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot { + let parsed: SheetSnapshot + try { + parsed = assertSnapshot(sheet) + } catch (error) { + if (!(error instanceof SnapshotError)) throw error + const kind = + error.reason === 'caps' ? 'snapshot_too_large' : 'snapshot_invalid' + throw new ArchiveExportError(kind, error.reason) + } + for (const asset of parsed.assets) { + try { + cleanSvgRoot(asset.svg) + } catch (error) { + if (!(error instanceof SvgRejectedError)) throw error + throw new ArchiveExportError('snapshot_invalid', `asset ${error.reason}`) + } + } + return parsed +} + +/** Steps 2 and 3: the report belongs to this sheet and fits the page budget. */ +function assertExportable(report: Report, sheet: SheetSnapshot): void { + if ( + report.sheet.sheetId !== sheet.ref.sheetId || + report.sheet.documentSha256 !== sheet.ref.documentSha256 + ) { + throw new ArchiveExportError('sheet_mismatch') + } + if (report.observations.length > PAGE_CAPS.observations) { + throw new ArchiveExportError('too_many_pages', 'observations') + } + const tooManyViews = report.observations.some( + (o) => + new Set(o.zones.map((z) => z.viewId)).size > + PAGE_CAPS.viewsPerObservation, + ) + if (tooManyViews) throw new ArchiveExportError('too_many_pages', 'views') +} + +function buildEnvelope( + input: ExportInput, + sheet: SheetSnapshot, +): ReportArchiveEnvelope { + return { + format: ENVELOPE_FORMAT, + envelopeVersion: ENVELOPE_VERSION, + exportedAt: input.exportedAt.toISOString(), + locale: input.locale, + report: input.report, + sheetSnapshot: sheet, + branding: input.branding, + labels: input.labels, + } +} + +/** Step 4: pretty JSON under the attachment cap. */ +function encodeEnvelope(envelope: ReportArchiveEnvelope): Uint8Array { + const bytes = new TextEncoder().encode(JSON.stringify(envelope, null, 2)) + if (bytes.byteLength > MAX_ATTACHMENT_BYTES) { + throw new ArchiveExportError('snapshot_too_large', 'attachment') + } + return bytes +} + +/** Step 5: document information, every date the export time. */ +function setMetadata(pdfDoc: PDFDocument, input: ExportInput): void { + const labels = input.labels[input.locale] + pdfDoc.setTitle( + `${labels['pdf.title.suffix.bilan']}${input.report.animal.name}`, + ) + pdfDoc.setAuthor(input.report.practitioner.name) + pdfDoc.setSubject(labels['pdf.subject']) + pdfDoc.setKeywords([PDF_KEYWORD]) + pdfDoc.setCreationDate(input.exportedAt) + pdfDoc.setModificationDate(input.exportedAt) +} + +interface Pages { + pdfDoc: PDFDocument + input: ExportInput + sheet: SheetSnapshot + index: SheetIndex + ctx: RenderContext + branding: BrandingImages + warnings: ExportWarning[] +} + +/** Steps 8 and 9: one page per observation, the conclusion, footers everywhere. */ +async function drawPages(pages: Pages): Promise { + const { pdfDoc, input, ctx, branding } = pages + const headerAssets = { logo: branding.header, siteUrl: branding.siteUrl } + for (let i = 0; i < input.report.observations.length; i += 1) { + await addObservationPage({ + pdfDoc, + report: input.report, + observation: input.report.observations[i]!, + obsIndex: i, + sheet: pages.index, + snapshot: pages.sheet, + ctx, + headerAssets, + rasterizer: input.rasterizer, + warnings: pages.warnings, + }) + } + await addConclusionPage(pdfDoc, input.report, ctx, headerAssets) + const all = pdfDoc.getPages() + all.forEach((page, idx) => { + const pagination = { pageNumber: idx + 1, totalPages: all.length } + drawFooter(page, pagination, ctx, branding) + }) +} + +export async function exportReportArchive( + input: ExportInput, +): Promise { + const sheet = checkedSnapshot(input.sheet) + assertExportable(input.report, sheet) + const envelope = buildEnvelope(input, sheet) + const attachment = encodeEnvelope(envelope) + + const pdfDoc = await PDFDocument.create() + setMetadata(pdfDoc, input) + const fonts = await embedFonts(pdfDoc) + const warnings: ExportWarning[] = [] + const branding = await embedBranding( + { pdfDoc, rasterizer: input.rasterizer, warnings }, + input.branding, + ) + await drawPages({ + pdfDoc, + input, + sheet, + index: buildSheetIndex(snapshotIndexSource(sheet)), + ctx: { fonts, locale: input.locale, labels: input.labels[input.locale] }, + branding, + warnings, + }) + await attachEnvelope(pdfDoc, attachment, input.exportedAt) + return { pdf: await pdfDoc.save(), envelope, warnings } +} + +export interface ReexportOptions { + locale: PdfLocale + rasterizer: Rasterizer + exportedAt: Date +} + +/** Re-export from an archive alone: no sheet, no network, no configuration. */ +export function exportFromEnvelope( + env: ReportArchiveEnvelope, + opts: ReexportOptions, +): Promise { + return exportReportArchive({ + report: env.report, + sheet: env.sheetSnapshot, + branding: env.branding, + labels: env.labels, + ...opts, + }) +} diff --git a/packages/pdf/src/i18n/en.ts b/packages/pdf/src/i18n/en.ts new file mode 100644 index 00000000..2ea2aaae --- /dev/null +++ b/packages/pdf/src/i18n/en.ts @@ -0,0 +1,30 @@ +import type { PdfLabels } from '@faunosteo/domain' + +/** Verbatim copy of the app's EN strings the PDF read when Step 6 started. */ +export const en: PdfLabels = { + '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', + 'severity.mild': 'mild', + 'severity.moderate': 'moderate', + 'severity.severe': 'severe', + 'lateral.left': 'Left', + 'lateral.right': 'Right', + 'footer.powered_by': 'Powered by', + 'footer.in_partnership': 'In partnership with', +} diff --git a/packages/pdf/src/i18n/fr.ts b/packages/pdf/src/i18n/fr.ts new file mode 100644 index 00000000..b4bfdb72 --- /dev/null +++ b/packages/pdf/src/i18n/fr.ts @@ -0,0 +1,30 @@ +import type { PdfLabels } from '@faunosteo/domain' + +/** Verbatim copy of the app's FR strings the PDF read when Step 6 started. */ +export const fr: PdfLabels = { + '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", + 'severity.mild': 'légère', + 'severity.moderate': 'modérée', + 'severity.severe': 'sévère', + 'lateral.left': 'Gauche', + 'lateral.right': 'Droite', + 'footer.powered_by': 'Propulsé par', + 'footer.in_partnership': 'En partenariat avec', +} diff --git a/packages/pdf/src/i18n/index.ts b/packages/pdf/src/i18n/index.ts new file mode 100644 index 00000000..79edc00f --- /dev/null +++ b/packages/pdf/src/i18n/index.ts @@ -0,0 +1,6 @@ +import type { PdfLabelSet } from '@faunosteo/domain' +import { en } from './en' +import { fr } from './fr' + +/** The wording of the day, frozen into every archive the engine writes. */ +export const defaultPdfLabels: PdfLabelSet = { fr, en } diff --git a/packages/pdf/src/index.ts b/packages/pdf/src/index.ts new file mode 100644 index 00000000..58018a0c --- /dev/null +++ b/packages/pdf/src/index.ts @@ -0,0 +1,22 @@ +/** + * @faunosteo/pdf — the browser-free PDF engine (STEP6 §13). + */ +export { exportReportArchive, exportFromEnvelope } from './export' +export { readReportArchive, MAX_PDF_BYTES } from './read' +export { readAttachedDocument, PDF_KEYWORD } from './attachment/read' +export { MAX_ATTACHMENT_BYTES } from './attachment/inflate' +export { + ArchiveReadError, + ArchiveExportError, + type ArchiveReadErrorKind, + type ArchiveExportErrorKind, +} from './errors' +export type { + Rasterizer, + ExportInput, + ExportResult, + ExportWarning, + PdfLocale, +} from './types' +export { defaultPdfLabels } from './i18n' +export { composeHighlightedViewSvg } from './svg/view' diff --git a/packages/pdf/src/read.ts b/packages/pdf/src/read.ts new file mode 100644 index 00000000..bd1ed7fb --- /dev/null +++ b/packages/pdf/src/read.ts @@ -0,0 +1,51 @@ +import { PDFDocument } from 'pdf-lib' +import { + readArchiveDocument, + UnsupportedReportVersionError, + type ArchiveReadOutcome, + type ReportMigrationMap, +} from '@faunosteo/domain' +import { readAttachedDocument } from './attachment/read' +import { ArchiveReadError } from './errors' + +/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */ +export const MAX_PDF_BYTES = 50 * 1024 * 1024 + +async function loadPdf(pdfBytes: Uint8Array): Promise { + if (pdfBytes.byteLength > MAX_PDF_BYTES) { + throw new ArchiveReadError('invalid_pdf') + } + try { + return await PDFDocument.load(pdfBytes, { ignoreEncryption: true }) + } catch { + throw new ArchiveReadError('invalid_pdf') + } +} + +/** + * Reads a Faunosteo PDF back: size cap, PDF parse, attachment (filename + * first), JSON, then the layered reading of the domain (report first, then + * the envelope accepted whole or dropped with a reason). An unknown report + * version is `incompatible_version` with that version; any other content + * failure is `no_attachment`, as today. + */ +export async function readReportArchive( + pdfBytes: Uint8Array, + map: ReportMigrationMap, +): Promise { + const pdfDoc = await loadPdf(pdfBytes) + const data = await readAttachedDocument(pdfDoc) + try { + return readArchiveDocument(data, map) + } catch (error) { + // A numeric but unknown version is an incompatible Faunosteo report; no + // version at all is not a Faunosteo attachment (today's message). + if ( + error instanceof UnsupportedReportVersionError && + error.foundVersion !== null + ) { + throw new ArchiveReadError('incompatible_version', error.foundVersion) + } + throw new ArchiveReadError('no_attachment') + } +} diff --git a/packages/pdf/src/render/conclusionPage.ts b/packages/pdf/src/render/conclusionPage.ts new file mode 100644 index 00000000..84572512 --- /dev/null +++ b/packages/pdf/src/render/conclusionPage.ts @@ -0,0 +1,117 @@ +import { PageSizes, type PDFDocument } from 'pdf-lib' +import type { Report } from '@faunosteo/domain' +import { + COLOR_ACCENT, + COLOR_INK, + COLOR_MUTED, + EYEBROW_Y_OFFSET, + MARGIN_X, + SECTION_LABEL_GAP, + TITLE_RULE_OFFSET, + TITLE_RULE_WIDTH, + TITLE_Y_OFFSET, +} from './constants' +import type { RenderContext } from './context' +import { formatDate } from './dates' +import { drawHeader, type HeaderAssets } from './header' +import { drawText, wrapLines } from './text' + +const SECTION_TOP_GAP = 28 +const SECTION_BLOCK_GAP = 18 +const TEXT_LINE_HEIGHT = 14 + +interface ConclusionSection { + label: string + body: string + color?: typeof COLOR_INK +} + +function nextAppointmentText(report: Report, ctx: RenderContext): string { + const next = report.nextAppointment! + return next.kind === 'date' ? formatDate(next.date, ctx.locale) : next.text +} + +function conclusionSections( + report: Report, + ctx: RenderContext, +): ConclusionSection[] { + const { labels } = ctx + const sections: ConclusionSection[] = [ + { + label: labels['pdf.section.conclusion'], + body: report.conclusion || labels['pdf.empty'], + }, + { + label: labels['pdf.section.recommendations'], + body: report.recommendations || labels['pdf.empty'], + }, + ] + if (report.nextAppointment) { + sections.push({ + label: labels['pdf.section.next_appointment'], + body: nextAppointmentText(report, ctx) || labels['pdf.empty'], + color: COLOR_MUTED, + }) + } + return sections +} + +export async function addConclusionPage( + pdfDoc: PDFDocument, + report: Report, + ctx: RenderContext, + headerAssets: HeaderAssets, +): Promise { + const { fonts, labels } = ctx + const page = pdfDoc.addPage(PageSizes.A4) + const { width, height } = page.getSize() + const max = width - MARGIN_X * 2 + + drawHeader(page, report, ctx, headerAssets) + + const eyebrowY = height - EYEBROW_Y_OFFSET + const titleY = height - TITLE_Y_OFFSET + drawText(page, labels['pdf.eyebrow.synthesis'], { + x: MARGIN_X, + y: eyebrowY, + size: 9, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) + drawText(page, labels['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 + for (const { label, body, color } of conclusionSections(report, ctx)) { + drawText(page, 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) => { + drawText(page, line, { + x: MARGIN_X, + y: cursorY, + size: 11, + font: fonts.bodyRegular, + color: color ?? COLOR_INK, + }) + cursorY -= TEXT_LINE_HEIGHT + }) + cursorY -= SECTION_BLOCK_GAP + } +} diff --git a/packages/pdf/src/render/constants.ts b/packages/pdf/src/render/constants.ts new file mode 100644 index 00000000..c12effbd --- /dev/null +++ b/packages/pdf/src/render/constants.ts @@ -0,0 +1,18 @@ +import { rgb } from 'pdf-lib' + +/** + * Layout and colour constants shared across page renderers (header, footer, + * observation page, conclusion page). Only values identical across callers + * live here; a same-named constant with another value stays local. + */ + +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) diff --git a/packages/pdf/src/render/context.ts b/packages/pdf/src/render/context.ts new file mode 100644 index 00000000..a4d013a6 --- /dev/null +++ b/packages/pdf/src/render/context.ts @@ -0,0 +1,11 @@ +import type { PdfLabels } from '@faunosteo/domain' +import type { EmbeddedFonts } from './fonts' + +export type PdfLocale = 'fr' | 'en' + +/** What every page renderer needs besides the page: fonts, locale, labels. */ +export interface RenderContext { + fonts: EmbeddedFonts + locale: PdfLocale + labels: PdfLabels +} diff --git a/packages/pdf/src/render/dates.ts b/packages/pdf/src/render/dates.ts new file mode 100644 index 00000000..f5c5af36 --- /dev/null +++ b/packages/pdf/src/render/dates.ts @@ -0,0 +1,26 @@ +import type { PdfLocale } from './context' + +const LOCALE_TAG: Record = { + fr: 'fr-FR', + en: 'en-US', +} + +/** + * Long date in the locale for a `YYYY-MM-DD` value. Anything else is + * printed unchanged: a report is user data and never fails the export. + */ +export function formatDate(isoDate: string, locale: PdfLocale): string { + const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/) + if (!match) return isoDate + const [, y, mo, d] = match + const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d))) + const rolledOver = + date.getUTCMonth() !== Number(mo) - 1 || date.getUTCDate() !== Number(d) + if (Number.isNaN(date.getTime()) || rolledOver) return isoDate + return new Intl.DateTimeFormat(LOCALE_TAG[locale], { + day: 'numeric', + month: 'long', + year: 'numeric', + timeZone: 'UTC', + }).format(date) +} diff --git a/packages/pdf/src/render/fonts.ts b/packages/pdf/src/render/fonts.ts new file mode 100644 index 00000000..c36d7bd6 --- /dev/null +++ b/packages/pdf/src/render/fonts.ts @@ -0,0 +1,17 @@ +import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib' + +/** Helvetica body, Times heading: WinAnsi standard fonts (TTF planned). */ +export interface EmbeddedFonts { + bodyRegular: PDFFont + bodyBold: PDFFont + headingRegular: PDFFont +} + +export async function embedFonts(pdfDoc: PDFDocument): Promise { + const [bodyRegular, bodyBold, headingRegular] = await Promise.all([ + pdfDoc.embedFont(StandardFonts.Helvetica), + pdfDoc.embedFont(StandardFonts.HelveticaBold), + pdfDoc.embedFont(StandardFonts.TimesRoman), + ]) + return { bodyRegular, bodyBold, headingRegular } +} diff --git a/packages/pdf/src/render/footer.ts b/packages/pdf/src/render/footer.ts new file mode 100644 index 00000000..1ce317f5 --- /dev/null +++ b/packages/pdf/src/render/footer.ts @@ -0,0 +1,170 @@ +import { rgb, type PDFPage } from 'pdf-lib' +import type { BrandingImages, CreditAsset } from '../branding' +import { COLOR_MUTED, MARGIN_X } from './constants' +import type { RenderContext } from './context' +import { addLinkAnnotation } from './linkAnnotation' +import { drawText, measure } from './text' + +const FOOTER_BASE_Y = 20 +const FONT_SIZE = 8 +const LOGO_W = 80 +const LOGO_H = 30 +const ROW_Y = FOOTER_BASE_Y + 14 +const TEXT_BASE_Y = ROW_Y + 6 +const CREDIT_LOGO_H = 16 +const POWERED_LOGO_W = 70 +const COLOR_RULE = rgb(0.85, 0.83, 0.8) +const COLOR_CREDIT = rgb(0.28, 0.56, 0.42) + +function drawRule(page: PDFPage): void { + const { width } = page.getSize() + const separatorY = ROW_Y + LOGO_H + 6 + page.drawLine({ + start: { x: MARGIN_X, y: separatorY }, + end: { x: width - MARGIN_X, y: separatorY }, + thickness: 0.5, + color: COLOR_RULE, + }) +} + +function drawSiteLogo(page: PDFPage, assets: BrandingImages): void { + if (!assets.footer) return + const rect = { x: MARGIN_X, y: ROW_Y, width: LOGO_W, height: LOGO_H } + page.drawImage(assets.footer, rect) + addLinkAnnotation(page, { ...rect, url: assets.siteUrl }) +} + +function drawMutedLabel( + page: PDFPage, + text: string, + x: number, + ctx: RenderContext, +): void { + drawText(page, text, { + x, + y: TEXT_BASE_Y, + size: FONT_SIZE, + font: ctx.fonts.bodyRegular, + color: COLOR_MUTED, + }) +} + +/** The credit's fallback text in the accent colour, linked. */ +function drawCreditText( + page: PDFPage, + credit: CreditAsset, + x: number, + ctx: RenderContext, +): void { + const font = ctx.fonts.bodyRegular + drawText(page, credit.fallbackText, { + x, + y: TEXT_BASE_Y, + size: FONT_SIZE, + font, + color: COLOR_CREDIT, + }) + addLinkAnnotation(page, { + x, + y: TEXT_BASE_Y - 2, + width: measure(font, credit.fallbackText, FONT_SIZE), + height: FONT_SIZE + 4, + url: credit.url, + }) +} + +function drawCreditLogo( + page: PDFPage, + credit: CreditAsset & { image: NonNullable }, + x: number, + width: number, +): void { + const rect = { x, y: ROW_Y + 2, width, height: CREDIT_LOGO_H } + page.drawImage(credit.image, rect) + addLinkAnnotation(page, { ...rect, url: credit.url }) +} + +/** Centred block: label then the fixed-width logo or the fallback text. */ +function drawPoweredBy( + page: PDFPage, + credit: CreditAsset, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const font = ctx.fonts.bodyRegular + const label = `${ctx.labels['footer.powered_by']} ` + const labelW = measure(font, label, FONT_SIZE) + const creditW = credit.image + ? POWERED_LOGO_W + : measure(font, credit.fallbackText, FONT_SIZE) + const x = (width - labelW - creditW) / 2 + drawMutedLabel(page, label, x, ctx) + if (credit.image) { + drawCreditLogo( + page, + { ...credit, image: credit.image }, + x + labelW, + POWERED_LOGO_W, + ) + } else { + drawCreditText(page, credit, x + labelW, ctx) + } +} + +/** Right-aligned block: label then the aspect-sized logo or the handle. */ +function drawPartner( + page: PDFPage, + credit: CreditAsset, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const font = ctx.fonts.bodyRegular + const label = `${ctx.labels['footer.in_partnership']} ` + const labelW = measure(font, label, FONT_SIZE) + const creditW = credit.image + ? CREDIT_LOGO_H * (credit.image.width / credit.image.height) + : measure(font, credit.fallbackText, FONT_SIZE) + const x = width - MARGIN_X - labelW - creditW + drawMutedLabel(page, label, x, ctx) + if (credit.image) { + drawCreditLogo( + page, + { ...credit, image: credit.image }, + x + labelW, + creditW, + ) + } else { + drawCreditText(page, credit, x + labelW, ctx) + } +} + +function drawPageNumber( + page: PDFPage, + pageNumber: number, + totalPages: number, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const text = `${pageNumber} / ${totalPages}` + drawText(page, text, { + x: (width - measure(ctx.fonts.bodyRegular, text, FONT_SIZE)) / 2, + y: FOOTER_BASE_Y + 2, + size: FONT_SIZE, + font: ctx.fonts.bodyRegular, + color: COLOR_MUTED, + }) +} + +/** Rule, site logo, powered-by credit, partner credit, page number. */ +export function drawFooter( + page: PDFPage, + pagination: { pageNumber: number; totalPages: number }, + ctx: RenderContext, + assets: BrandingImages, +): void { + drawRule(page) + drawSiteLogo(page, assets) + if (assets.poweredBy) drawPoweredBy(page, assets.poweredBy, ctx) + if (assets.partner) drawPartner(page, assets.partner, ctx) + drawPageNumber(page, pagination.pageNumber, pagination.totalPages, ctx) +} diff --git a/packages/pdf/src/render/header.ts b/packages/pdf/src/render/header.ts new file mode 100644 index 00000000..58e1c867 --- /dev/null +++ b/packages/pdf/src/render/header.ts @@ -0,0 +1,112 @@ +import type { PDFImage, PDFPage } from 'pdf-lib' +import type { Report } from '@faunosteo/domain' +import { COLOR_INK, COLOR_MUTED, MARGIN_X } from './constants' +import type { RenderContext } from './context' +import { formatDate } from './dates' +import { addLinkAnnotation } from './linkAnnotation' +import { drawText, measure } from './text' + +const TOP_Y = 800 +const LOGO_WIDTH = 100 +const LOGO_HEIGHT = 38 + +export interface HeaderAssets { + logo: PDFImage | null + siteUrl: string +} + +function practitionerLines(report: Report, ctx: RenderContext): string[] { + const { practitioner } = report + return [ + practitioner.name, + practitioner.cabinet, + practitioner.contact, + practitioner.siret + ? `${ctx.labels['pdf.siret_prefix']}${practitioner.siret}` + : undefined, + ].filter((line): line is string => Boolean(line)) +} + +function animalLines(report: Report, ctx: RenderContext): string[] { + const animalLine = [ + report.animal.name, + report.animal.breed ? `(${report.animal.breed})` : '', + report.animal.age ? `· ${report.animal.age}` : '', + ] + .filter(Boolean) + .join(' ') + return [ + animalLine, + `${ctx.labels['pdf.owner_prefix']}${report.owner.name}`, + formatDate(report.date, ctx.locale), + ] +} + +function drawLeftColumn( + page: PDFPage, + lines: string[], + ctx: RenderContext, +): void { + lines.forEach((line, i) => { + drawText(page, line, { + x: MARGIN_X, + y: TOP_Y - i * 12, + size: i === 0 ? 11 : 9, + font: i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular, + color: i === 0 ? COLOR_INK : COLOR_MUTED, + }) + }) +} + +function drawRightColumn( + page: PDFPage, + lines: string[], + ctx: RenderContext, +): void { + const { width } = page.getSize() + lines.forEach((line, i) => { + const size = i === 0 ? 11 : 9 + const font = i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular + drawText(page, line, { + x: width - MARGIN_X - measure(font, line, size), + y: TOP_Y - i * 12, + size, + font, + color: i === 0 ? COLOR_INK : COLOR_MUTED, + }) + }) +} + +function drawLogo(page: PDFPage, assets: HeaderAssets): void { + if (!assets.logo) return + const { width } = page.getSize() + const rect = { + x: (width - LOGO_WIDTH) / 2, + y: TOP_Y - LOGO_HEIGHT + 10, + width: LOGO_WIDTH, + height: LOGO_HEIGHT, + } + page.drawImage(assets.logo, rect) + addLinkAnnotation(page, { ...rect, url: assets.siteUrl }) +} + +/** Practitioner block left, logo centred, animal block right, then a rule. */ +export function drawHeader( + page: PDFPage, + report: Report, + ctx: RenderContext, + assets: HeaderAssets, +): void { + const { width } = page.getSize() + const left = practitionerLines(report, ctx) + drawLeftColumn(page, left, ctx) + drawLogo(page, assets) + drawRightColumn(page, animalLines(report, ctx), ctx) + const separatorY = TOP_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, + }) +} diff --git a/packages/pdf/src/render/linkAnnotation.ts b/packages/pdf/src/render/linkAnnotation.ts new file mode 100644 index 00000000..d775d20e --- /dev/null +++ b/packages/pdf/src/render/linkAnnotation.ts @@ -0,0 +1,36 @@ +import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib' + +export interface LinkRect { + x: number + y: number + width: number + height: number + url: string +} + +/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */ +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) + } +} diff --git a/packages/pdf/src/render/observationPage.ts b/packages/pdf/src/render/observationPage.ts new file mode 100644 index 00000000..d2054a3a --- /dev/null +++ b/packages/pdf/src/render/observationPage.ts @@ -0,0 +1,634 @@ +import { + PageSizes, + rgb, + type PDFDocument, + type PDFImage, + type PDFPage, +} from 'pdf-lib' +import { + pickLabel, + type Finding, + type Observation, + type PdfLabels, + type Report, + type ReportZone, + type Severity, + type SheetIndex, + type SheetSnapshot, +} from '@faunosteo/domain' +import { renderHighlightedView } from '../svg/view' +import type { ExportWarning, Rasterizer } from '../types' +import { + COLOR_ACCENT, + COLOR_INK, + EYEBROW_Y_OFFSET, + MARGIN_X, + SECTION_LABEL_GAP, + TITLE_RULE_OFFSET, + TITLE_RULE_WIDTH, + TITLE_Y_OFFSET, +} from './constants' +import type { PdfLocale, RenderContext } from './context' +import type { EmbeddedFonts } from './fonts' +import { drawHeader, type HeaderAssets } from './header' +import { drawText, measure, wrapLines } from './text' + +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> = { + 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 +/** Items of a section joined by this print as a segmented line. */ +const ITEM_JOIN = ' · ' + +/** Width of the visible separator block including the empty space on each side. */ +function separatorWidth(fonts: EmbeddedFonts): number { + return ( + measure(fonts.bodyBold, 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 = measure(fonts.bodyRegular, 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 +} + +interface SegmentCursor { + x: number + y: number +} + +function drawSeparator( + page: PDFPage, + cursor: SegmentCursor, + fonts: EmbeddedFonts, +): void { + const baselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3 + drawText(page, SEPARATOR_GLYPH, { + x: cursor.x + SEPARATOR_SIDE_GAP, + y: cursor.y - baselineOffset, + size: SEPARATOR_SIZE, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) +} + +/** + * 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[], + start: SegmentCursor, + maxWidth: number, + fonts: EmbeddedFonts, +): number { + if (items.length === 0) return start.y - TEXT_LINE_HEIGHT + const sepW = separatorWidth(fonts) + const cursor = { ...start } + for (let i = 0; i < items.length; i += 1) { + const item = items[i]! + const itemW = measure(fonts.bodyRegular, item, SECTION_TEXT_SIZE) + if (cursor.x + itemW > start.x + maxWidth && cursor.x > start.x) { + cursor.x = start.x + cursor.y -= TEXT_LINE_HEIGHT + } + drawText(page, item, { + x: cursor.x, + y: cursor.y, + size: SECTION_TEXT_SIZE, + font: fonts.bodyRegular, + color: COLOR_INK, + }) + cursor.x += itemW + if (i === items.length - 1) continue + if (cursor.x + sepW > start.x + maxWidth) { + cursor.x = start.x + cursor.y -= TEXT_LINE_HEIGHT + } else { + drawSeparator(page, cursor, fonts) + cursor.x += sepW + } + } + return cursor.y - TEXT_LINE_HEIGHT +} + +/** Parameters needed to render one observation page. */ +export interface ObservationPageContext { + pdfDoc: PDFDocument + report: Report + observation: Observation + obsIndex: number + sheet: SheetIndex + snapshot: SheetSnapshot + ctx: RenderContext + headerAssets: HeaderAssets + rasterizer: Rasterizer + warnings: ExportWarning[] +} + +interface PageDrawContext { + page: PDFPage + fonts: EmbeddedFonts + width: number +} + +interface RenderedImage { + label: string + img: PDFImage + aspect: number +} + +interface ObservationSection { + label: string + value: string +} + +function drawSeverityPill( + draw: PageDrawContext, + severity: Severity, + labels: PdfLabels, + anchor: { numW: number; titleY: number }, +): void { + const { page, fonts } = draw + const sevText = labels[`severity.${severity}`].toUpperCase() + const sevSize = 9 + const padX = 8 + const padY = 4 + const pillW = measure(fonts.bodyBold, sevText, sevSize) + padX * 2 + const pillH = sevSize + padY * 2 + const pillX = MARGIN_X + anchor.numW + 14 + const pillY = anchor.titleY + 4 + page.drawRectangle({ + x: pillX, + y: pillY, + width: pillW, + height: pillH, + color: SEVERITY_BG[severity], + }) + drawText(page, sevText, { + x: pillX + padX, + y: pillY + padY, + size: sevSize, + font: fonts.bodyBold, + color: COLOR_WHITE, + }) +} + +function drawObservationTitleBlock( + draw: PageDrawContext, + labels: PdfLabels, + obsIndex: number, + severity: Severity | undefined, +): number { + const { page, fonts } = draw + const { height } = page.getSize() + const eyebrowY = height - EYEBROW_Y_OFFSET + const titleY = height - TITLE_Y_OFFSET + const obsLabel = String(obsIndex + 1).padStart(2, '0') + drawText(page, labels['pdf.eyebrow.observation'], { + x: MARGIN_X, + y: eyebrowY, + size: 9, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) + drawText(page, obsLabel, { + x: MARGIN_X, + y: titleY, + size: 22, + font: fonts.headingRegular, + color: COLOR_INK, + }) + if (severity) { + const numW = measure(fonts.headingRegular, obsLabel, 22) + drawSeverityPill(draw, severity, labels, { numW, titleY }) + } + 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 +} + +/** Unique views the observation touches and the snapshot holds, main first. */ +export function observationViewIds( + sheet: SheetIndex, + observation: Observation, +): string[] { + 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), + ) +} + +function viewLabel( + sheet: SheetIndex, + viewId: string, + ctx: RenderContext, +): string { + const view = sheet.view(viewId)! + if (view.kind === 'main') return ctx.labels['pdf.view.general'] + const name = pickLabel(view.name, ctx.locale).toUpperCase() + return `${ctx.labels['pdf.view.detail_prefix']}${name}` +} + +interface RasterisedView { + viewId: string + png: Uint8Array | null +} + +/** One view rasterised; a failure yields null and a warning, never a throw. */ +async function rasteriseView( + page: ObservationPageContext, + viewId: string, +): Promise { + try { + const { svg, size } = renderHighlightedView( + page.snapshot, + viewId, + page.observation, + ) + return { viewId, png: await page.rasterizer(svg, size) } + } catch { + page.warnings.push({ + kind: 'view_raster_failed', + observationId: page.observation.id, + viewId, + }) + return { viewId, png: null } + } +} + +/** Rasterisation in parallel, embedding in view order so bytes stay stable. */ +async function buildObservationImages( + page: ObservationPageContext, +): Promise { + const viewIds = observationViewIds(page.sheet, page.observation) + const rasters = await Promise.all( + viewIds.map((viewId) => rasteriseView(page, viewId)), + ) + const rendered: RenderedImage[] = [] + for (const { viewId, png } of rasters) { + if (!png) continue + try { + const img = await page.pdfDoc.embedPng(png) + rendered.push({ + label: viewLabel(page.sheet, viewId, page.ctx), + img, + aspect: img.width > 0 ? img.height / img.width : 0.6, + }) + } catch { + page.warnings.push({ + kind: 'view_raster_failed', + observationId: page.observation.id, + viewId, + }) + } + } + return rendered +} + +/** Zone name: snapshot annotation, else the report's label snapshot, else the id. */ +function zoneText(z: ReportZone, sheet: SheetIndex, locale: PdfLocale): 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 sideLabel(side: 'left' | 'right', labels: PdfLabels): string { + return labels[side === 'left' ? 'lateral.left' : 'lateral.right'] +} + +function describeObservationZones( + zones: ReportZone[], + sheet: SheetIndex, + ctx: RenderContext, +): string { + return zones + .map((z) => { + const v = z.vertebrae?.length + ? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})` + : '' + const side = z.side ? ` (${sideLabel(z.side, ctx.labels)})` : '' + return `${zoneText(z, sheet, ctx.locale)}${v}${side}` + }) + .join(ITEM_JOIN) +} + +/** Finding group heading: snapshot finding-zone name, else the id as is. */ +function findingZoneName( + zoneId: string, + sheet: SheetIndex, + locale: PdfLocale, +): string { + const zone = sheet.findingZone(zoneId) + return zone ? pickLabel(zone.name, locale) : zoneId +} + +function findingText(f: Finding, locale: PdfLocale): string { + const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot + return f.requiresVetReferral ? `(!) ${label}` : label +} + +/** Groups findings by zone+side, one section per group; snapshots give the text. */ +function buildFindingsSections( + findings: Finding[], + sheet: SheetIndex, + ctx: RenderContext, +): ObservationSection[] { + const byZoneSide = new Map() + 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, ctx.locale) + if (side) zoneName = `${zoneName} (${sideLabel(side, ctx.labels)})` + sections.push({ + label: `${ctx.labels['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`, + value: group.map((f) => findingText(f, ctx.locale)).join(ITEM_JOIN), + }) + } + return sections +} + +function buildObservationSections( + observation: Observation, + sheet: SheetIndex, + ctx: RenderContext, +): ObservationSection[] { + const { labels } = ctx + const zonesText = describeObservationZones(observation.zones, sheet, ctx) + const sections: ObservationSection[] = [ + { + label: labels['pdf.section.zones'], + value: zonesText || labels['pdf.empty'], + }, + ...buildFindingsSections(observation.findings, sheet, ctx), + ] + if (observation.freeTextFindings.length) { + sections.push({ + label: labels['pdf.section.free_findings'], + value: observation.freeTextFindings.join(ITEM_JOIN), + }) + } + if (observation.severity) { + sections.push({ + label: labels['pdf.section.severity'], + value: labels[`severity.${observation.severity}`], + }) + } + if (observation.comment.trim()) { + sections.push({ + label: labels['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(ITEM_JOIN) + ? countSegmentedLines(value.split(ITEM_JOIN), 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 +} + +interface ImageGrid { + cols: number + rows: number + cellW: number + offsetX: number + rowBudget: number +} + +function imageGridOf( + rendered: RenderedImage[], + width: number, + availH: number, +): ImageGrid { + 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 + return { + cols, + rows, + cellW, + offsetX: isSingle ? (fullCellW - cellW) / 2 : 0, + rowBudget: Math.max( + IMAGE_MIN_CELL_H, + (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, + ), + } +} + +/** One row of the grid: labels above, then the images; returns the row height. */ +function drawImageRow( + draw: PageDrawContext, + rowItems: RenderedImage[], + grid: ImageGrid, + topY: number, +): number { + const { page, fonts } = draw + const cellHs = rowItems.map((it) => + Math.min(grid.cellW * it.aspect, grid.rowBudget), + ) + const cellX = (c: number) => + MARGIN_X + grid.offsetX + c * (grid.cellW + IMAGE_COL_GAP) + rowItems.forEach((it, c) => { + drawText(page, it.label, { + x: cellX(c), + y: topY, + size: 8, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) + }) + const imagesY = topY - IMAGE_LABEL_GAP + rowItems.forEach((it, c) => { + page.drawImage(it.img, { + x: cellX(c), + y: imagesY - cellHs[c]!, + width: grid.cellW, + height: cellHs[c]!, + }) + }) + return Math.max(0, ...cellHs) +} + +/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */ +function drawObservationImageGrid( + draw: PageDrawContext, + rendered: RenderedImage[], + startY: number, + reservedBottom: number, +): number { + if (rendered.length === 0) return startY + const availH = Math.max(IMAGE_MIN_CELL_H, startY - reservedBottom) + const grid = imageGridOf(rendered, draw.width, availH) + let cursorY = startY + for (let r = 0; r < grid.rows; r += 1) { + const rowItems = rendered.slice(r * grid.cols, r * grid.cols + grid.cols) + const rowH = drawImageRow(draw, rowItems, grid, cursorY) + cursorY -= IMAGE_LABEL_GAP + rowH + if (r < grid.rows - 1) cursorY -= IMAGE_ROW_GAP + } + return cursorY - IMAGE_BOTTOM_GAP +} + +function drawSectionValue( + draw: PageDrawContext, + value: string, + startY: number, + maxTextW: number, +): number { + const { page, fonts } = draw + if (value.includes(ITEM_JOIN)) { + return drawSegmentedText( + page, + value.split(ITEM_JOIN), + { x: MARGIN_X, y: startY }, + maxTextW, + fonts, + ) + } + let cursorY = startY + for (const line of wrapLines( + value, + fonts.bodyRegular, + SECTION_TEXT_SIZE, + maxTextW, + )) { + drawText(page, line, { + x: MARGIN_X, + y: cursorY, + size: SECTION_TEXT_SIZE, + font: fonts.bodyRegular, + color: COLOR_INK, + }) + cursorY -= TEXT_LINE_HEIGHT + } + return cursorY +} + +function drawObservationSections( + draw: PageDrawContext, + sections: ObservationSection[], + startY: number, + maxTextW: number, +): number { + let cursorY = startY + for (const { label, value } of sections) { + drawText(draw.page, label, { + x: MARGIN_X, + y: cursorY, + size: 8, + font: draw.fonts.bodyBold, + color: COLOR_ACCENT, + }) + cursorY -= SECTION_LABEL_GAP + 9 + cursorY = drawSectionValue(draw, value, cursorY, maxTextW) + cursorY -= SECTION_BLOCK_GAP + } + return cursorY +} + +export async function addObservationPage( + input: ObservationPageContext, +): Promise { + const { pdfDoc, report, observation, obsIndex, sheet, ctx, headerAssets } = + input + const page = pdfDoc.addPage(PageSizes.A4) + const { width } = page.getSize() + drawHeader(page, report, ctx, headerAssets) + + const draw: PageDrawContext = { page, fonts: ctx.fonts, width } + const titleY = drawObservationTitleBlock( + draw, + ctx.labels, + obsIndex, + observation.severity, + ) + const rendered = await buildObservationImages(input) + const maxTextW = width - MARGIN_X * 2 + const sections = buildObservationSections(observation, sheet, ctx) + const reservedBottom = + MARGIN_BOTTOM + + estimateSectionsHeight(sections, ctx.fonts, maxTextW) + + IMAGE_BOTTOM_GAP + let cursorY = drawObservationImageGrid( + draw, + rendered, + titleY - IMAGE_TOP_GAP, + reservedBottom, + ) + cursorY -= TEXT_TOP_GAP + drawObservationSections(draw, sections, cursorY, maxTextW) +} diff --git a/packages/pdf/src/render/text.ts b/packages/pdf/src/render/text.ts new file mode 100644 index 00000000..35801f41 --- /dev/null +++ b/packages/pdf/src/render/text.ts @@ -0,0 +1,46 @@ +import type { PDFFont, PDFPage, PDFPageDrawTextOptions } from 'pdf-lib' +import { safeText } from '../text' + +/** + * Every string reaches pdf-lib through these three helpers, so a glyph the + * standard fonts cannot encode never throws at draw or measure time. + */ + +export function measure(font: PDFFont, text: string, size: number): number { + return font.widthOfTextAtSize(safeText(text), size) +} + +export function drawText( + page: PDFPage, + text: string, + options: PDFPageDrawTextOptions, +): void { + page.drawText(safeText(text), options) +} + +/** + * Greedy word-wrap: splits `text` into lines whose rendered width at + * `size` points stays within `max` for the given font. Whitespace of any + * kind separates words first, then each word is made safe. + */ +export function wrapLines( + text: string, + font: PDFFont, + size: number, + max: number, +): string[] { + const words = text.split(/\s+/).map(safeText) + const lines: string[] = [] + let line = '' + for (const w of words) { + const test = line ? `${line} ${w}` : w + if (measure(font, test, size) > max && line) { + lines.push(line) + line = w + } else { + line = test + } + } + if (line) lines.push(line) + return lines +} diff --git a/packages/pdf/src/svg/parse.ts b/packages/pdf/src/svg/parse.ts new file mode 100644 index 00000000..06d08245 --- /dev/null +++ b/packages/pdf/src/svg/parse.ts @@ -0,0 +1,37 @@ +import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom' +import { SvgRejectedError } from '../errors' + +/** + * SVG text in, DOM root out, with xmldom (one code path in Node and in the + * browser). Entity declarations are refused before parsing; a parse error + * is reported as a typed rejection and its message, which may echo the + * input, is never logged. + */ + +const ENTITY_MARKUP = /` counters refuse an oversized tree. + * The caller learns what was removed (names only, never values). + */ + +export const SANITIZER_CAPS = { + elements: 20_000, + depth: 64, + uses: 256, + stdDeviation: 100, +} as const + +const ALLOWED_ELEMENTS = new Set([ + 'svg', + 'g', + 'path', + 'circle', + 'ellipse', + 'rect', + 'line', + 'polyline', + 'polygon', + 'defs', + 'linearGradient', + 'radialGradient', + 'stop', + 'filter', + 'feGaussianBlur', + 'feMerge', + 'feMergeNode', + 'feOffset', + 'feFlood', + 'feComposite', + 'feBlend', + 'feColorMatrix', + 'clipPath', + 'mask', + 'title', + 'desc', + 'switch', + 'use', +]) + +const ALLOWED_ATTRIBUTES = new Set([ + 'id', + 'class', + 'd', + 'cx', + 'cy', + 'r', + 'rx', + 'ry', + 'x', + 'y', + 'x1', + 'y1', + 'x2', + 'y2', + 'dx', + 'dy', + 'width', + 'height', + 'points', + 'transform', + 'viewBox', + 'version', + 'preserveAspectRatio', + 'fill', + 'fill-opacity', + 'fill-rule', + 'stroke', + 'stroke-width', + 'stroke-linecap', + 'stroke-linejoin', + 'stroke-opacity', + 'stroke-dasharray', + 'stroke-dashoffset', + 'stroke-miterlimit', + 'opacity', + 'filter', + 'clip-path', + 'clip-rule', + 'mask', + 'display', + 'visibility', + 'color', + 'gradientUnits', + 'gradientTransform', + 'spreadMethod', + 'offset', + 'stop-color', + 'stop-opacity', + 'stdDeviation', + 'in', + 'in2', + 'result', + 'mode', + 'operator', + 'k1', + 'k2', + 'k3', + 'k4', + 'flood-color', + 'flood-opacity', + 'type', + 'values', + 'color-interpolation-filters', + 'filterUnits', + 'primitiveUnits', + 'systemLanguage', + 'font-family', + 'font-size', + 'font-weight', + 'xmlns', + 'xmlns:xlink', + 'xlink:href', + 'href', + 'style', +]) + +const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/ +const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi +const STYLE_FORBIDDEN = /expression\(|@import|javascript:|behavior:/i + +export interface SanitizeOutcome { + /** Removed element names and `element@attribute` pairs, in document order. */ + removed: string[] +} + +const ELEMENT_NODE = 1 + +function isElement(node: Node): node is Element { + return node.nodeType === ELEMENT_NODE +} + +function elementChildren(node: Node): Element[] { + return Array.from(node.childNodes).filter(isElement) +} + +/** Every `url(` in the value must point inside the document (`url(#…)`). */ +function urlsAreLocal(value: string): boolean { + for (const match of value.matchAll(URL_FUNCTION)) { + if (match[1] !== '#') return false + } + return true +} + +function hrefIsLocal(value: string): boolean { + return LOCAL_REFERENCE.test(value.trim()) +} + +/** Whether an allowed attribute keeps its value, by name-specific rule. */ +function attributeAcceptable(name: string, value: string): boolean { + if (!urlsAreLocal(value)) return false + if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value) + if (name === 'style') return !STYLE_FORBIDDEN.test(value) + return true +} + +/** Clamps every number of a `stdDeviation` list; rewrites only when needed. */ +function clampStdDeviation(element: Element): void { + const raw = element.getAttribute('stdDeviation') + if (raw === null) return + const numbers = raw + .trim() + .split(/[\s,]+/) + .map(Number) + if (numbers.some(Number.isNaN)) { + element.removeAttribute('stdDeviation') + return + } + if (numbers.every((n) => n <= SANITIZER_CAPS.stdDeviation)) return + const clamped = numbers.map((n) => Math.min(n, SANITIZER_CAPS.stdDeviation)) + element.setAttribute('stdDeviation', clamped.join(' ')) +} + +function sanitizeAttributes(element: Element, removed: string[]): void { + const attributes: Attr[] = Array.from(element.attributes) + for (const attribute of attributes) { + const { name, value } = attribute + const keep = + ALLOWED_ATTRIBUTES.has(name) && attributeAcceptable(name, value) + if (keep) continue + element.removeAttribute(name) + removed.push(`${element.tagName}@${name}`) + } + clampStdDeviation(element) +} + +interface Walk { + removed: string[] + elements: number + uses: number +} + +function visit(element: Element, depth: number, walk: Walk): void { + walk.elements += 1 + if (walk.elements > SANITIZER_CAPS.elements) { + throw new SvgRejectedError('too_many_elements') + } + if (depth > SANITIZER_CAPS.depth) throw new SvgRejectedError('too_deep') + if (element.tagName === 'use') { + walk.uses += 1 + if (walk.uses > SANITIZER_CAPS.uses) { + throw new SvgRejectedError('too_many_uses') + } + } + sanitizeAttributes(element, walk.removed) + for (const child of elementChildren(element)) { + if (ALLOWED_ELEMENTS.has(child.tagName)) { + visit(child, depth + 1, walk) + } else { + element.removeChild(child) + walk.removed.push(child.tagName) + } + } +} + +/** + * Sanitises the tree under `root` in place. Throws SvgRejectedError when a + * counter cap is exceeded; the tree is then unusable and the caller drops + * it. Returns the names of what was removed (empty on the real assets). + */ +export function sanitizeSvgRoot(root: Element): SanitizeOutcome { + if (root.tagName !== 'svg') throw new SvgRejectedError('not_svg') + const walk: Walk = { removed: [], elements: 0, uses: 0 } + visit(root, 1, walk) + return { removed: walk.removed } +} diff --git a/packages/pdf/src/svg/view.ts b/packages/pdf/src/svg/view.ts new file mode 100644 index 00000000..b7556dfa --- /dev/null +++ b/packages/pdf/src/svg/view.ts @@ -0,0 +1,123 @@ +import type { Element } from '@xmldom/xmldom' +import { composeViewSvg } from '@faunosteo/anatomy/render' +import type { Observation, SheetSnapshot, SheetView } from '@faunosteo/domain' +import { parseSvg, serializeSvg } from './parse' +import { sanitizeSvgRoot } from './sanitize' + +/** + * The picture of one view of an observation: the snapshot's drawing, + * sanitised, framed on the view and overlaid with the observation's zones + * highlighted (accent fill, halo on the main view). The raster size follows + * today's rule, width 1200 px and the view box aspect, with the aspect + * clamped so an untrusted `viewBox` cannot request a huge canvas. + */ + +export const RASTER_WIDTH_PX = 1200 +const ASPECT_MIN = 0.2 +const ASPECT_MAX = 2.0 +const ASPECT_FALLBACK = 0.6 + +export interface RasterSize { + widthPx: number + heightPx: number +} + +export interface RenderedSvg { + svg: string + size: RasterSize +} + +/** Height over width of a `viewBox` value, or the fallback when unusable. */ +function aspectOf(viewBox: string | null): number { + const parts = (viewBox ?? '') + .trim() + .split(/[\s,]+/) + .map(Number) + const [, , width, height] = parts + if (parts.length !== 4 || !(width! > 0) || !(height! > 0)) { + return ASPECT_FALLBACK + } + return height! / width! +} + +export function rasterSizeOf(viewBox: string | null): RasterSize { + const aspect = Math.min(ASPECT_MAX, Math.max(ASPECT_MIN, aspectOf(viewBox))) + return { + widthPx: RASTER_WIDTH_PX, + heightPx: Math.max(1, Math.round(RASTER_WIDTH_PX * aspect)), + } +} + +/** The asset a view draws: its own, else the first up its parent chain. */ +export function assetIdOfView( + view: SheetView, + views: ReadonlyMap, +): string | null { + const visited = new Set() + let current: SheetView | undefined = view + while (current && !visited.has(current.id)) { + if (current.svg_asset_id !== null) return current.svg_asset_id + visited.add(current.id) + current = + current.kind === 'detail' ? views.get(current.parent_view_id) : undefined + } + return null +} + +function assetText(sheet: SheetSnapshot, view: SheetView): string { + const views = new Map(sheet.document.views.map((v) => [v.id, v])) + const assetId = assetIdOfView(view, views) + const asset = sheet.assets.find((a) => a.svgAssetId === assetId) + if (!asset) throw new Error(`view "${view.id}" reaches no asset`) + return asset.svg +} + +/** Parse, sanitise: the only way an asset text becomes a tree here. */ +export function cleanSvgRoot(text: string): Element { + const root = parseSvg(text) + sanitizeSvgRoot(root) + return root +} + +/** The view's drawing with the observation's zones of that view highlighted. */ +export function renderHighlightedView( + sheet: SheetSnapshot, + viewId: string, + observation: Observation, +): RenderedSvg { + const view = sheet.document.views.find((v) => v.id === viewId) + if (!view) throw new Error(`unknown view "${viewId}"`) + const annotationIds = new Set( + observation.zones + .filter((zone) => zone.viewId === viewId) + .map((zone) => zone.annotationId), + ) + const root = cleanSvgRoot(assetText(sheet, view)) + composeViewSvg({ + root, + document: sheet.document, + viewId, + highlight: { annotationIds, halo: view.kind === 'main' }, + }) + return { + svg: serializeSvg(root), + size: rasterSizeOf(root.getAttribute('viewBox')), + } +} + +export function composeHighlightedViewSvg( + sheet: SheetSnapshot, + viewId: string, + observation: Observation, +): string { + return renderHighlightedView(sheet, viewId, observation).svg +} + +/** A branding SVG made safe, with the raster size its own viewBox gives. */ +export function renderBrandingSvg(text: string): RenderedSvg { + const root = cleanSvgRoot(text) + return { + svg: serializeSvg(root), + size: rasterSizeOf(root.getAttribute('viewBox')), + } +} diff --git a/packages/pdf/src/text.ts b/packages/pdf/src/text.ts new file mode 100644 index 00000000..f34e0fae --- /dev/null +++ b/packages/pdf/src/text.ts @@ -0,0 +1,21 @@ +import { Encodings } from '@pdf-lib/standard-fonts' + +/** + * The single text ingress of the engine (STEP6 §15). The standard fonts are + * WinAnsi-encoded: a glyph outside that table makes pdf-lib throw at draw + * or measure time. Control, format and line/paragraph separator characters + * are dropped; every other unencodable code point prints as `?`. En and em + * dashes, bullets, accents and the euro sign are WinAnsi and survive. + */ + +const DROPPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu + +function encodable(char: string): string { + const codePoint = char.codePointAt(0) + if (codePoint === undefined) return '' + return Encodings.WinAnsi.canEncodeUnicodeCodePoint(codePoint) ? char : '?' +} + +export function safeText(text: string): string { + return Array.from(text.replace(DROPPED, ''), encodable).join('') +} diff --git a/packages/pdf/src/types.ts b/packages/pdf/src/types.ts new file mode 100644 index 00000000..f4d05b7d --- /dev/null +++ b/packages/pdf/src/types.ts @@ -0,0 +1,43 @@ +import type { + Branding, + PdfLabelSet, + Report, + ReportArchiveEnvelope, + SheetSnapshot, +} from '@faunosteo/domain' +import type { PdfLocale } from './render/context' + +export type { PdfLocale } + +/** + * Rasterisation is an adapter (STEP6 §3.3): the engine computes the size + * and the caller renders (browser Image/canvas, resvg in Node). + */ +export type Rasterizer = ( + svg: string, + size: { widthPx: number; heightPx: number }, +) => Promise + +export interface ExportInput { + report: Report + sheet: SheetSnapshot + branding: Branding + labels: PdfLabelSet + locale: PdfLocale + rasterizer: Rasterizer + /** Drives every date in the file: metadata, attachment, envelope. */ + exportedAt: Date +} + +export type ExportWarning = + | { kind: 'view_raster_failed'; observationId: string; viewId: string } + | { + kind: 'logo_failed' + slot: 'headerLogo' | 'footerLogo' | 'poweredBy' | 'partner' + } + +export interface ExportResult { + pdf: Uint8Array + envelope: ReportArchiveEnvelope + warnings: ExportWarning[] +} diff --git a/packages/pdf/tests/goldens.test.ts b/packages/pdf/tests/goldens.test.ts new file mode 100644 index 00000000..89f65dcc --- /dev/null +++ b/packages/pdf/tests/goldens.test.ts @@ -0,0 +1,137 @@ +/** + * T3 (STEP6 §7, §17): the engine reproduces every Phase 0 golden, per + * report × locale × logo mode. A mismatch is a visible change: the golden + * is never edited here. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { defaultPdfLabels, exportReportArchive } from '../src' +import type { PdfLocale } from '../src' +import { + brandingOf, + checkGolden, + FIXED_EXPORTED_AT, + ONE_PX_PNG, + rasterizerOf, + readGolden, + readLinks, + recordDrawing, + snapshotViews, + TWO_BY_ONE_PNG, + type ImageEntry, + type LinkEntry, + type LogoMode, + type TextEntry, + type ViewSnapshot, +} from './helpers/goldens' +import { + loadGoldenReports, + REPORT_NAMES, + type GoldenReports, + type ReportName, +} from './helpers/reports' + +const MODES: readonly LogoMode[] = ['nologos', 'logos'] + +let golden: GoldenReports + +beforeAll(() => { + golden = loadGoldenReports() +}) +afterAll(() => vi.restoreAllMocks()) + +interface Exported { + bytes: Uint8Array + texts: TextEntry[] + images: ImageEntry[] + links: LinkEntry[] +} + +async function exportWith( + name: ReportName, + mode: LogoMode, + locale: PdfLocale, +): Promise { + const recording = recordDrawing() + try { + const { pdf, warnings } = await exportReportArchive({ + report: golden.reports[name], + sheet: golden.snapshots[name], + branding: brandingOf(mode), + labels: defaultPdfLabels, + locale, + rasterizer: rasterizerOf(mode), + exportedAt: FIXED_EXPORTED_AT, + }) + expect(warnings).toEqual([]) + const { texts, images } = recording + return { bytes: pdf, texts, images, links: await readLinks(pdf) } + } finally { + recording.stop() + } +} + +const pagesOf = (entries: readonly { page: number }[]) => + entries.map((e) => e.page) + +describe('golden inputs', () => { + it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => { + const doc = await PDFDocument.create() + const two = await doc.embedPng(TWO_BY_ONE_PNG) + expect([two.width, two.height]).toEqual([2, 1]) + const one = await doc.embedPng(ONE_PX_PNG) + expect([one.width, one.height]).toEqual([1, 1]) + }) + + it('the v2unresolved report carries the unresolved findings of the freeze', () => { + expect(golden.unresolvedOfV2Unresolved).toBeGreaterThan(0) + const findings = golden.reports.v2unresolved.observations.flatMap( + (o) => o.findings, + ) + expect(findings.filter((f) => f.unresolved)).toHaveLength( + golden.unresolvedOfV2Unresolved, + ) + }) +}) + +describe.each(REPORT_NAMES)('goldens of %s', (name) => { + describe.each(MODES)('%s', (mode) => { + it('text, images and links per locale; same pagination across locales', async () => { + const fr = await exportWith(name, mode, 'fr') + const en = await exportWith(name, mode, 'en') + for (const [locale, out] of [ + ['fr', fr], + ['en', en], + ] as const) { + checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts) + checkGolden(`images.${name}.${locale}.${mode}.json`, out.images) + checkGolden(`links.${name}.${locale}.${mode}.json`, out.links) + } + expect(pagesOf(en.images)).toEqual(pagesOf(fr.images)) + expect(pagesOf(en.links)).toEqual(pagesOf(fr.links)) + }, 30_000) + }) + + // Hidden markers are absent in the engine (the browser hid them with + // display="none") and the layer 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 actual = snapshotViews(golden.snapshots[name], golden.reports[name]) + const expected = readGolden(`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) + }) +}) diff --git a/packages/pdf/tests/helpers/draft.ts b/packages/pdf/tests/helpers/draft.ts new file mode 100644 index 00000000..276285b8 --- /dev/null +++ b/packages/pdf/tests/helpers/draft.ts @@ -0,0 +1,90 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { join, resolve } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportMigrationMapSchema, + type ReportMigrationMap, + type SnapshotSource, +} from '@faunosteo/domain' + +/** + * Paths and loaders shared by the engine tests. The committed equine draft + * is read from the seed as the application bundles it; the Phase 0 goldens + * and fixtures are read from the app's test folder, never copied. + */ + +const HERE = resolve(fileURLToPath(import.meta.url), '..') +export const REPO_ROOT = resolve(HERE, '../../../..') +export const DRAFT_DIR = resolve( + REPO_ROOT, + 'supabase/seed/anatomical-sheets/equine/draft', +) +export const LEGACY_BASELINE = resolve( + REPO_ROOT, + 'supabase/seed/anatomical-sheets/equine/legacy-import/document.json', +) +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') + +export function readJson(path: string): T { + return JSON.parse(readFileSync(path, 'utf8')) as T +} + +export function readFixtureJson(name: string): T { + return readJson(resolve(FIXTURES_DIR, name)) +} + +export function readFixtureBytes(name: string): Uint8Array { + return new Uint8Array(readFileSync(resolve(FIXTURES_DIR, name))) +} + +interface SeedRef { + sheet_id: string + version_id: string | null + document_sha256: string + schema_version: number + species_id: string +} + +interface SeedAsset { + file: string + sha256: string + svg_asset_id: string +} + +export interface DraftSheet extends SnapshotSource { + assetHashes: Readonly> + migrationMap: ReportMigrationMap +} + +export function loadDraftSheet(): DraftSheet { + const json = (name: string) => readJson(join(DRAFT_DIR, name)) + const ref = json('sheet-ref.json') + const assets: Record = {} + const assetHashes: Record = {} + for (const asset of json('assets.json')) { + assets[asset.svg_asset_id] = readFileSync( + join(DRAFT_DIR, 'assets', asset.file), + 'utf8', + ) + assetHashes[asset.svg_asset_id] = asset.sha256 + } + return { + status: 'draft', + ref: { + sheetId: ref.sheet_id, + versionId: ref.version_id, + documentSha256: ref.document_sha256, + }, + speciesId: ref.species_id, + schemaVersion: ref.schema_version, + document: AnatomicalSheetDocumentSchema.parse(json('document.json')), + assets, + assetHashes, + migrationMap: ReportMigrationMapSchema.parse( + json('report-migration-map.json'), + ), + } +} diff --git a/packages/pdf/tests/helpers/goldens.ts b/packages/pdf/tests/helpers/goldens.ts new file mode 100644 index 00000000..d9e33f61 --- /dev/null +++ b/packages/pdf/tests/helpers/goldens.ts @@ -0,0 +1,359 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { DOMParser, type Element, type Node } from '@xmldom/xmldom' +import { expect, vi } from 'vitest' +import { + PDFArray, + PDFDict, + PDFDocument, + PDFHexString, + PDFName, + PDFNumber, + PDFPage, + PDFString, +} from 'pdf-lib' +import type { + Branding, + Observation, + Report, + SheetSnapshot, +} from '@faunosteo/domain' +import { composeHighlightedViewSvg, type Rasterizer } from '../../src' +import { GOLDEN_DIR, PUBLIC_DIR } from './draft' + +/** + * Step 6 Phase 0 goldens, replayed on the engine: the same recorder on + * pdf-lib, the same link reader, the same view facts (computed with xmldom + * instead of the browser DOM) and the same fixed PNG rasters. + */ + +export const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z') + +/** 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', + ), +) + +/** A rasterizer returning the same PNG whatever the SVG, like the Phase 0 mock. */ +export function fixedRasterizer(png: Uint8Array): Rasterizer { + return async () => png +} + +export type LogoMode = 'nologos' | 'logos' + +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', +} + +function publicPng(relative: string): { kind: 'png'; base64: string } { + const bytes = readFileSync(resolve(PUBLIC_DIR, relative)) + return { kind: 'png', base64: Buffer.from(bytes).toString('base64') } +} + +/** Every logo null, credits with their fallback texts (fetch 404 in Phase 0). */ +export function nologosBranding(): Branding { + return { + siteUrl: SITE_URL, + headerLogo: null, + footerLogo: null, + poweredBy: { logo: null, ...POWERED_BY }, + partner: { logo: null, ...PARTNER }, + } +} + +/** The four real `public/` files (Phase 0 fetch stub). */ +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, + }, + partner: { + logo: { + kind: 'svg', + svg: readFileSync(resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'), 'utf8'), + }, + ...PARTNER, + }, + } +} + +export function brandingOf(mode: LogoMode): Branding { + return mode === 'logos' ? logosBranding() : nologosBranding() +} + +export function rasterizerOf(mode: LogoMode): Rasterizer { + return fixedRasterizer(mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG) +} + +export interface TextEntry { + page: number + text: string + x: number | null + y: number | null + size: number | null + font: string | null +} + +export interface ImageEntry { + page: number + x: number | null + y: number | null + width: number | null + height: number | null +} + +export interface LinkEntry { + page: number + rect: number[] + uri: string +} + +export function round2(value: unknown): number | null { + return typeof value === 'number' ? Math.round(value * 100) / 100 : null +} + +/** Pages are appended in order and never moved: the index at draw time is final. */ +function pageIndex(page: PDFPage): number { + return page.doc.getPages().indexOf(page) +} + +export interface DrawRecording { + texts: TextEntry[] + images: ImageEntry[] + stop(): void +} + +/** Records every drawText / drawImage while letting pdf-lib draw for real. */ +export function recordDrawing(): DrawRecording { + const texts: TextEntry[] = [] + const images: ImageEntry[] = [] + const drawText = PDFPage.prototype.drawText + const drawImage = PDFPage.prototype.drawImage + const textSpy = vi + .spyOn(PDFPage.prototype, 'drawText') + .mockImplementation(function (this: PDFPage, text, options) { + texts.push({ + page: pageIndex(this), + text, + x: round2(options?.x), + y: round2(options?.y), + size: round2(options?.size), + font: options?.font?.name ?? null, + }) + return drawText.call(this, text, options) + }) + const imageSpy = vi + .spyOn(PDFPage.prototype, 'drawImage') + .mockImplementation(function (this: PDFPage, image, options) { + images.push({ + page: pageIndex(this), + x: round2(options?.x), + y: round2(options?.y), + width: round2(options?.width), + height: round2(options?.height), + }) + return drawImage.call(this, image, options) + }) + return { + texts, + images, + stop: () => { + textSpy.mockRestore() + imageSpy.mockRestore() + }, + } +} + +function linkOf(dict: PDFDict, page: number): LinkEntry | null { + if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null + const rect = dict + .lookup(PDFName.of('Rect'), PDFArray) + .asArray() + .map((n) => round2((n as PDFNumber).asNumber()) ?? 0) + const uri = dict.lookup(PDFName.of('A'), PDFDict).lookup(PDFName.of('URI')) + const text = + uri instanceof PDFString || uri instanceof PDFHexString + ? uri.decodeText() + : String(uri) + return { page, rect, uri: text } +} + +/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */ +export async function readLinks(bytes: Uint8Array): Promise { + const doc = await PDFDocument.load(bytes) + const out: LinkEntry[] = [] + doc.getPages().forEach((page, index) => { + const annots = page.node.Annots() + if (!annots) return + for (let i = 0; i < annots.size(); i += 1) { + const link = linkOf(annots.lookup(i, PDFDict), index) + if (link) out.push(link) + } + }) + return out +} + +// --------------------------------------------------------------------------- +// View facts (G2), computed with xmldom on the engine's SVG + +export const HIGHLIGHT_FILL = '#b85a3f' + +export interface HighlightedElement { + tag: string + cx: string | null + cy: string | null + r: string | null + points: string | null + d: string | null + fill: string | null + fillOpacity: string | null + filter: string | null +} + +export interface ViewSnapshot { + observationId: string + viewId: string + viewBox: string | null + halo: boolean + highlighted: HighlightedElement[] + nonHighlightedVisible: number + dataAttributes: number + titles: number +} + +function isElement(node: Node): node is Element { + return node.nodeType === 1 +} + +/** Every element under `root` (root included), document order. */ +export function allElements(root: Element): Element[] { + const out: Element[] = [] + const stack: Element[] = [root] + while (stack.length) { + const el = stack.pop()! + out.push(el) + const children = Array.from(el.childNodes).filter(isElement) + for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]!) + } + return out +} + +export function elementChildren(el: Element): Element[] { + return Array.from(el.childNodes).filter(isElement) +} + +function highlightedOf(el: Element): HighlightedElement { + const attr = (name: string) => el.getAttribute(name) + return { + tag: el.tagName, + cx: attr('cx'), + cy: attr('cy'), + r: attr('r'), + points: attr('points'), + d: attr('d'), + fill: attr('fill'), + fillOpacity: attr('fill-opacity'), + filter: attr('filter'), + } +} + +/** Children of the annotation layer (last `` of the root) still visible and not highlighted. */ +function countVisibleNonHighlighted(root: Element): number { + const layer = elementChildren(root) + .filter((c) => c.tagName === 'g') + .at(-1) + if (!layer) return 0 + return elementChildren(layer).filter( + (el) => + el.getAttribute('fill') !== HIGHLIGHT_FILL && + el.getAttribute('display') !== 'none', + ).length +} + +function countDataAttributes(root: Element): number { + return allElements(root).reduce( + (count, el) => + count + + Array.from(el.attributes).filter((a) => a.name.startsWith('data-')) + .length, + 0, + ) +} + +export function parseXml(svg: string): Element { + return new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement! +} + +export function snapshotView( + sheet: SheetSnapshot, + observation: Observation, + viewId: string, +): ViewSnapshot { + const root = parseXml(composeHighlightedViewSvg(sheet, viewId, observation)) + const elements = allElements(root) + return { + observationId: observation.id, + viewId, + viewBox: root.getAttribute('viewBox'), + halo: elements.some( + (el) => el.tagName === 'filter' && el.getAttribute('id') === 'osteo-halo', + ), + highlighted: elements + .filter((el) => el.getAttribute('fill') === HIGHLIGHT_FILL) + .map(highlightedOf), + nonHighlightedVisible: countVisibleNonHighlighted(root), + dataAttributes: countDataAttributes(root), + titles: elements.filter((el) => el.tagName === 'title').length, + } +} + +/** The views an observation draws, in the pipeline's order: main first, then first appearance. */ +export function viewIdsOf( + 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) => views.has(id)) + .sort((a, b) => Number(b === main) - Number(a === main)) +} + +export function snapshotViews( + sheet: SheetSnapshot, + report: Report, +): ViewSnapshot[] { + return report.observations.flatMap((observation) => + viewIdsOf(sheet, observation).map((viewId) => + snapshotView(sheet, observation, viewId), + ), + ) +} + +export function readGolden(name: string): T { + return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T +} + +/** Asserts deep equality with a Phase 0 golden (never regenerated here). */ +export function checkGolden(name: string, actual: unknown): void { + expect(actual, name).toEqual(readGolden(name)) +} diff --git a/packages/pdf/tests/helpers/legacy-leaves.ts b/packages/pdf/tests/helpers/legacy-leaves.ts new file mode 100644 index 00000000..508a4752 --- /dev/null +++ b/packages/pdf/tests/helpers/legacy-leaves.ts @@ -0,0 +1,84 @@ +import { + AnatomicalSheetDocumentSchema, + ReportV2Schema, + type AnatomicalSheetDocument, + type FindingCategory, + type FindingNode, + type ObservationV2, + type ReportV2, +} from '@faunosteo/domain' +import { LEGACY_BASELINE, readJson } from './draft' + +/** + * The legacy catalog as the application's archive knew it: every leaf of the + * generated baseline becomes a Report v2 finding, one observation per zone. + * Same recipe as the app and domain helpers (Phase 0 `v2unresolved`). + */ + +export interface LegacyLeaf { + zoneId: string + path: string[] + name: { fr: string; en: string } + vet: boolean +} + +export function loadLegacyBaseline(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse(readJson(LEGACY_BASELINE)) +} + +export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] { + const out: LegacyLeaf[] = [] + const walk = ( + zoneId: string, + nodes: readonly (FindingCategory | FindingNode)[], + prefix: string[], + ) => { + for (const node of nodes) { + const path = [...prefix, node.id] + if (node.children.length > 0) walk(zoneId, node.children, path) + else { + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral + out.push({ zoneId, path, name: node.name, vet }) + } + } + } + for (const zone of doc.finding_zones) walk(zone.id, zone.categories, []) + return out +} + +export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 { + const byZone = new Map() + for (const leaf of leaves) { + let obs = byZone.get(leaf.zoneId) + if (!obs) { + obs = { + id: `obs-${leaf.zoneId}`, + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + } + byZone.set(leaf.zoneId, obs) + } + obs.findings.push({ + zoneId: leaf.zoneId, + path: leaf.path, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en || leaf.name.fr, + ...(leaf.vet ? { requiresVetReferral: true } : {}), + }) + } + return ReportV2Schema.parse({ + version: 2, + id: 'all-leaves', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Synthetic' }, + animal: { speciesId: 'equine', name: 'Synthetic' }, + owner: { name: 'Synthetic' }, + observations: [...byZone.values()], + conclusion: '', + recommendations: '', + }) +} diff --git a/packages/pdf/tests/helpers/pdf.ts b/packages/pdf/tests/helpers/pdf.ts new file mode 100644 index 00000000..584a57c4 --- /dev/null +++ b/packages/pdf/tests/helpers/pdf.ts @@ -0,0 +1,46 @@ +import { AFRelationship, PDFDocument, PDFName, PDFRawStream } from 'pdf-lib' + +/** Crafted PDFs for the read tests, built with pdf-lib's own attach. */ +export async function pdfWithAttachment( + name: string, + payload: unknown, + extra: { keywords?: string[]; before?: [string, unknown] } = {}, +): Promise { + const doc = await PDFDocument.create() + doc.addPage() + if (extra.keywords) doc.setKeywords(extra.keywords) + if (extra.before) await attachJson(doc, extra.before[0], extra.before[1]) + await attachJson(doc, name, payload) + return doc.save() +} + +async function attachJson( + doc: PDFDocument, + name: string, + payload: unknown, +): Promise { + await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, { + mimeType: 'application/json', + afRelationship: AFRelationship.Data, + }) +} + +export async function pdfWithoutAttachment( + keywords?: string[], +): Promise { + const doc = await PDFDocument.create() + doc.addPage() + if (keywords) doc.setKeywords(keywords) + return doc.save() +} + +/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF. */ +export async function storedAttachmentSize(bytes: Uint8Array): Promise { + const doc = await PDFDocument.load(bytes) + for (const [, object] of doc.context.enumerateIndirectObjects()) { + if (!(object instanceof PDFRawStream)) continue + const type = object.dict.lookup(PDFName.of('Type')) + if (type === PDFName.of('EmbeddedFile')) return object.contents.length + } + throw new Error('no EmbeddedFile stream') +} diff --git a/packages/pdf/tests/helpers/reports.ts b/packages/pdf/tests/helpers/reports.ts new file mode 100644 index 00000000..1091b53d --- /dev/null +++ b/packages/pdf/tests/helpers/reports.ts @@ -0,0 +1,71 @@ +import { + buildSheetSnapshot, + readReportDocument, + ReportSchema, + type Report, + type SheetSnapshot, +} from '@faunosteo/domain' +import { loadDraftSheet, readFixtureJson, type DraftSheet } from './draft' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from './legacy-leaves' + +/** The three Phase 0 reports, built with the Phase 0 recipe. */ +export const REPORT_NAMES = ['v2full', 'demo', 'v2unresolved'] as const +export type ReportName = (typeof REPORT_NAMES)[number] + +export interface GoldenReports { + draft: DraftSheet + reports: Record + snapshots: Record + /** Unresolved findings of `v2unresolved` as the migration counted them. */ + unresolvedOfV2Unresolved: number +} + +/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */ +function buildV2Unresolved(draft: DraftSheet) { + const leaves = legacyLeaves(loadLegacyBaseline()) + const unresolvedFamilies = leaves.filter( + (l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb', + ) + const resolved = leaves.find((l) => l.zoneId === 'frontal')! + return readReportDocument( + leavesAsV2Report([...unresolvedFamilies, resolved]), + draft.migrationMap, + ) +} + +export function loadGoldenReports(): GoldenReports { + const draft = loadDraftSheet() + const unresolved = buildV2Unresolved(draft) + const reports: Record = { + v2full: readReportDocument( + readFixtureJson('report-v2.full.json'), + draft.migrationMap, + ).report, + demo: ReportSchema.parse(readFixtureJson('report-v3.demo.json')), + v2unresolved: unresolved.report, + } + const snapshots = Object.fromEntries( + REPORT_NAMES.map((name) => [ + name, + buildSheetSnapshot(draft, reports[name]), + ]), + ) as Record + return { + draft, + reports, + snapshots, + unresolvedOfV2Unresolved: unresolved.unresolvedFindings, + } +} + +/** The 612-leaf legacy report migrated through the draft map (T5). */ +export function allLeavesMigrated(draft: DraftSheet) { + return readReportDocument( + leavesAsV2Report(legacyLeaves(loadLegacyBaseline())), + draft.migrationMap, + ) +} diff --git a/packages/pdf/tests/helpers/resvg.ts b/packages/pdf/tests/helpers/resvg.ts new file mode 100644 index 00000000..6dcd2e92 --- /dev/null +++ b/packages/pdf/tests/helpers/resvg.ts @@ -0,0 +1,88 @@ +import { Resvg } from '@resvg/resvg-js' +import type { Rasterizer } from '../../src' + +/** + * A real Node rasterizer for T10. resvg 0.40 (resvg-js 2.6.2) panics + * (`geom.rs:27`, `Option::unwrap() on None`) when gradient-filled elements + * are culled by a cropped root `viewBox` such as the head view's + * `60 100 500 380` on the equine drawing, aborting the process. The + * adapter therefore renders the box covering the whole content at the + * same scale and crops the pixels to the requested view: identical output + * for a view that already covers its content (main view). + */ + +export interface Raster { + requested: { widthPx: number; heightPx: number } + png: Uint8Array +} + +interface Box { + x: number + y: number + width: number + height: number +} + +const FONT = { loadSystemFonts: false } + +function rootViewBox(svg: string): Box | null { + const tag = svg.match(/]*>/)?.[0] ?? '' + const raw = tag.match(/\sviewBox="([^"]+)"/)?.[1] + if (!raw) return null + const [x, y, width, height] = raw + .trim() + .split(/[\s,]+/) + .map(Number) + if (!(width! > 0) || !(height! > 0)) return null + return { x: x!, y: y!, width: width!, height: height! } +} + +function withViewBox(svg: string, box: Box): string { + const value = `${box.x} ${box.y} ${box.width} ${box.height}` + return svg.replace(/(]*?\sviewBox=")[^"]+(")/, `$1${value}$2`) +} + +function union(a: Box, b: Box): Box { + const x = Math.min(a.x, b.x) + const y = Math.min(a.y, b.y) + return { + x, + y, + width: Math.max(a.x + a.width, b.x + b.width) - x, + height: Math.max(a.y + a.height, b.y + b.height) - y, + } +} + +function contentBox(svg: string): Box | null { + const bbox = new Resvg(svg, { font: FONT }).getBBox() + if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null + return { x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height } +} + +export function resvgRasterizer(record: Raster[] = []): Rasterizer { + return async (svg, size) => { + const crop = rootViewBox(svg) + const content = crop ? contentBox(svg) : null + const full = crop && content ? union(crop, content) : crop + const scale = crop ? size.widthPx / crop.width : 1 + const left = Math.round(((crop?.x ?? 0) - (full?.x ?? 0)) * scale) + const top = Math.round(((crop?.y ?? 0) - (full?.y ?? 0)) * scale) + const resvg = new Resvg(full ? withViewBox(svg, full) : svg, { + fitTo: { + mode: 'width', + value: full ? Math.round(full.width * scale) : size.widthPx, + }, + background: 'white', + font: FONT, + crop: { + left, + top, + right: left + size.widthPx, + bottom: top + size.heightPx, + }, + }) + const png = new Uint8Array(resvg.render().asPng()) + record.push({ requested: size, png }) + return png + } +} diff --git a/packages/pdf/tests/raster.test.ts b/packages/pdf/tests/raster.test.ts new file mode 100644 index 00000000..01103405 --- /dev/null +++ b/packages/pdf/tests/raster.test.ts @@ -0,0 +1,122 @@ +/** + * T10 (STEP6 §7): a real rasterizer (resvg) renders the demo report's main + * and head views: 1200 px wide, height from the view box, highlight colour + * present, sane non-white ratio. A failing rasterizer degrades to a page + * without the image and one warning. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import * as UPNG from '@pdf-lib/upng' +import { PDFDocument } from 'pdf-lib' +import { buildSheetSnapshot } from '@faunosteo/domain' +import { + defaultPdfLabels, + exportReportArchive, + type ExportInput, + type Rasterizer, +} from '../src' +import { + FIXED_EXPORTED_AT, + nologosBranding, + recordDrawing, +} from './helpers/goldens' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' +import { resvgRasterizer, type Raster } from './helpers/resvg' + +const HIGHLIGHT = { r: 0xb8, g: 0x5a, b: 0x3f } +const TOLERANCE = 24 + +interface PixelFacts { + width: number + height: number + highlightPixels: number + nonWhiteRatio: number +} + +function pixelFacts(png: Uint8Array): PixelFacts { + const buffer = new ArrayBuffer(png.byteLength) + new Uint8Array(buffer).set(png) + const image = UPNG.decode(buffer) + const rgba = new Uint8Array(UPNG.toRGBA8(image)[0]!) + let highlightPixels = 0 + let nonWhite = 0 + for (let i = 0; i < rgba.length; i += 4) { + const [r, g, b] = [rgba[i]!, rgba[i + 1]!, rgba[i + 2]!] + if (r < 250 || g < 250 || b < 250) nonWhite += 1 + if ( + Math.abs(r - HIGHLIGHT.r) <= TOLERANCE && + Math.abs(g - HIGHLIGHT.g) <= TOLERANCE && + Math.abs(b - HIGHLIGHT.b) <= TOLERANCE + ) { + highlightPixels += 1 + } + } + const total = rgba.length / 4 + return { + width: image.width, + height: image.height, + highlightPixels, + nonWhiteRatio: nonWhite / total, + } +} + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +function inputFor( + observations: GoldenReports['reports']['demo']['observations'], + rasterizer: Rasterizer, +): ExportInput { + const report = { ...golden.reports.demo, observations } + return { + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer, + exportedAt: FIXED_EXPORTED_AT, + } +} + +describe('resvg rasterisation of the demo views', () => { + it('main (haloed) and head views: 1200 px wide, highlight present, sane coverage', async () => { + const rasters: Raster[] = [] + const [main, , , head] = golden.reports.demo.observations + const { pdf, warnings } = await exportReportArchive( + inputFor([main!, head!], resvgRasterizer(rasters)), + ) + expect(warnings).toEqual([]) + expect(rasters).toHaveLength(2) + for (const { requested, png } of rasters) { + const facts = pixelFacts(png) + expect(facts.width).toBe(1200) + expect(Math.abs(facts.height - requested.heightPx)).toBeLessThanOrEqual(1) + expect(facts.highlightPixels).toBeGreaterThan(0) + expect(facts.nonWhiteRatio).toBeGreaterThanOrEqual(0.01) + expect(facts.nonWhiteRatio).toBeLessThanOrEqual(0.9) + } + // main: 2073.4 × 1629.4 → 943 px; head: 500 × 380 → 912 px + expect(rasters.map((r) => r.requested.heightPx)).toEqual([943, 912]) + expect((await PDFDocument.load(pdf)).getPageCount()).toBe(3) + }, 60_000) + + it('a rasterizer that throws: page without image, one view_raster_failed warning', async () => { + const [main] = golden.reports.demo.observations + const failing: Rasterizer = async () => { + throw new Error('no renderer here') + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive(inputFor([main!], failing)) + expect(warnings).toEqual([ + { kind: 'view_raster_failed', observationId: main!.id, viewId: 'main' }, + ]) + expect(recording.images).toEqual([]) + expect(recording.texts.some((t) => t.text === 'VUE GÉNÉRALE')).toBe(false) + } finally { + recording.stop() + } + }) +}) diff --git a/packages/pdf/tests/read.test.ts b/packages/pdf/tests/read.test.ts new file mode 100644 index 00000000..bfda7ecf --- /dev/null +++ b/packages/pdf/tests/read.test.ts @@ -0,0 +1,175 @@ +/** + * T4 T5 T6 (STEP6 §4, §7, §14 "Read"): roundtrip, the frozen v2 PDFs and + * the 612-leaf legacy report, the bare v3 fixture, wrapper and report + * versions, stripped attachments, attachment selection, size cap. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { + buildSheetSnapshot, + type Report, + type ReportArchiveEnvelope, +} from '@faunosteo/domain' +import { + ArchiveReadError, + defaultPdfLabels, + exportReportArchive, + MAX_PDF_BYTES, + readReportArchive, + type ExportResult, +} from '../src' +import { readFixtureBytes } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + nologosBranding, + rasterizerOf, +} from './helpers/goldens' +import { pdfWithAttachment, pdfWithoutAttachment } from './helpers/pdf' +import { + allLeavesMigrated, + loadGoldenReports, + type GoldenReports, +} from './helpers/reports' + +let golden: GoldenReports +const map = () => golden.draft.migrationMap + +beforeAll(() => { + golden = loadGoldenReports() +}) + +function exportOnDraft(report: Report): Promise { + return exportReportArchive({ + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + }) +} + +const unresolvedFindings = (report: Report) => + report.observations.flatMap((o) => o.findings).filter((f) => f.unresolved) + .length + +async function rejects( + bytes: Uint8Array, + expected: Partial, +): Promise { + const promise = readReportArchive(bytes, map()) + await expect(promise).rejects.toBeInstanceOf(ArchiveReadError) + await expect(promise).rejects.toMatchObject(expected) +} + +describe('T4 roundtrip', () => { + it('reads back the exported envelope whole', async () => { + const { pdf, envelope } = await exportOnDraft(golden.reports.demo) + const outcome = await readReportArchive(pdf, map()) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.migrated).toBe(false) + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.archive).toEqual(envelope) + }) +}) + +describe('T5 v2 archives and the bare v3 fixture', () => { + it.each(['report-v2.full.pdf', 'report-v2.minimal.pdf'])( + '%s: migrated, re-exported, imported again equal', + async (name) => { + const first = await readReportArchive(readFixtureBytes(name), map()) + expect(first.origin).toBe('v2') + expect(first.migrated).toBe(true) + expect(first.archive).toBeNull() + expect(first.report.version).toBe(3) + const { pdf } = await exportOnDraft(first.report) + const again = await readReportArchive(pdf, map()) + expect(again.origin).toBe('envelope_v1') + expect(again.report).toEqual(first.report) + }, + ) + + it('keeps the 29 unresolved findings of the 612-leaf report through export and import', async () => { + const migrated = allLeavesMigrated(golden.draft) + expect(migrated.unresolvedFindings).toBe(29) + expect(unresolvedFindings(migrated.report)).toBe(29) + const { pdf } = await exportOnDraft(migrated.report) + const again = await readReportArchive(pdf, map()) + expect(unresolvedFindings(again.report)).toBe(29) + expect(again.report).toEqual(migrated.report) + }) + + it('reads report-v3.bare.pdf as a bare v3 with no archive', async () => { + const outcome = await readReportArchive( + readFixtureBytes('report-v3.bare.pdf'), + map(), + ) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(golden.reports.demo) + }) +}) + +describe('T6 versions', () => { + let envelope: ReportArchiveEnvelope + beforeAll(async () => { + envelope = (await exportOnDraft(golden.reports.demo)).envelope + }) + + it('envelope v2 wrapper: report kept, snapshot rejected as unsupported_envelope', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { + ...envelope, + envelopeVersion: 2, + }) + const outcome = await readReportArchive(bytes, map()) + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBe('unsupported_envelope') + }) + + it('envelope v1 with a report v4: incompatible_version 4', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { + ...envelope, + report: { ...envelope.report, version: 4 }, + }) + await rejects(bytes, { kind: 'incompatible_version', foundVersion: 4 }) + }) + + it('bare report version 7: incompatible_version 7', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { version: 7 }) + await rejects(bytes, { kind: 'incompatible_version', foundVersion: 7 }) + }) +}) + +describe('attachment presence and selection', () => { + it('a stamped PDF without attachment: attachment_stripped', async () => { + const bytes = await pdfWithoutAttachment(['faunosteo-archive/1']) + await rejects(bytes, { kind: 'attachment_stripped' }) + }) + + it('a foreign PDF: no_attachment', async () => { + await rejects(await pdfWithoutAttachment(), { kind: 'no_attachment' }) + const foreign = await pdfWithAttachment('other.json', { hello: 'world' }) + await rejects(foreign, { kind: 'no_attachment' }) + }) + + it('the Filespec named osteo-report.json wins over an earlier EmbeddedFile', async () => { + const bytes = await pdfWithAttachment( + 'osteo-report.json', + golden.reports.demo, + { before: ['other.json', { hello: 'world', version: 2 }] }, + ) + const outcome = await readReportArchive(bytes, map()) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.report).toEqual(golden.reports.demo) + }) + + it('refuses an oversized or unparseable PDF as invalid_pdf', async () => { + await rejects(new Uint8Array(MAX_PDF_BYTES + 1), { kind: 'invalid_pdf' }) + await rejects(new TextEncoder().encode('not a pdf at all'), { + kind: 'invalid_pdf', + }) + }) +}) diff --git a/packages/pdf/tests/reexport.test.ts b/packages/pdf/tests/reexport.test.ts new file mode 100644 index 00000000..69f29dcd --- /dev/null +++ b/packages/pdf/tests/reexport.test.ts @@ -0,0 +1,83 @@ +/** + * T1 (STEP6 §5, §7): an archive re-exports from its own envelope, with no + * sheet, no network and no configuration: same drawn text, same images, + * same view facts, same envelope but the export time. + */ +import { afterAll, describe, expect, it, vi } from 'vitest' +import { + buildSheetSnapshot, + ReportSchema, + type ReportArchiveEnvelope, +} from '@faunosteo/domain' +import { + defaultPdfLabels, + exportFromEnvelope, + exportReportArchive, + readReportArchive, + type ExportResult, +} from '../src' +import { loadDraftSheet, readFixtureJson } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + logosBranding, + rasterizerOf, + recordDrawing, + snapshotViews, + type DrawRecording, +} from './helpers/goldens' + +afterAll(() => vi.restoreAllMocks()) + +type Recorded = ExportResult & Pick + +async function recorded(run: () => Promise): Promise { + const recording = recordDrawing() + try { + const result = await run() + return { ...result, texts: recording.texts, images: recording.images } + } finally { + recording.stop() + } +} + +const withoutDate = ({ exportedAt: _e, ...rest }: ReportArchiveEnvelope) => rest + +describe('re-export from the envelope alone', () => { + it('reproduces text, images, views and the envelope minus exportedAt', async () => { + // The draft is known here only, for the first export. + const draft = loadDraftSheet() + const report = ReportSchema.parse(readFixtureJson('report-v3.demo.json')) + const first = await recorded(() => + exportReportArchive({ + report, + sheet: buildSheetSnapshot(draft, report), + branding: logosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('logos'), + exportedAt: FIXED_EXPORTED_AT, + }), + ) + const outcome = await readReportArchive(first.pdf, draft.migrationMap) + expect(outcome.origin).toBe('envelope_v1') + const archive = outcome.archive! + + // From here on, only the archive is used. + const later = new Date('2027-01-01T00:00:00.000Z') + const second = await recorded(() => + exportFromEnvelope(archive, { + locale: 'fr', + rasterizer: rasterizerOf('logos'), + exportedAt: later, + }), + ) + expect(second.warnings).toEqual([]) + expect(second.texts).toEqual(first.texts) + expect(second.images).toEqual(first.images) + expect( + snapshotViews(second.envelope.sheetSnapshot, second.envelope.report), + ).toEqual(snapshotViews(first.envelope.sheetSnapshot, report)) + expect(second.envelope.exportedAt).toBe(later.toISOString()) + expect(withoutDate(second.envelope)).toEqual(withoutDate(first.envelope)) + }) +}) diff --git a/packages/pdf/tests/security.test.ts b/packages/pdf/tests/security.test.ts new file mode 100644 index 00000000..08f3e8e7 --- /dev/null +++ b/packages/pdf/tests/security.test.ts @@ -0,0 +1,411 @@ +/** + * T8 (STEP6 §6, §15): a hostile or oversized snapshot never sinks the + * report on import and never produces an unreadable file on export; hostile + * SVG content is removed, refused or clamped; the real assets pass the + * sanitiser untouched; the inflate bomb guard stays. + */ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { beforeAll, describe, expect, it } from 'vitest' +import { + assertSnapshot, + SnapshotError, + type Report, + type ReportArchiveEnvelope, + type SheetSnapshot, +} from '@faunosteo/domain' +import { + ArchiveExportError, + defaultPdfLabels, + exportReportArchive, + readReportArchive, + type ExportInput, + type Rasterizer, +} from '../src' +import { inflateFlate } from '../src/attachment/inflate' +import { SvgRejectedError } from '../src/errors' +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 { + FIXED_EXPORTED_AT, + nologosBranding, + ONE_PX_PNG, + rasterizerOf, + recordDrawing, +} from './helpers/goldens' +import { pdfWithAttachment } from './helpers/pdf' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +let golden: GoldenReports +let envelope: ReportArchiveEnvelope + +const clone = (value: T): T => JSON.parse(JSON.stringify(value)) as T + +function baseInput(report: Report, sheet: SheetSnapshot): ExportInput { + return { + report, + sheet, + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + } +} + +beforeAll(async () => { + golden = loadGoldenReports() + envelope = ( + await exportReportArchive( + baseInput(golden.reports.demo, golden.snapshots.demo), + ) + ).envelope +}) + +/** The reason the domain gate gives: the oracle the engine must surface. */ +function domainReason(snapshot: unknown): string { + try { + assertSnapshot(snapshot) + return 'accepted' + } catch (error) { + if (error instanceof SnapshotError) return error.reason + throw error + } +} + +type Mutation = (snapshot: SheetSnapshot) => void + +const UUID = (i: number) => `00000000-0000-4000-8000-00000000000${i}` + +const MUTATIONS: Array<[string, string, Mutation]> = [ + [ + '5 assets', + 'schema', + (s) => { + s.assets = Array.from({ length: 5 }, (_, i) => ({ + ...s.assets[0]!, + svgAssetId: i === 0 ? s.assets[0]!.svgAssetId : UUID(i), + })) + }, + ], + [ + 'a 3 MiB asset', + 'caps', + (s) => { + s.assets[0]!.svg = 'é'.repeat(1_100_000) + }, + ], + [ + 'finding depth 9', + 'caps', + (s) => { + const leaf = { + id: 'deep', + name: { fr: 'x', en: 'x' }, + description: {}, + requires_vet_referral: false, + reference_ids: [], + review_status: 'inherited' as const, + children: [] as never[], + } + let node: typeof leaf = leaf + for (let depth = 0; depth < 9; depth += 1) { + node = { ...leaf, id: `n${depth}`, children: [node] as never[] } + } + const zone = s.document.finding_zones.find((z) => z.categories.length)! + zone.categories[0]!.children.push(node) + }, + ], + [ + '1,025 annotations', + 'caps', + (s) => { + s.document.annotations.push( + ...Array.from({ length: 1025 }, (_, i) => ({ + ...s.document.annotations[0]!, + id: `extra-${i}`, + })), + ) + }, + ], + [ + 'a view chain cycle', + 'integrity', + (s) => { + const head = s.document.views.find((v) => v.id === 'head')! + if (head.kind === 'detail') head.parent_view_id = 'head' + }, + ], + [ + 'a dangling svg_asset_id', + 'integrity', + (s) => { + s.document.views.find((v) => v.kind === 'main')!.svg_asset_id = UUID(9) + }, + ], + [ + 'another sheet (sheet_mismatch)', + 'sheet_mismatch', + (s) => { + s.ref.documentSha256 = 'f'.repeat(64) + }, + ], +] + +describe('import: the report survives a rejected snapshot', () => { + it.each(MUTATIONS)( + '%s → %s', + async (_name, reason, mutate) => { + const hostile = clone(envelope) + mutate(hostile.sheetSnapshot) + if (reason !== 'sheet_mismatch') { + expect(domainReason(hostile.sheetSnapshot)).toBe(reason) + } + const bytes = await pdfWithAttachment('osteo-report.json', hostile) + const outcome = await readReportArchive(bytes, golden.draft.migrationMap) + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBe(reason) + }, + 20_000, + ) +}) + +describe('export: a snapshot over the caps fails with a typed error and no file', () => { + it.each([ + ['1,025 annotations', 'snapshot_too_large', MUTATIONS[3]![2]], + ['a 3 MiB asset', 'snapshot_too_large', MUTATIONS[1]![2]], + ['5 assets', 'snapshot_invalid', MUTATIONS[0]![2]], + ['a dangling svg_asset_id', 'snapshot_invalid', MUTATIONS[5]![2]], + ['another sheet', 'sheet_mismatch', MUTATIONS[6]![2]], + ] as const)('%s → %s', async (_name, kind, mutate) => { + const sheet = clone(golden.snapshots.demo) + mutate(sheet) + const promise = exportReportArchive(baseInput(golden.reports.demo, sheet)) + await expect(promise).rejects.toBeInstanceOf(ArchiveExportError) + await expect(promise).rejects.toMatchObject({ kind }) + }) + + it('too many observations or views per observation → too_many_pages', async () => { + const demo = golden.reports.demo + const many = { + ...demo, + observations: Array.from({ length: 501 }, (_, i) => ({ + ...demo.observations[0]!, + id: `o${i}`, + })), + } + await expect( + exportReportArchive(baseInput(many, golden.snapshots.demo)), + ).rejects.toMatchObject({ kind: 'too_many_pages' }) + const views = { + ...demo, + observations: [ + { + ...demo.observations[0]!, + zones: Array.from({ length: 9 }, (_, i) => ({ + annotationId: 'c7-t1', + viewId: `v${i}`, + })), + }, + ], + } + await expect( + exportReportArchive(baseInput(views, golden.snapshots.demo)), + ).rejects.toMatchObject({ kind: 'too_many_pages' }) + }) +}) + +// --------------------------------------------------------------------------- +// Hostile SVG + +const SVG_OPEN = + '' +const wrap = (inner: string) => `${SVG_OPEN}${inner}` + +/** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */ +async function exportWithAsset(svg: string): Promise { + const sheet = clone(golden.snapshots.demo) + sheet.assets[0]!.svg = svg + const seen: string[] = [] + const rasterizer: Rasterizer = async (text) => { + seen.push(text) + return ONE_PX_PNG + } + const report = { + ...golden.reports.demo, + observations: [golden.reports.demo.observations[0]!], + } + const { warnings } = await exportReportArchive({ + ...baseInput(report, sheet), + rasterizer, + }) + expect(warnings).toEqual([]) + return seen +} + +describe('hostile SVG assets', () => { + it('' + + '' + + '' + + '' + + '' + + '' + + '', + ), + ) + expect(seen).toBeDefined() + for (const forbidden of [ + '') + expect(seen).toContain('') + expect(seen).toContain('fill="#b85a3f"') + }) + + it('the sanitiser names what it removed and clamps stdDeviation', () => { + const root = parseSvg( + wrap( + '' + + '' + + '', + ), + ) + const { removed } = sanitizeSvgRoot(root) + expect(removed).toEqual([ + 'script', + 'g@onclick', + 'g@data-x', + 'path@style', + 'feTurbulence', + 'use@xlink:href', + 'a', + ]) + expect(serializeSvg(root)).toContain('stdDeviation="100 3"') + }) + + it(' and 257 are refused: the export fails as snapshot_invalid', async () => { + const entity = + ']>' + wrap('&x;') + await expect(exportWithAsset(entity)).rejects.toMatchObject({ + kind: 'snapshot_invalid', + }) + const uses = (count: number) => + wrap( + '' + + ''.repeat(count), + ) + await expect(exportWithAsset(uses(257))).rejects.toMatchObject({ + kind: 'snapshot_invalid', + }) + expect(() => sanitizeSvgRoot(parseSvg(uses(257)))).toThrow(SvgRejectedError) + await expect(exportWithAsset(uses(256))).resolves.toHaveLength(1) + }) + + it('a huge root viewBox is clamped to a 1200×2400 raster', async () => { + expect(rasterSizeOf('0 0 1 100000')).toEqual({ + widthPx: 1200, + heightPx: 2400, + }) + expect(rasterSizeOf('0 0 100000 1')).toEqual({ + widthPx: 1200, + heightPx: 240, + }) + expect(rasterSizeOf(null)).toEqual({ widthPx: 1200, heightPx: 720 }) + const sizes: Array<{ widthPx: number; heightPx: number }> = [] + const branding = nologosBranding() + branding.partner!.logo = { + kind: 'svg', + svg: '', + } + await exportReportArchive({ + ...baseInput(golden.reports.demo, golden.snapshots.demo), + branding, + rasterizer: async (_svg, size) => { + sizes.push(size) + return ONE_PX_PNG + }, + }) + expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 }) + }) + + 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'), + ]) { + const text = readFileSync(file, 'utf8') + const pristine = serializeSvg(parseSvg(text)) + const root = parseSvg(text) + expect(sanitizeSvgRoot(root)).toEqual({ removed: [] }) + expect(serializeSvg(root)).toBe(pristine) + } + }) +}) + +describe('__proto__ ids and the inflate bomb', () => { + it('report ids named __proto__ print raw and pollute nothing', async () => { + const demo = golden.reports.demo + const report: Report = { + ...demo, + observations: [ + { + ...demo.observations[0]!, + zones: [{ annotationId: '__proto__', viewId: 'main' }], + findings: [ + { + findingZoneId: '__proto__', + path: ['__proto__'], + labelFrSnapshot: 'proto fr', + labelEnSnapshot: 'proto en', + }, + ], + }, + ], + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive( + baseInput(report, golden.snapshots.demo), + ) + expect(warnings).toEqual([]) + const drawn = recording.texts.map((t) => t.text) + expect(drawn).toContain('__proto__') + expect(drawn).toContain('CONSTATS — __PROTO__') + expect(drawn).toContain('proto fr') + } finally { + recording.stop() + } + expect(Object.keys(Object.prototype)).toEqual([]) + expect(({} as Record).polluted).toBeUndefined() + }) + + async function deflate(data: Uint8Array): Promise { + const stream = new Blob([data]) + .stream() + .pipeThrough(new CompressionStream('deflate')) + return new Uint8Array(await new Response(stream).arrayBuffer()) + } + + it('inflates a normal payload and returns null for a 24 MB bomb', async () => { + const payload = new TextEncoder().encode(JSON.stringify({ version: 2 })) + const out = await inflateFlate(await deflate(payload)) + expect(new TextDecoder().decode(out!)).toContain('version') + const bomb = await deflate(new Uint8Array(24 * 1024 * 1024)) + expect(bomb.byteLength).toBeLessThan(1024 * 1024) + expect(await inflateFlate(bomb)).toBeNull() + }) +}) diff --git a/packages/pdf/tests/size.test.ts b/packages/pdf/tests/size.test.ts new file mode 100644 index 00000000..1c10be7f --- /dev/null +++ b/packages/pdf/tests/size.test.ts @@ -0,0 +1,47 @@ +/** + * T7 (STEP6 §7): the demo envelope stays well under the attachment cap; + * stored (Flate) and raw sizes are printed for both brandings. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { defaultPdfLabels, exportReportArchive } from '../src' +import { + brandingOf, + FIXED_EXPORTED_AT, + rasterizerOf, + type LogoMode, +} from './helpers/goldens' +import { storedAttachmentSize } from './helpers/pdf' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +const MAX_STORED = 250_000 + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +describe('demo envelope size', () => { + it.each(['nologos', 'logos'])( + '%s: stored attachment under 250,000 bytes', + async (mode) => { + const { pdf, envelope } = await exportReportArchive({ + report: golden.reports.demo, + sheet: golden.snapshots.demo, + branding: brandingOf(mode), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf(mode), + exportedAt: FIXED_EXPORTED_AT, + }) + const raw = new TextEncoder().encode( + JSON.stringify(envelope, null, 2), + ).byteLength + const stored = await storedAttachmentSize(pdf) + console.log( + `[size] demo ${mode}: stored ${stored} B, raw ${raw} B, pdf ${pdf.byteLength} B`, + ) + expect(stored).toBeLessThan(MAX_STORED) + expect(stored).toBeLessThan(raw) + }, + ) +}) diff --git a/packages/pdf/tests/text.test.ts b/packages/pdf/tests/text.test.ts new file mode 100644 index 00000000..38c5332b --- /dev/null +++ b/packages/pdf/tests/text.test.ts @@ -0,0 +1,90 @@ +/** + * T9 (STEP6 §15): the WinAnsi canary. One text ingress, so a glyph the + * standard fonts cannot encode never reaches pdf-lib; `formatDate` never + * throws on user data. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { PDFDocument, StandardFonts } from 'pdf-lib' +import { buildSheetSnapshot } from '@faunosteo/domain' +import { defaultPdfLabels, exportReportArchive } from '../src' +import { formatDate } from '../src/render/dates' +import { wrapLines } from '../src/render/text' +import { safeText } from '../src/text' +import { + FIXED_EXPORTED_AT, + nologosBranding, + rasterizerOf, + recordDrawing, +} from './helpers/goldens' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +describe('safeText', () => { + it('keeps the WinAnsi glyphs the pages use', () => { + const kept = 'Fixation (C2–C7) — bilan • zone · Sévérité à l’écu €' + expect(safeText(kept)).toBe(kept) + }) + + it('replaces unencodable glyphs by ? and strips control characters', () => { + expect(safeText('⚠ alerte')).toBe('? alerte') + expect(safeText('a → b')).toBe('a ? b') + expect(safeText('ok 😀')).toBe('ok ?') + expect(safeText('a\tb')).toBe('ab') + expect(safeText('a
b')).toBe('ab') + expect(safeText('a\x1bb')).toBe('ab') + }) + + it('wrapLines splits on any whitespace first, then makes each word safe', async () => { + const doc = await PDFDocument.create() + const font = await doc.embedFont(StandardFonts.Helvetica) + expect(wrapLines('un\tdeux\ntrois ⚠', font, 10, 1000)).toEqual([ + 'un deux trois ?', + ]) + }) +}) + +describe('export with hostile text', () => { + it('a report with ⚠ in a comment exports; the glyph prints as ?', async () => { + const demo = golden.reports.demo + const report = { + ...demo, + observations: [ + { ...demo.observations[0]!, comment: 'Attention ⚠ tab\tici → fin' }, + ], + conclusion: 'Conclusion ⚠', + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive({ + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + }) + expect(warnings).toEqual([]) + const drawn = recording.texts.map((t) => t.text) + expect(drawn).toContain('Attention ? tab ici ? fin') + expect(drawn).toContain('Conclusion ?') + expect(drawn.every((t) => safeText(t) === t)).toBe(true) + } finally { + recording.stop() + } + }) +}) + +describe('formatDate', () => { + it('formats an ISO date per locale and returns anything else unchanged', () => { + expect(formatDate('2026-11-20', 'fr')).toBe('20 novembre 2026') + expect(formatDate('2026-11-20', 'en')).toBe('November 20, 2026') + expect(formatDate('n/a', 'fr')).toBe('n/a') + expect(formatDate('2026-13-45', 'en')).toBe('2026-13-45') + expect(formatDate('2026-02-30', 'en')).toBe('2026-02-30') + }) +}) diff --git a/packages/pdf/tsconfig.json b/packages/pdf/tsconfig.json new file mode 100644 index 00000000..99d2ea87 --- /dev/null +++ b/packages/pdf/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "types": ["node", "vitest/globals"], + "noEmit": true + }, + "include": ["src", "tests"], + "exclude": ["node_modules"] +} diff --git a/packages/pdf/vitest.config.ts b/packages/pdf/vitest.config.ts new file mode 100644 index 00000000..f6374039 --- /dev/null +++ b/packages/pdf/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/**/*.test.ts'], + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 11574827..fea5ad80 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -168,6 +168,49 @@ importers: specifier: ^3.2.7 version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15) + packages/pdf: + dependencies: + '@faunosteo/anatomy': + specifier: workspace:* + version: link:../anatomy + '@faunosteo/domain': + specifier: workspace:* + version: link:../domain + '@pdf-lib/standard-fonts': + specifier: ^1.0.0 + version: 1.0.0 + '@xmldom/xmldom': + specifier: ^0.9.8 + version: 0.9.12 + pdf-lib: + specifier: ^1.17.1 + version: 1.17.1 + devDependencies: + '@pdf-lib/upng': + specifier: ^1.0.1 + version: 1.0.1 + '@resvg/resvg-js': + specifier: ^2.6.2 + version: 2.6.2 + '@types/node': + specifier: ^20.19.41 + version: 20.19.41 + eslint: + specifier: ^9.17.0 + version: 9.39.4(jiti@2.7.0) + globals: + specifier: ^15.14.0 + version: 15.15.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + typescript-eslint: + specifier: ^8.19.0 + version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15) + packages/supabase: dependencies: '@faunosteo/domain': @@ -473,6 +516,82 @@ packages: '@pdf-lib/upng@1.0.1': resolution: {integrity: sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==} + '@resvg/resvg-js-android-arm-eabi@2.6.2': + resolution: {integrity: sha512-FrJibrAk6v29eabIPgcTUMPXiEz8ssrAk7TXxsiZzww9UTQ1Z5KAbFJs+Z0Ez+VZTYgnE5IQJqBcoSiMebtPHA==} + engines: {node: '>= 10'} + cpu: [arm] + os: [android] + + '@resvg/resvg-js-android-arm64@2.6.2': + resolution: {integrity: sha512-VcOKezEhm2VqzXpcIJoITuvUS/fcjIw5NA/w3tjzWyzmvoCdd+QXIqy3FBGulWdClvp4g+IfUemigrkLThSjAQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [android] + + '@resvg/resvg-js-darwin-arm64@2.6.2': + resolution: {integrity: sha512-nmok2LnAd6nLUKI16aEB9ydMC6Lidiiq2m1nEBDR1LaaP7FGs4AJ90qDraxX+CWlVuRlvNjyYJTNv8qFjtL9+A==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@resvg/resvg-js-darwin-x64@2.6.2': + resolution: {integrity: sha512-GInyZLjgWDfsVT6+SHxQVRwNzV0AuA1uqGsOAW+0th56J7Nh6bHHKXHBWzUrihxMetcFDmQMAX1tZ1fZDYSRsw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@resvg/resvg-js-linux-arm-gnueabihf@2.6.2': + resolution: {integrity: sha512-YIV3u/R9zJbpqTTNwTZM5/ocWetDKGsro0SWp70eGEM9eV2MerWyBRZnQIgzU3YBnSBQ1RcxRZvY/UxwESfZIw==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@resvg/resvg-js-linux-arm64-gnu@2.6.2': + resolution: {integrity: sha512-zc2BlJSim7YR4FZDQ8OUoJg5holYzdiYMeobb9pJuGDidGL9KZUv7SbiD4E8oZogtYY42UZEap7dqkkYuA91pg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@resvg/resvg-js-linux-arm64-musl@2.6.2': + resolution: {integrity: sha512-3h3dLPWNgSsD4lQBJPb4f+kvdOSJHa5PjTYVsWHxLUzH4IFTJUAnmuWpw4KqyQ3NA5QCyhw4TWgxk3jRkQxEKg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@resvg/resvg-js-linux-x64-gnu@2.6.2': + resolution: {integrity: sha512-IVUe+ckIerA7xMZ50duAZzwf1U7khQe2E0QpUxu5MBJNao5RqC0zwV/Zm965vw6D3gGFUl7j4m+oJjubBVoftw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@resvg/resvg-js-linux-x64-musl@2.6.2': + resolution: {integrity: sha512-UOf83vqTzoYQO9SZ0fPl2ZIFtNIz/Rr/y+7X8XRX1ZnBYsQ/tTb+cj9TE+KHOdmlTFBxhYzVkP2lRByCzqi4jQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@resvg/resvg-js-win32-arm64-msvc@2.6.2': + resolution: {integrity: sha512-7C/RSgCa+7vqZ7qAbItfiaAWhyRSoD4l4BQAbVDqRRsRgY+S+hgS3in0Rxr7IorKUpGE69X48q6/nOAuTJQxeQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@resvg/resvg-js-win32-ia32-msvc@2.6.2': + resolution: {integrity: sha512-har4aPAlvjnLcil40AC77YDIk6loMawuJwFINEM7n0pZviwMkMvjb2W5ZirsNOZY4aDbo5tLx0wNMREp5Brk+w==} + engines: {node: '>= 10'} + cpu: [ia32] + os: [win32] + + '@resvg/resvg-js-win32-x64-msvc@2.6.2': + resolution: {integrity: sha512-ZXtYhtUr5SSaBrUDq7DiyjOFJqBVL/dOBN7N/qmi/pO0IgiWW/f/ue3nbvu9joWE5aAKDoIzy/CxsY0suwGosQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@resvg/resvg-js@2.6.2': + resolution: {integrity: sha512-xBaJish5OeGmniDj9cW5PRa/PtmuVU3ziqrbr5xJj901ZDN4TosrVaNZpEiLZAxdfnhAe7uQ7QFWfjPe9d9K2Q==} + engines: {node: '>= 10'} + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -2507,6 +2626,57 @@ snapshots: dependencies: pako: 1.0.11 + '@resvg/resvg-js-android-arm-eabi@2.6.2': + optional: true + + '@resvg/resvg-js-android-arm64@2.6.2': + optional: true + + '@resvg/resvg-js-darwin-arm64@2.6.2': + optional: true + + '@resvg/resvg-js-darwin-x64@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm-gnueabihf@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm64-gnu@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm64-musl@2.6.2': + optional: true + + '@resvg/resvg-js-linux-x64-gnu@2.6.2': + optional: true + + '@resvg/resvg-js-linux-x64-musl@2.6.2': + optional: true + + '@resvg/resvg-js-win32-arm64-msvc@2.6.2': + optional: true + + '@resvg/resvg-js-win32-ia32-msvc@2.6.2': + optional: true + + '@resvg/resvg-js-win32-x64-msvc@2.6.2': + optional: true + + '@resvg/resvg-js@2.6.2': + optionalDependencies: + '@resvg/resvg-js-android-arm-eabi': 2.6.2 + '@resvg/resvg-js-android-arm64': 2.6.2 + '@resvg/resvg-js-darwin-arm64': 2.6.2 + '@resvg/resvg-js-darwin-x64': 2.6.2 + '@resvg/resvg-js-linux-arm-gnueabihf': 2.6.2 + '@resvg/resvg-js-linux-arm64-gnu': 2.6.2 + '@resvg/resvg-js-linux-arm64-musl': 2.6.2 + '@resvg/resvg-js-linux-x64-gnu': 2.6.2 + '@resvg/resvg-js-linux-x64-musl': 2.6.2 + '@resvg/resvg-js-win32-arm64-msvc': 2.6.2 + '@resvg/resvg-js-win32-ia32-msvc': 2.6.2 + '@resvg/resvg-js-win32-x64-msvc': 2.6.2 + '@rolldown/pluginutils@1.0.0-beta.27': {} '@rollup/rollup-android-arm-eabi@4.60.4':