166 lines
5.6 KiB
TypeScript
166 lines
5.6 KiB
TypeScript
/**
|
|
* Archive check: reads the report attached to one or more Faunosteo PDFs and
|
|
* prints it next to its v3 reading on the bundled reference sheet.
|
|
*
|
|
* pnpm report:compare <file.pdf | folder>... [--summary] [--full]
|
|
* [--locale fr|en] [--diff a.pdf b.pdf]
|
|
*
|
|
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
|
|
* is checked against the sheet. Items the sheet cannot place are marked
|
|
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
|
|
* PDFs (an archive and its re-export after import, typically). By default
|
|
* only identifiers, catalog labels, counts and placeholders are printed and
|
|
* compared (a text shows as `conclusion (present)`); names and free texts,
|
|
* printed and compared, need `--full`.
|
|
* Untrusted strings are printed with control characters escaped. It writes
|
|
* no output file.
|
|
*/
|
|
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
import { basename, join, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { PDFDocument } from 'pdf-lib'
|
|
import {
|
|
readArchiveDocument,
|
|
UnsupportedReportVersionError,
|
|
} from '@faunosteo/domain'
|
|
import {
|
|
ArchiveReadError,
|
|
MAX_PDF_BYTES,
|
|
readAttachedDocument,
|
|
} from '@faunosteo/pdf'
|
|
import { parseBundledSheet } from '../src/sheets/provider'
|
|
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
|
|
import {
|
|
compareReport,
|
|
diffLines,
|
|
esc,
|
|
parseArgs,
|
|
renderComparison,
|
|
renderSummary,
|
|
type CliArgs,
|
|
type Comparison,
|
|
} from './compare/report'
|
|
|
|
const SEED_DIR = resolve(
|
|
fileURLToPath(import.meta.url),
|
|
'../../../../supabase/seed/anatomical-sheets/equine/draft',
|
|
)
|
|
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
|
|
const CWD = process.env.INIT_CWD ?? process.cwd()
|
|
|
|
function loadSheet(): SheetIndex {
|
|
const json = (name: string) =>
|
|
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
|
|
// The comparison needs the document and the map, not the drawings.
|
|
return buildSheetIndex(
|
|
parseBundledSheet({
|
|
status: 'draft',
|
|
ref: json('sheet-ref.json'),
|
|
document: json('document.json'),
|
|
migrationMap: json('report-migration-map.json'),
|
|
assets: {},
|
|
assetHashes: {},
|
|
}),
|
|
)
|
|
}
|
|
|
|
/** A folder stands for its PDFs; any other argument stays one entry. */
|
|
function expandArg(arg: string): string[] {
|
|
const path = resolve(CWD, arg)
|
|
try {
|
|
if (!statSync(path).isDirectory()) return [path]
|
|
} catch {
|
|
return [path] // reported as a failed entry by compareFile
|
|
}
|
|
return readdirSync(path)
|
|
.filter((f) => f.toLowerCase().endsWith('.pdf'))
|
|
.sort()
|
|
.map((f) => join(path, f))
|
|
}
|
|
|
|
async function compareFile(
|
|
path: string,
|
|
sheet: SheetIndex,
|
|
args: CliArgs,
|
|
): Promise<Comparison> {
|
|
const st = statSync(path)
|
|
if (!st.isFile()) throw new Error('not a regular file')
|
|
if (st.size > MAX_PDF_BYTES) throw new Error('file too large')
|
|
const bytes = new Uint8Array(readFileSync(path))
|
|
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true })
|
|
const raw = await readAttachedDocument(pdf)
|
|
try {
|
|
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
|
|
return compareReport(raw, outcome, sheet, args)
|
|
} catch (err) {
|
|
if (err instanceof UnsupportedReportVersionError) {
|
|
// The version is a number or null: nothing of the attachment is echoed.
|
|
throw new Error(`report version ${err.foundVersion} cannot be read`)
|
|
}
|
|
throw err
|
|
}
|
|
}
|
|
|
|
/** The engine's typed read failures, worded without echoing the file. */
|
|
const READ_FAILURES: Record<ArchiveReadError['kind'], string> = {
|
|
invalid_pdf: 'not a readable PDF',
|
|
no_attachment: 'no Faunosteo attachment found',
|
|
attachment_stripped:
|
|
'attachment stripped (the PDF is stamped as a Faunosteo archive)',
|
|
incompatible_version: 'report version cannot be read',
|
|
}
|
|
|
|
/** A missing or unreadable file is a failed entry, not a crash. */
|
|
function failureReason(err: unknown): string {
|
|
const code = (err as NodeJS.ErrnoException | undefined)?.code
|
|
if (code === 'ENOENT') return 'file not found'
|
|
if (code === 'EACCES') return 'file not readable'
|
|
if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind]
|
|
// JSON.parse messages echo a fragment of the attachment.
|
|
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
|
|
return err instanceof Error ? err.message : String(err)
|
|
}
|
|
|
|
async function main(argv: string[]): Promise<number> {
|
|
const args = parseArgs(argv)
|
|
const files = args.files.flatMap(expandArg)
|
|
if (files.length === 0 || (args.diff && files.length !== 2)) {
|
|
console.error(
|
|
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]',
|
|
)
|
|
return 1
|
|
}
|
|
const sheet = loadSheet()
|
|
const results: Comparison[] = []
|
|
let failures = 0
|
|
for (const file of files) {
|
|
const name = esc(basename(file))
|
|
try {
|
|
const c = await compareFile(file, sheet, args)
|
|
results.push(c)
|
|
if (!args.diff) {
|
|
const lines = args.summary
|
|
? [renderSummary(name, c)]
|
|
: [...renderComparison(name, c), '']
|
|
console.log(lines.join('\n'))
|
|
}
|
|
} catch (err) {
|
|
failures += 1
|
|
console.log(`!! ${name}: ${esc(failureReason(err))}`)
|
|
}
|
|
}
|
|
if (args.diff && results.length === 2) {
|
|
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
|
|
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
|
|
}
|
|
return failures ? 2 : 0
|
|
}
|
|
|
|
main(process.argv.slice(2)).then(
|
|
(code) => process.exit(code),
|
|
(err) => {
|
|
console.error(esc(err instanceof Error ? err.message : String(err)))
|
|
process.exit(1)
|
|
},
|
|
)
|