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:
1 parent
e7419cb4cb
commit
c17956031d
46 files changed
+4396
-1
No files matched your search
@@ -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,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user