feat(pdf): R4.6 app export on the core's session: export.ts drives ExportSession (rasters one by one, warnings in the engine's order, abort on unmount), labels moved to the app, EditorRoute downloads the Blob of the parts; suites read the file's content streams (pdfRead helper), app-path bytes = R4 digests, hex strings upper-case as pdf-lib

This commit is contained in:
bchanot committed 2026-10-19 01:26:13 +02:00
1 parent 9e688b6801
commit d492bf7112
29 files changed
+507 -131

No files matched your search

+17 -6
View File
@@ -34,8 +34,10 @@ import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import { downloadBlob } from '@/lib/download'
import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import type {
ExportWarning,
RebaseOutcome,
} from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { coreFailureMessage } from '@/core/failure'
@@ -95,6 +97,8 @@ export default function EditorRoute() {
const heldAttempt = useRef<number | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
// Leaving the editor mid-export cancels it: the core's session is freed, no file results.
const exportAbort = useRef<AbortController | null>(null)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
// One alert per restore, even if the effect runs again before the re-render.
const rebaseAlerted = useRef(false)
@@ -103,6 +107,10 @@ export default function EditorRoute() {
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
}, [])
useEffect(() => {
return () => exportAbort.current?.abort()
}, [])
// No report in memory: restore the per-tab draft once the sheet is known.
// A draft rebased on another sheet is announced with its unresolved count,
// an unreadable one is set aside. While the core cannot run, nothing is
@@ -233,14 +241,14 @@ export default function EditorRoute() {
async function onExport(index: SheetIndex) {
if (!report) return
setExporting(true)
const abort = new AbortController()
exportAbort.current = abort
try {
const { pdf, warnings } = await exportReportToPdf(report, index, {
locale,
signal: abort.signal,
})
downloadBlob(
new Blob([pdf as BlobPart], { type: 'application/pdf' }),
`bilan-${report.animal.name}-${report.date}.pdf`,
)
downloadBlob(pdf, `bilan-${report.animal.name}-${report.date}.pdf`)
const missing = missingItemsOf(warnings)
if (missing.length) {
window.alert(
@@ -248,9 +256,12 @@ export default function EditorRoute() {
)
}
} catch (err) {
// A cancelled export (the editor left) ends silently.
if (abort.signal.aborted) return
console.error('PDF export failed', err)
window.alert(coreFailureMessage(t, 'editor.export_failed'))
} finally {
if (exportAbort.current === abort) exportAbort.current = null
setExporting(false)
}
}
+13 -6
View File
@@ -1,12 +1,19 @@
import type { Rasterizer } from '@faunosteo/pdf'
/**
* The browser side of the engine's rasterizer adapter: the engine has fixed
* the pixel size, this module only stamps it on the SVG root and lets the
* browser draw the SVG through an Image / canvas pair, which renders exactly
* what the practitioner sees in the inline anatomy canvas.
* The browser side of the core's raster requests (R4.6; the engine's adapter
* before): the core has fixed the pixel size, this module only stamps it on
* the SVG root and lets the browser draw the SVG through an Image / canvas
* pair, which renders exactly what the practitioner sees in the inline
* anatomy canvas.
*/
export interface RasterSize {
widthPx: number
heightPx: number
}
/** Draws `svg` at `size` as a PNG. */
export type Rasterizer = (svg: string, size: RasterSize) => Promise<Uint8Array>
const SVG_NS = 'http://www.w3.org/2000/svg'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+105 -25
View File
@@ -1,33 +1,97 @@
import type { Report } from '@faunosteo/core-wasm/types'
import {
defaultPdfLabels,
exportReportArchive,
type ExportInput,
type ExportWarning,
} from '@faunosteo/pdf'
openExportSession,
type CoreExportSession,
type CoreOutcome,
} from '@faunosteo/core-wasm'
import type {
ExportInput,
ExportWarning,
RasterRequest,
Report,
} from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadBranding } from './branding'
import { browserRasterizer } from './browserRasterizer'
import { defaultPdfLabels } from './labels'
export interface PdfExportOptions {
locale: Locale
/** Aborting frees the session (the editor leaving mid-export); no file results. */
signal?: AbortSignal
}
export interface PdfExportResult {
pdf: Uint8Array
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
/** The file, from the parts the core handed out (never concatenated in memory). */
pdf: Blob
/** Non-fatal warnings: a logo or a view that failed to embed. */
warnings: ExportWarning[]
}
/** A core call the export could not go past: its closed kind, for the DEV console. */
export class ExportFailure extends Error {
constructor(
public readonly kind: string,
detail?: string,
) {
super(detail ? `${kind}: ${detail}` : kind)
this.name = 'ExportFailure'
}
}
function unwrap<T>(outcome: CoreOutcome<T>): T {
if (!outcome.ok) throw new ExportFailure(outcome.kind, outcome.detail)
return outcome.value
}
function assertNotAborted(signal: AbortSignal | undefined): void {
if (signal?.aborted) throw new DOMException('export aborted', 'AbortError')
}
/**
* Exports the report as an archive PDF through the engine: the core builds
* the snapshot of the loaded sheet the pages are drawn from and the
* attachment carries (R2), the branding comes from the bundled logos, the
* browser rasterises the views, the TypeScript engine writes the file (the
* writer moves to the core at R4). The core's report and snapshot are the
* same JSON contracts the engine's Zod types describe. Warnings are logged
* and returned for the caller to surface.
* One batch of the session's requests rasterised under `Promise.all`, as the engine did:
* a raster that fails is reported as it rejects (the warning order the engine recorded),
* the others are given in request order once the batch has settled (the embedding order,
* so the file's bytes do not depend on which raster finished first). The PNG bytes are
* copied into the core and dropped as each `addRaster` returns.
*/
async function answerBatch(
session: CoreExportSession,
requests: RasterRequest[],
signal: AbortSignal | undefined,
): Promise<void> {
const settled = await Promise.all(
requests.map(async (request) => {
try {
const png = await browserRasterizer(request.svg, {
widthPx: request.widthPx,
heightPx: request.heightPx,
})
return { key: request.key, png }
} catch {
assertNotAborted(signal)
unwrap(session.rasterFailed(request.key))
return { key: request.key, png: null }
}
}),
)
for (const { key, png } of settled) {
if (!png) continue
assertNotAborted(signal)
unwrap(session.addRaster(key, png))
}
}
/**
* Exports the report as an archive PDF through the core's session (R4.6, plan §B.1.6):
* the core builds the snapshot of the loaded sheet the pages are drawn from and the
* attachment carries, the branding comes from the bundled logos, the labels from
* `labels.ts`, the export time from the clock; the core then asks for each raster it
* needs (the SVG logos, then the views of each observation), the browser draws it, and
* the core writes the file as the rasters arrive. The session is freed whatever happens.
* A refused input or a core failure throws (`ExportFailure`, or the `AbortError` of a
* cancelled export); warnings are returned for the caller to surface.
*/
export async function exportReportToPdf(
report: Report,
@@ -35,18 +99,34 @@ export async function exportReportToPdf(
opts: PdfExportOptions,
): Promise<PdfExportResult> {
const snapshot = index.ops.snapshot(report)
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
const result = await exportReportArchive({
report: report as ExportInput['report'],
sheet: snapshot.value as ExportInput['sheet'],
if (!snapshot.ok) throw new ExportFailure(snapshot.kind, snapshot.detail)
const input: ExportInput = {
report,
sheetSnapshot: snapshot.value,
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
rasterizer: browserRasterizer,
exportedAt: new Date(),
})
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
exportedAt: new Date().toISOString(),
}
assertNotAborted(opts.signal)
const session = unwrap(openExportSession(coreRuntime(), JSON.stringify(input)))
try {
for (;;) {
assertNotAborted(opts.signal)
const step = unwrap(session.next())
if (step.step === 'done') break
await answerBatch(session, step.requests, opts.signal)
}
const parts = unwrap(session.finish())
const warnings = unwrap(session.warnings())
for (const warning of warnings) {
console.warn('PDF export warning', warning)
}
return {
pdf: new Blob(parts as BlobPart[], { type: 'application/pdf' }),
warnings,
}
} finally {
session.free()
}
return { pdf: result.pdf, warnings: result.warnings }
}
+67
View File
@@ -0,0 +1,67 @@
import type { PdfLabelSet, PdfLabels } from '@faunosteo/core-wasm/types'
/**
* The static wording of the PDF (section headings, metadata), frozen into every archive
* the export writes (R4.6: moved verbatim from `packages/pdf/src/i18n`, same key order,
* which is the order every shipped attachment carries; the app dictionaries hold no
* `pdf.*` key). A wording change here changes new exports only: an old archive keeps the
* labels it was written with.
*/
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',
}
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',
}
export const defaultPdfLabels: PdfLabelSet = { fr, en }