feat(pdf): @faunosteo/pdf engine — explicit inputs, envelope v1 attachment, layered reader, xmldom composition, allowlist SVG sanitiser, WinAnsi guard, rasterizer adapter; goldens reproduced

This commit is contained in:
bchanot committed 2026-10-11 13:09:17 +02:00
1 parent e7419cb4cb
commit c17956031d
46 files changed
+4396 -1

No files matched your search

+43
View File
@@ -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<Uint8Array | null> {
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
}
}
+105
View File
@@ -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<Uint8Array | null> {
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<unknown> {
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')
}
}
+19
View File
@@ -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<void> {
await pdfDoc.attach(bytes, ATTACHMENT_FILENAME, {
mimeType: 'application/json',
description: ATTACHMENT_DESCRIPTION,
creationDate: exportedAt,
modificationDate: exportedAt,
afRelationship: AFRelationship.Data,
})
}
+91
View File
@@ -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<ExportWarning, { kind: 'logo_failed' }>['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<PDFImage> {
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<PDFImage | null> {
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<CreditAsset | null> {
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<BrandingImages> {
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),
}
}
+53
View File
@@ -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'
}
}
+208
View File
@@ -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<void> {
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<ExportResult> {
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<ExportResult> {
return exportReportArchive({
report: env.report,
sheet: env.sheetSnapshot,
branding: env.branding,
labels: env.labels,
...opts,
})
}
+30
View File
@@ -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',
}
+30
View File
@@ -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',
}
+6
View File
@@ -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 }
+22
View File
@@ -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'
+51
View File
@@ -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<PDFDocument> {
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<ArchiveReadOutcome> {
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')
}
}
+117
View File
@@ -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<void> {
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
}
}
+18
View File
@@ -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)
+11
View File
@@ -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
}
+26
View File
@@ -0,0 +1,26 @@
import type { PdfLocale } from './context'
const LOCALE_TAG: Record<PdfLocale, string> = {
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)
}
+17
View File
@@ -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<EmbeddedFonts> {
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
pdfDoc.embedFont(StandardFonts.Helvetica),
pdfDoc.embedFont(StandardFonts.HelveticaBold),
pdfDoc.embedFont(StandardFonts.TimesRoman),
])
return { bodyRegular, bodyBold, headingRegular }
}
+170
View File
@@ -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<CreditAsset['image']> },
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)
}
+112
View File
@@ -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,
})
}
+36
View File
@@ -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)
}
}
+634
View File
@@ -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<Severity, ReturnType<typeof rgb>> = {
mild: rgb(0.55, 0.65, 0.45),
moderate: rgb(0.85, 0.55, 0.18),
severe: rgb(0.78, 0.2, 0.2),
}
const SECTION_TEXT_SIZE = 10
const SEPARATOR_GLYPH = '•'
const SEPARATOR_SIZE = 14
const SEPARATOR_SIDE_GAP = 5
/** 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<RasterisedView> {
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<RenderedImage[]> {
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<string, Finding[]>()
for (const f of findings) {
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
}
const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0]!
const side = group[0]?.side
let zoneName = findingZoneName(zoneId, sheet, 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<void> {
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)
}
+46
View File
@@ -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
}
+37
View File
@@ -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 = /<!(DOCTYPE|ENTITY)/i
const SVG_NS = 'http://www.w3.org/2000/svg'
function rejectOnError(level: 'warning' | 'error' | 'fatalError'): void {
if (level !== 'warning') throw new SvgRejectedError('malformed')
}
export function parseSvg(text: string): Element {
if (ENTITY_MARKUP.test(text)) throw new SvgRejectedError('doctype')
let root: Element | null
try {
const parser = new DOMParser({ onError: rejectOnError })
root = parser.parseFromString(text, 'image/svg+xml').documentElement
} catch (error) {
if (error instanceof SvgRejectedError) throw error
throw new SvgRejectedError('malformed')
}
if (!root || root.localName !== 'svg' || root.namespaceURI !== SVG_NS) {
throw new SvgRejectedError('not_svg')
}
return root
}
/** The root element alone: no XML declaration, as the app serialised it. */
export function serializeSvg(root: Element): string {
return new XMLSerializer().serializeToString(root)
}
+237
View File
@@ -0,0 +1,237 @@
import type { Attr, Element, Node } from '@xmldom/xmldom'
import { SvgRejectedError } from '../errors'
/**
* Allowlist sanitiser for the sheet drawings and the branding SVGs
* (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the
* inventory of the real assets plus structural needs are removed with
* their subtree; `href` and `url(…)` must stay inside the document; a
* `style` attribute may carry no external reference; the halo filters are
* clamped. Element, nesting and `<use>` 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 }
}
+123
View File
@@ -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, SheetView>,
): string | null {
const visited = new Set<string>()
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')),
}
}
+21
View File
@@ -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('')
}
+43
View File
@@ -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<Uint8Array>
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[]
}