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,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<Exported> {
|
||||
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 <g> 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<ViewSnapshot[]>(`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)
|
||||
})
|
||||
})
|
||||
@@ -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<T = unknown>(path: string): T {
|
||||
return JSON.parse(readFileSync(path, 'utf8')) as T
|
||||
}
|
||||
|
||||
export function readFixtureJson<T = unknown>(name: string): T {
|
||||
return readJson<T>(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<Record<string, string>>
|
||||
migrationMap: ReportMigrationMap
|
||||
}
|
||||
|
||||
export function loadDraftSheet(): DraftSheet {
|
||||
const json = <T>(name: string) => readJson<T>(join(DRAFT_DIR, name))
|
||||
const ref = json<SeedRef>('sheet-ref.json')
|
||||
const assets: Record<string, string> = {}
|
||||
const assetHashes: Record<string, string> = {}
|
||||
for (const asset of json<SeedAsset[]>('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'),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -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<LinkEntry[]> {
|
||||
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 `<g>` 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<T = unknown>(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))
|
||||
}
|
||||
@@ -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<string, ObservationV2>()
|
||||
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: '',
|
||||
})
|
||||
}
|
||||
@@ -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<Uint8Array> {
|
||||
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<void> {
|
||||
await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, {
|
||||
mimeType: 'application/json',
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function pdfWithoutAttachment(
|
||||
keywords?: string[],
|
||||
): Promise<Uint8Array> {
|
||||
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<number> {
|
||||
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')
|
||||
}
|
||||
@@ -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<ReportName, Report>
|
||||
snapshots: Record<ReportName, SheetSnapshot>
|
||||
/** 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<ReportName, Report> = {
|
||||
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<ReportName, SheetSnapshot>
|
||||
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,
|
||||
)
|
||||
}
|
||||
@@ -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(/<svg\b[^>]*>/)?.[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(/(<svg\b[^>]*?\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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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<ExportResult> {
|
||||
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<ArchiveReadError>,
|
||||
): Promise<void> {
|
||||
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',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<DrawRecording, 'texts' | 'images'>
|
||||
|
||||
async function recorded(run: () => Promise<ExportResult>): Promise<Recorded> {
|
||||
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))
|
||||
})
|
||||
})
|
||||
@@ -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 = <T>(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 =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2073.4 1629.4">'
|
||||
const wrap = (inner: string) => `${SVG_OPEN}${inner}</svg>`
|
||||
|
||||
/** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */
|
||||
async function exportWithAsset(svg: string): Promise<string[]> {
|
||||
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('<script>, on*, javascript: href, external <image>, <style> are gone from what is rasterised', async () => {
|
||||
const [seen] = await exportWithAsset(
|
||||
wrap(
|
||||
'<script>alert(1)</script>' +
|
||||
'<style>path{fill:url(http://evil.test/a)}</style>' +
|
||||
'<defs><path id="p" d="M0 0h10v10z"/></defs>' +
|
||||
'<path d="M0 0h1" onload="steal()" style="fill:url(http://evil.test/b)"/>' +
|
||||
'<use xlink:href="javascript:alert(1)"/><use href="#p"/>' +
|
||||
'<image href="https://evil.test/x.png" width="10" height="10"/>' +
|
||||
'<path d="M1 1h1" fill="url(http://evil.test/c)"/>',
|
||||
),
|
||||
)
|
||||
expect(seen).toBeDefined()
|
||||
for (const forbidden of [
|
||||
'<script',
|
||||
'<style',
|
||||
'onload',
|
||||
'javascript:',
|
||||
'<image',
|
||||
'evil.test',
|
||||
]) {
|
||||
expect(seen).not.toContain(forbidden)
|
||||
}
|
||||
expect(seen).toContain('<use href="#p"/>')
|
||||
expect(seen).toContain('<path id="p" d="M0 0h10v10z"/>')
|
||||
expect(seen).toContain('fill="#b85a3f"')
|
||||
})
|
||||
|
||||
it('the sanitiser names what it removed and clamps stdDeviation', () => {
|
||||
const root = parseSvg(
|
||||
wrap(
|
||||
'<script>x</script><g onclick="y()" data-x="1"><path d="M0 0" style="fill:url(http://e)"/></g>' +
|
||||
'<filter id="f"><feGaussianBlur stdDeviation="500,3"/><feTurbulence/></filter>' +
|
||||
'<use xlink:href="javascript:z"/><a href="#ok"/>',
|
||||
),
|
||||
)
|
||||
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('<!ENTITY> and 257 <use> are refused: the export fails as snapshot_invalid', async () => {
|
||||
const entity =
|
||||
'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]>' + wrap('&x;')
|
||||
await expect(exportWithAsset(entity)).rejects.toMatchObject({
|
||||
kind: 'snapshot_invalid',
|
||||
})
|
||||
const uses = (count: number) =>
|
||||
wrap(
|
||||
'<defs><path id="p" d="M0 0h1"/></defs>' +
|
||||
'<use href="#p"/>'.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: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 100000"><rect width="1" height="1"/></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<string, unknown>).polluted).toBeUndefined()
|
||||
})
|
||||
|
||||
async function deflate(data: Uint8Array): Promise<Uint8Array> {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<LogoMode>(['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)
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user