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

52 lines
1.7 KiB
TypeScript

import { PDFDocument } from 'pdf-lib'
import {
readArchiveDocument,
UnsupportedReportVersionError,
type ArchiveReadOutcome,
type ReportMigrationMap,
} from '@faunosteo/domain'
import { readAttachedDocument } from './attachment/read'
import { ArchiveReadError } from './errors'
/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
export const MAX_PDF_BYTES = 50 * 1024 * 1024
async function loadPdf(pdfBytes: Uint8Array): Promise<PDFDocument> {
if (pdfBytes.byteLength > MAX_PDF_BYTES) {
throw new ArchiveReadError('invalid_pdf')
}
try {
return await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
} catch {
throw new ArchiveReadError('invalid_pdf')
}
}
/**
* Reads a Faunosteo PDF back: size cap, PDF parse, attachment (filename
* first), JSON, then the layered reading of the domain (report first, then
* the envelope accepted whole or dropped with a reason). An unknown report
* version is `incompatible_version` with that version; any other content
* failure is `no_attachment`, as today.
*/
export async function readReportArchive(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ArchiveReadOutcome> {
const pdfDoc = await loadPdf(pdfBytes)
const data = await readAttachedDocument(pdfDoc)
try {
return readArchiveDocument(data, map)
} catch (error) {
// A numeric but unknown version is an incompatible Faunosteo report; no
// version at all is not a Faunosteo attachment (today's message).
if (
error instanceof UnsupportedReportVersionError &&
error.foundVersion !== null
) {
throw new ArchiveReadError('incompatible_version', error.foundVersion)
}
throw new ArchiveReadError('no_attachment')
}
}