136 lines
4.4 KiB
TypeScript
136 lines
4.4 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] [--identity]
|
|
* [--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). Names are
|
|
* printed only with `--identity`. Reads only; never writes a 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 {
|
|
readReportDocument,
|
|
REPORT_VERSION,
|
|
UnsupportedReportVersionError,
|
|
} from '@faunosteo/domain'
|
|
import { readAttachedDocument } from '../src/pdf/attachment'
|
|
import { MAX_PDF_BYTES } from '../src/pdf/import'
|
|
import { parseBundledSheet } from '../src/sheets/provider'
|
|
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
|
|
import {
|
|
compareReport,
|
|
diffLines,
|
|
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: {},
|
|
}),
|
|
)
|
|
}
|
|
|
|
function expandFiles(args: string[]): string[] {
|
|
const out: string[] = []
|
|
for (const arg of args) {
|
|
const path = resolve(CWD, arg)
|
|
if (statSync(path).isDirectory()) {
|
|
const pdfs = readdirSync(path)
|
|
.filter((f) => f.toLowerCase().endsWith('.pdf'))
|
|
.sort()
|
|
out.push(...pdfs.map((f) => join(path, f)))
|
|
} else out.push(path)
|
|
}
|
|
return out
|
|
}
|
|
|
|
async function compareFile(
|
|
path: string,
|
|
sheet: SheetIndex,
|
|
args: CliArgs,
|
|
): Promise<Comparison> {
|
|
const bytes = new Uint8Array(readFileSync(path))
|
|
if (bytes.byteLength > MAX_PDF_BYTES) throw new Error('file too large')
|
|
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true })
|
|
const raw = await readAttachedDocument(pdf)
|
|
const version = (raw as { version: number }).version
|
|
try {
|
|
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
|
|
return compareReport(raw, outcome, version !== REPORT_VERSION, sheet, args)
|
|
} catch (err) {
|
|
if (err instanceof UnsupportedReportVersionError) {
|
|
throw new Error(`report version ${version} cannot be read`)
|
|
}
|
|
throw err
|
|
}
|
|
}
|
|
|
|
async function main(argv: string[]): Promise<number> {
|
|
const args = parseArgs(argv)
|
|
const files = expandFiles(args.files)
|
|
if (files.length === 0 || (args.diff && files.length !== 2)) {
|
|
console.error(
|
|
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--identity] [--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 = 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}: ${err instanceof Error ? err.message : 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(err instanceof Error ? err.message : err)
|
|
process.exit(1)
|
|
},
|
|
)
|