Files
faunosteo/packages/pdf/src/export.ts
T

226 lines
6.9 KiB
TypeScript

import { PDFDocument } from 'pdf-lib'
import {
assertSnapshot,
BrandingSchema,
buildSheetIndex,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
PdfLabelSetSchema,
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 0: the branding and the labels pass their schemas again. They reach
* the engine from an archive or from the application and end up in link
* URIs and drawn text, so a caller cannot be trusted to have validated them.
*/
function assertBrandingAndLabels(input: ExportInput): void {
if (!BrandingSchema.safeParse(input.branding).success) {
throw new ArchiveExportError('branding_invalid', 'branding')
}
if (!PdfLabelSetSchema.safeParse(input.labels).success) {
throw new ArchiveExportError('branding_invalid', 'labels')
}
}
/** 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> {
assertBrandingAndLabels(input)
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,
})
}