#!/usr/bin/env node // Compliance check for CI: validates every invoice in a folder with the official rules and // reports regressions against a baseline. Node 18+, no dependencies. // // node einv-ci.mjs [options] // --rules rule set to validate with (default: latest; pin e.g. 2026-11) // --baseline known results; only NEW failures fail the build // --update-baseline write the current results to the baseline file and pass // --compare-rules also validate with another rule set and report every file whose result changes // --report write all results as JSON // --summary write a Markdown summary (default: $GITHUB_STEP_SUMMARY when set) // --fail-on what counts as a failure (default: error) // // node einv-ci.mjs --test-set [--rules ] [--compare-rules ] [--report file] [--summary file] // runs a test set stored in your account (dashboard → Test sets, or POST /v1/test-sets): every // document is checked against its expected result and compared with the previous run // // Environment: EINV_KEY (a test key is enough), EINV_BASE (default https://einvoiceengine.com). // Exit code 1 when a file fails (or, with a baseline, when a file got worse), 2 on usage errors. import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { join, relative } from "node:path"; const args = process.argv.slice(2); const opt = (name, def) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : def; }; const flag = (name) => args.includes(`--${name}`); const folder = args[0] && !args[0].startsWith("--") ? args[0] : undefined; const base = (process.env.EINV_BASE ?? "https://einvoiceengine.com").replace(/\/$/, ""); const key = process.env.EINV_KEY; const rules = opt("rules", "latest"); const compareRules = opt("compare-rules"); const baselineFile = opt("baseline"); const failOn = opt("fail-on", "error"); const testSet = opt("test-set"); if ((testSet ? !/^[0-9a-f-]{36}$/i.test(testSet) : !folder || !existsSync(folder)) || !key) { console.error("usage: EINV_KEY=… node einv-ci.mjs [--rules 2026-11] [--baseline file] [--compare-rules latest] [--report file] [--summary file]"); console.error(" EINV_KEY=… node einv-ci.mjs --test-set [--rules 2026-11] [--compare-rules latest] [--report file] [--summary file]"); process.exit(2); } if (testSet) process.exit(await runTestSet(testSet)); /** Runs a stored test set on the server; the server keeps the expectations and the run history. */ async function runTestSet(id) { const headers = { authorization: `Bearer ${key}`, "content-type": "application/json" }; const idem = `einv-ci-${Date.now()}-${Math.random().toString(36).slice(2)}`; let run; for (let attempt = 0; ; attempt++) { const r = await fetch(`${base}/v1/test-sets/${id}/runs`, { method: "POST", headers: { ...headers, "idempotency-key": idem }, body: JSON.stringify({ rules, ...(compareRules ? { compareRules } : {}) }), }); if ((r.status === 429 || r.status >= 500) && attempt < 5) { await sleep(Number(r.headers.get("retry-after") ?? 2 ** attempt) * 1000); continue; } const j = await r.json().catch(() => ({})); if (!r.ok) { console.error(`error ${r.status} ${j.error?.code ?? ""}: ${j.error?.message ?? "request failed"}`); return 2; } run = j; break; } for (const d of run.results) { const tag = d.outcome === "failed" ? "FAIL" : d.outcome === "passed" ? "OK " : "NEW "; const extra = [d.missing.length ? `missing ${d.missing.join(",")}` : "", d.unexpected.length ? `unexpected ${d.unexpected.join(",")}` : "", d.diff.change !== "unchanged" ? d.diff.change.replace(/_/g, " ") : ""].filter(Boolean).join("; "); console.log(`${tag} ${d.actual.status}${d.actual.rules.length ? " " + d.actual.rules.join(",") : ""} ${d.filename}${extra ? ` (${extra})` : ""}`); } const s = run.summary; console.log(`${s.documents} documents, ${s.passed} passed, ${s.failed} failed${s.noExpectation ? `, ${s.noExpectation} without expectation` : ""}; since the previous run: ${s.diff.newFailures} with new failures, ${s.diff.fixed} fixed`); const mdRes = await fetch(`${base}/v1/test-sets/${id}/runs/${run.id}?format=markdown`, { headers }); const md = mdRes.ok ? await mdRes.text() : `### E-invoice test set: ${run.passed ? "passed" : "failed"} (run ${run.id})`; const summary = opt("summary", process.env.GITHUB_STEP_SUMMARY); if (summary) (opt("summary") ? writeFileSync : appendFileSync)(summary, md + "\n"); const report = opt("report"); if (report) writeFileSync(report, JSON.stringify(run, null, 2) + "\n"); return run.passed ? 0 : 1; } function files(dir) { return readdirSync(dir) .flatMap((f) => { const p = join(dir, f); return statSync(p).isDirectory() ? files(p) : /\.(xml|pdf)$/i.test(f) ? [p] : []; }) .sort(); } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); async function validate(path, ruleSet) { const body = readFileSync(path); for (let attempt = 0; ; attempt++) { const r = await fetch(`${base}/v1/invoices/validate?store=false&rules=${encodeURIComponent(ruleSet)}`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": /\.pdf$/i.test(path) ? "application/pdf" : "application/xml" }, body, }); if (r.status === 429 && attempt < 5) { await sleep(Number(r.headers.get("retry-after") ?? 2 ** attempt) * 1000); continue; } const j = await r.json().catch(() => ({})); if (j.error) return { status: "error", profile: "", errors: [`${j.error.code}`], warnings: [], message: j.error.message }; const ids = (sev) => [...new Set(j.findings.filter((f) => f.severity === sev).map((f) => f.ruleId + (f.location?.line ? `@${f.location.line}` : "")))]; return { status: j.status, profile: j.detected?.profile ?? j.detected?.format ?? "", errors: ids("error"), warnings: ids("warning"), ruleset: j.ruleset?.version }; } } async function all(list, ruleSet) { const out = {}; let next = 0; await Promise.all( Array.from({ length: Math.min(4, list.length) }, async () => { while (next < list.length) { const f = list[next++]; out[relative(folder, f)] = await validate(f, ruleSet); } }), ); return out; } const failing = (r) => r.status !== "valid" || (failOn === "warning" && r.warnings.length > 0); const ruleIds = (r) => new Set([...r.errors, ...(failOn === "warning" ? r.warnings : [])].map((x) => x.split("@")[0])); const list = files(folder); const results = await all(list, rules); const baseline = baselineFile && existsSync(baselineFile) && !flag("update-baseline") ? JSON.parse(readFileSync(baselineFile, "utf8")).results ?? {} : null; const regressions = []; for (const [file, r] of Object.entries(results)) { if (!failing(r)) continue; if (!baseline) regressions.push({ file, reason: r.errors.join(", ") || r.status }); else { const was = baseline[file]; const known = was ? ruleIds(was) : new Set(); const fresh = [...ruleIds(r)].filter((id) => !known.has(id)); if (!was || !failing(was) || fresh.length) regressions.push({ file, reason: was ? `new: ${fresh.join(", ") || r.status}` : `new file: ${r.errors.join(", ") || r.status}` }); } } const fixed = baseline ? Object.entries(baseline).filter(([f, was]) => failing(was) && results[f] && !failing(results[f])).map(([f]) => f) : []; let changes = []; if (compareRules) { const other = await all(list, compareRules); changes = Object.keys(results) .filter((f) => results[f].status !== other[f].status || results[f].errors.join() !== other[f].errors.join()) .map((f) => ({ file: f, [rules]: `${results[f].status} ${results[f].errors.join(", ")}`.trim(), [compareRules]: `${other[f].status} ${other[f].errors.join(", ")}`.trim() })); } for (const [file, r] of Object.entries(results)) console.log(`${failing(r) ? "FAIL" : "OK "} ${r.status} ${r.profile}${r.errors.length ? " " + r.errors.join(",") : ""} ${file}`); const nFail = Object.values(results).filter(failing).length; console.log(`${list.length} checked, ${nFail} failed${baseline ? `, ${regressions.length} new, ${fixed.length} fixed` : ""}`); for (const c of changes) console.log(`rule set ${rules} → ${compareRules}: ${c.file}: ${c[rules]} → ${c[compareRules]}`); const ruleset = Object.values(results).find((r) => r.ruleset)?.ruleset ?? rules; const md = [ `### E-invoice compliance: ${regressions.length ? "❌" : "✅"} ${list.length} checked, ${nFail} failing${baseline ? `, ${regressions.length} new, ${fixed.length} fixed` : ""}`, "", `Rule set: \`${ruleset}\`${baseline ? ` · baseline: \`${baselineFile}\`` : ""}`, "", ...(regressions.length ? ["| File | Problem |", "|---|---|", ...regressions.map((x) => `| \`${x.file}\` | ${x.reason} |`), ""] : []), ...(fixed.length ? [`Fixed since the baseline: ${fixed.map((f) => `\`${f}\``).join(", ")}`, ""] : []), ...(compareRules ? [`#### Rule set ${rules} → ${compareRules}`, "", changes.length ? ["| File | " + rules + " | " + compareRules + " |", "|---|---|---|", ...changes.map((c) => `| \`${c.file}\` | ${c[rules]} | ${c[compareRules]} |`)].join("\n") : "No file changes its result.", ""] : []), ].join("\n"); const summary = opt("summary", process.env.GITHUB_STEP_SUMMARY); if (summary) (opt("summary") ? writeFileSync : appendFileSync)(summary, md + "\n"); const report = opt("report"); if (report) writeFileSync(report, JSON.stringify({ rules: ruleset, checkedAt: new Date().toISOString(), results, regressions, fixed, ruleSetChanges: changes }, null, 2) + "\n"); if (flag("update-baseline") && baselineFile) { writeFileSync(baselineFile, JSON.stringify({ rules: ruleset, results }, null, 2) + "\n"); console.log(`baseline written: ${baselineFile}`); process.exit(0); } process.exit(regressions.length ? 1 : 0);