Files
faunosteo/packages/pdf/tests/helpers/goldens.ts
T

360 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { BRAND_ASSETS_DIR, GOLDEN_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 brandPng(file: string): { kind: 'png'; base64: string } {
const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file))
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 logo files the app bundles (served by a fetch stub in Phase 0). */
export function logosBranding(): Branding {
return {
siteUrl: SITE_URL,
headerLogo: brandPng('faunosteo-logo-horizontal-512.png'),
footerLogo: brandPng('faunosteo-horizontal-com-512.png'),
poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY },
partner: {
logo: {
kind: 'svg',
svg: readFileSync(
resolve(BRAND_ASSETS_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))
}