From fb7948307cf8e9ee4dfab2d170c980ca2833c247 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 12 Oct 2026 14:02:44 +0800 Subject: [PATCH] Remove Python from report validation and rendering --- bun.lock | 6 + package.json | 2 + report-templates/README.md | 5 +- report-templates/report.css | 33 +++++ skills/seal-use/SKILL.md | 2 +- src/cli/commands/report.ts | 6 +- src/cli/help.ts | 7 +- src/cli/parser.ts | 5 +- src/declarations.d.ts | 2 +- src/domains/seal/reports/browser.ts | 138 +++++++++++++++++ src/domains/seal/reports/files.test.ts | 34 ++++- src/domains/seal/reports/files.ts | 113 ++++++-------- src/domains/seal/reports/html.test.ts | 61 ++++++++ src/domains/seal/reports/html.ts | 97 ++++++++++++ src/domains/seal/reports/png.test.ts | 48 ++++++ src/domains/seal/reports/png.ts | 31 ++++ src/domains/seal/reports/resources.ts | 5 +- src/domains/seal/reports/validate.test.ts | 66 +++++++++ src/domains/seal/reports/validate.ts | 172 ++++++++++++++++++++++ 19 files changed, 743 insertions(+), 90 deletions(-) create mode 100644 report-templates/report.css create mode 100644 src/domains/seal/reports/browser.ts create mode 100644 src/domains/seal/reports/html.test.ts create mode 100644 src/domains/seal/reports/html.ts create mode 100644 src/domains/seal/reports/png.test.ts create mode 100644 src/domains/seal/reports/png.ts create mode 100644 src/domains/seal/reports/validate.test.ts create mode 100644 src/domains/seal/reports/validate.ts diff --git a/bun.lock b/bun.lock index 94908f4..416cdcb 100644 --- a/bun.lock +++ b/bun.lock @@ -11,6 +11,7 @@ "ky": "^2.0.2", "marked": "15.0.12", "pinyin-pro": "^3.29.3", + "pngjs": "7.0.0", "yauzl": "^3.4.0", "zod": "^4.4.3", }, @@ -18,6 +19,7 @@ "@modelcontextprotocol/client": "^2.0.0", "@types/archiver": "^8.0.0", "@types/bun": "^1.3.14", + "@types/pngjs": "6.0.5", "@types/yauzl": "^3.4.0", "bun-types": "^1.3.14", "oxlint": "1.86.0", @@ -81,6 +83,8 @@ "@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="], + "@types/pngjs": ["@types/pngjs@6.0.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="], + "@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="], "@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="], @@ -253,6 +257,8 @@ "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], + "pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="], + "process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="], "process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="], diff --git a/package.json b/package.json index 0f0da6b..c12cdfb 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "ky": "^2.0.2", "marked": "15.0.12", "pinyin-pro": "^3.29.3", + "pngjs": "7.0.0", "yauzl": "^3.4.0", "zod": "^4.4.3" }, @@ -52,6 +53,7 @@ "@modelcontextprotocol/client": "^2.0.0", "@types/archiver": "^8.0.0", "@types/bun": "^1.3.14", + "@types/pngjs": "6.0.5", "@types/yauzl": "^3.4.0", "bun-types": "^1.3.14", "oxlint": "1.86.0", diff --git a/report-templates/README.md b/report-templates/README.md index 2ca8587..2eac489 100644 --- a/report-templates/README.md +++ b/report-templates/README.md @@ -7,7 +7,8 @@ | `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 | | `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 | | `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) | -| `validate.py` / `render.py` | 结构校验 + HTML/PNG/PDF 渲染引擎,随 CLI 内嵌,由 `report validate` / `report render` 调用;也保留独立 Python 入口 | +| `report.css` | HTML、长图和 A4 PDF 共用的版式,随 CLI 内嵌 | +| `validate.py` / `render.py` | 历史独立工具,保留作迁移对照;CLI 已使用 `src/domains/seal/reports/` 下的 TypeScript 校验和渲染模块,不再内嵌或调用这两个脚本 | 模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。 @@ -23,6 +24,6 @@ seal-use report render reports/报告.md --out build/报告 校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。 -运行环境:校验和渲染需要 Python 3;PNG/PDF 需要 Chrome/Chromium,PNG 还需要该 Python 环境中的 Pillow。可通过 `--python`、`--chrome` 指定可执行文件。自动发现优先使用 PATH 或 Playwright 缓存中已有的 `chrome-headless-shell`,再查普通 Chrome/Chromium;不自动安装浏览器。CLI 自带 Markdown 解析器,不再运行 `npx`。含公式的报告首次渲染需联网下载 KaTeX 0.16.11 到 `~/.cache/seal-use/report-render/`,之后复用缓存;可用 `SEAL_REPORT_CACHE_DIR` 指定缓存目录。 +运行环境:生成月报、校验和 HTML 导出使用 CLI 自带运行时;PNG/PDF 另需 Chrome/Chromium,可用 `--chrome` 指定。长 PNG 拼接由随二进制打包的 JavaScript 库完成,无需 Python、Pillow、Node 或 npm。`--python` 已移除,传入时返回用法错误(退出码 2)。自动发现优先使用 PATH 或 Playwright 缓存中已有的 `chrome-headless-shell`,再查普通 Chrome/Chromium;不自动安装浏览器。CLI 自带 Markdown 解析器,不运行 `npx`。含公式的报告首次渲染需联网下载 KaTeX 0.16.11 到 `~/.cache/seal-use/report-render/`,之后复用缓存;可用 `SEAL_REPORT_CACHE_DIR` 指定缓存目录。 配图仍是模板示例/占位图,当前不会按当月数据自动重绘;对外使用前需替换。结构与数值校验通过也不代表示例值或人工裁决已经完备,应同时检查月报返回的 `notes`。 diff --git a/report-templates/report.css b/report-templates/report.css new file mode 100644 index 0000000..7426ca0 --- /dev/null +++ b/report-templates/report.css @@ -0,0 +1,33 @@ +:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; } +* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; } +body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg); + font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif; + -webkit-font-smoothing:antialiased; } +h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); } +h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); } +h3 { font-size:18px; margin:28px 0 12px; } +h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); } +p, li { margin:10px 0; } +blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head); + color:#33404d; border-radius:0 6px 6px 0; } +blockquote p { margin:6px 0; } +code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px; + font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; } +pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; } +pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; } +table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; } +th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; } +th { background:var(--head); font-weight:600; } +tr:nth-child(even) td { background:#fbfcfd; } +img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; } +em { color:var(--muted); font-size:14px; } +hr { border:0; border-top:1px solid var(--line); margin:32px 0; } +a { color:#0969da; } +.katex-display { margin:18px 0; } +@page { size: A4; margin: 14mm 12mm; } +@media print { + body { max-width:none; padding:0; font-size:12pt; } + h2, h3 { page-break-after:avoid; break-after:avoid; } + tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; } + thead { display:table-header-group; } +} diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 646f116..b7376b0 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -142,7 +142,7 @@ seal-use report render reports/报告.md --out build/报告 - **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。 - 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。 - 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。 -- 本地运行环境:Python 3;PNG/PDF 另需 Chrome/Chromium,PNG 需 Pillow(可用 `--python` / `--chrome` 指定环境)。Markdown 解析已打包,不需 npm/npx;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。 +- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。 - 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。 ### 人工裁决回填(算出人工审核准确率) diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 9968642..0604ff6 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -13,9 +13,9 @@ import type { ParsedArgs } from "../types.js"; export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) { const file = args.command[2] ?? stringOption(args.options.file); if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`); - const python = stringOption(args.options.python); + if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。"); if (action === "validate") { - const result = await validateReportFile(file, { python }); + const result = await validateReportFile(file); printJson(result, outputOptions(args.options)); if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1); return; @@ -23,7 +23,7 @@ export async function handleLocalReportCommand(action: "validate" | "render", ar const out = stringOption(args.options.out) ?? stringOption(args.options.o); if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>"); const result = await renderReportFile(file, { - out, python, format: stringOption(args.options.format), width: numberOption(args.options.width), + out, format: stringOption(args.options.format), width: numberOption(args.options.width), chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite) }); printJson(result, outputOptions(args.options)); diff --git a/src/cli/help.ts b/src/cli/help.ts index fbe544c..4ee02f0 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -631,8 +631,8 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "validate", summary: "Check a local report's structure, images, totals, and formulas", - usage: ["seal-use report validate <报告.md> [--python ]"], - options: [{ flag: "--python ", description: "Python 3 executable; defaults to python3 on PATH" }], + usage: ["seal-use report validate <报告.md>"], + options: [], description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails." }, { @@ -643,11 +643,10 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--out ", description: "Output filename stem; extensions are appended" }, { flag: "--format ", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" }, { flag: "--width ", description: "PNG viewport width, default 1200 (320–5000)" }, - { flag: "--python ", description: "Python 3 executable; defaults to python3 on PATH" }, { flag: "--chrome ", description: "Chrome/Chromium executable; otherwise auto-detected" }, { flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" } ], - description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Requires Python 3; PNG/PDF also need Chrome/Chromium, PNG needs Pillow. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency." + description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency." }, { name: "review set", diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 6ee17f3..4530901 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -61,7 +61,7 @@ export const VALUE_FLAGS = new Set([ "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "p", "package-id", "package-ids", "packageId", "packageIds", "path", "phone", "policyId", "poll-interval", "pollInterval", "port", - "prod", "prod-corp", "prodCorp", "purpose", "python", "q", "query", + "prod", "prod-corp", "prodCorp", "purpose", "q", "query", "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "reviewed-by", "reviewedBy", "report-id", @@ -115,7 +115,7 @@ export const KNOWN_FLAGS = new Set([ "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite", "p", "package-id", "package-ids", "packageId", "packageIds", "path", "phone", "plain", "policyId", "poll-interval", "pollInterval", "port", - "prod", "prod-corp", "prodCorp", "publish", "purpose", "python", "q", + "prod", "prod-corp", "prodCorp", "publish", "purpose", "q", "query", "quiet", "r", "recode", "record-id", "record-ids", "recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo", "report-id", @@ -169,6 +169,7 @@ export function parseArgs(argv: string[]): ParsedArgs { const eqIdx = raw.indexOf("="); const key = raw.slice(0, eqIdx); const val = raw.slice(eqIdx + 1); + if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。"); options[key] = val; continue; } diff --git a/src/declarations.d.ts b/src/declarations.d.ts index 2e5e1dd..6a83de0 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -13,7 +13,7 @@ declare module "*.yml" { export default content; } -declare module "*.py" { +declare module "*.css" { const content: string; export default content; } diff --git a/src/domains/seal/reports/browser.ts b/src/domains/seal/reports/browser.ts new file mode 100644 index 0000000..5d07905 --- /dev/null +++ b/src/domains/seal/reports/browser.ts @@ -0,0 +1,138 @@ +import { spawn } from "node:child_process" +import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { dirname, join } from "node:path" +import { pathToFileURL } from "node:url" +import { CliError, validationError } from "../../../core/errors.js" +import { pngDimensions, stitchPngBands, type PngBand } from "./png.js" + +export const PNG_BAND_HEIGHT = 14_000 + +function executable(path: string | null | undefined): path is string { + if (!path) return false + try { accessSync(path, constants.X_OK); return statSync(path).isFile() } catch { return false } +} + +function cachedHeadlessShells(): string[] { + const roots = [join(homedir(), "Library", "Caches", "ms-playwright"), join(homedir(), ".cache", "ms-playwright")] + if (process.env.LOCALAPPDATA) roots.push(join(process.env.LOCALAPPDATA, "ms-playwright")) + const candidates: string[] = [] + for (const root of roots) { + if (!existsSync(root)) continue + for (const version of readdirSync(root, { withFileTypes: true })) { + if (!version.isDirectory() || !version.name.startsWith("chromium_headless_shell-")) continue + const versionRoot = join(root, version.name) + for (const platform of readdirSync(versionRoot, { withFileTypes: true })) { + if (!platform.isDirectory() || !platform.name.startsWith("chrome-headless-shell-")) continue + for (const name of ["chrome-headless-shell", "chrome-headless-shell.exe"]) { + const path = join(versionRoot, platform.name, name) + if (executable(path)) candidates.push(path) + } + } + } + } + return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs) +} + +/** Dedicated headless shells avoid desktop Chrome startup/shutdown problems on headless hosts. */ +export function findReportChrome(explicit?: string): string { + if (explicit) { + const path = Bun.which(explicit) ?? explicit + if (executable(path)) return path + throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定") + } + const candidates = [ + Bun.which("chrome-headless-shell"), ...cachedHeadlessShells(), + ...["google-chrome", "chromium", "chromium-browser", "chrome", "msedge"].map((name) => Bun.which(name)), + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application", "chrome.exe"), + join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe") + ] + const path = candidates.find(executable) + if (!path) throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定") + return path +} + +function chrome(binary: string, profile: string, args: string[]): Promise { + return new Promise((resolve, reject) => { + const child = spawn(binary, [ + "--headless", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${profile}`, + "--no-first-run", "--no-default-browser-check", "--force-device-scale-factor=1", + "--run-all-compositor-stages-before-draw", ...args + ], { stdio: ["ignore", "pipe", "pipe"] }) + let title = "", tail = "", diagnostic = "", settled = false + const finish = (error?: Error) => { + if (settled) return + settled = true + clearTimeout(timeout) + if (error) reject(error); else resolve(title) + } + const timeout = setTimeout(() => { + child.kill("SIGKILL") + finish(new CliError("浏览器渲染超时。可通过 --chrome 指定可用的 Chrome/Chromium 或 chrome-headless-shell。", 1)) + }, 60_000) + // dump-dom contains embedded images and can be very large. Retain only the measured title, + // including cross-chunk matches, rather than imposing a new buffer limit on report size. + child.stdout?.on("data", (chunk: Buffer) => { + if (!args.includes("--dump-dom")) return + const text = tail + chunk.toString() + for (const match of text.matchAll(/PAGEH:(\d+)<\/title>/g)) title = `PAGEH:${match[1]}` + tail = text.slice(-256) + }) + child.stderr?.on("data", (chunk: Buffer) => { diagnostic = (diagnostic + chunk.toString()).slice(-65_536) }) + child.once("error", (error) => finish(new CliError(`报告浏览器执行失败:${error.message}`, 1))) + child.once("close", (code, signal) => finish(code === 0 ? undefined : new CliError(`报告浏览器执行失败:${diagnostic.trim() || `退出 ${code ?? signal}`}`, 1))) + }) +} + +/** 注入测量脚本,用 dump-dom 取文档真实高度,等待图片和公式字体加载。 */ +async function measureHeight(html: string, width: number, binary: string, profile: string): Promise<number> { + const probe = join(dirname(html), "_measure.html") + const script = '<script>async function measureReport(){await document.fonts.ready;document.title="PAGEH:"+Math.ceil(document.documentElement.scrollHeight)}window.addEventListener("load",measureReport);setTimeout(measureReport,3000)</script>' + writeFileSync(probe, readFileSync(html, "utf8").replace("</body>", script + "</body>")) + const output = await chrome(binary, profile, [`--window-size=${width},1000`, "--virtual-time-budget=30000", "--dump-dom", pathToFileURL(probe).href]) + const hits = [...output.matchAll(/PAGEH:(\d+)/g)] + const height = Number(hits.at(-1)?.[1]) + if (!Number.isSafeInteger(height) || height <= 0) throw new CliError("量取页面高度失败,未生成 PNG。", 1) + return height +} + +/** 位移样式放在所有样式之后,避免长图分带重复开头或丢失结尾。 */ +export function offsetReportBand(html: string, offset: number): string { + return html.replace("</head>", `<style>body{margin-top:-${offset}px}</style></head>`) +} + +async function renderPng(html: string, output: string, width: number, binary: string, profile: string) { + const height = await measureHeight(html, width, binary, profile) + const screenshot = async (source: string, destination: string, bandHeight: number) => { + await chrome(binary, profile, [`--screenshot=${destination}`, `--window-size=${width},${bandHeight}`, "--virtual-time-budget=30000", pathToFileURL(source).href]) + const dimensions = pngDimensions(destination) + if (dimensions.width !== width || dimensions.height !== bandHeight) throw new CliError("浏览器截图尺寸与请求不一致,未发布 PNG。", 1) + } + if (height <= PNG_BAND_HEIGHT) { + await screenshot(html, output, height) + return + } + const bands: PngBand[] = [] + const content = readFileSync(html, "utf8") + for (let offset = 0; offset < height; offset += PNG_BAND_HEIGHT) { + const bandHeight = Math.min(PNG_BAND_HEIGHT, height - offset) + const source = join(dirname(html), `_band${bands.length}.html`) + const file = join(dirname(html), `_band${bands.length}.png`) + writeFileSync(source, offsetReportBand(content, offset)) + await screenshot(source, file, bandHeight) + bands.push({ file, height: bandHeight }) + } + stitchPngBands(bands, width, height, output) +} + +/** PNG 为完整长图;PDF 使用 Chrome 的 A4 打印管线,保留表头重复和行不跨页样式。 */ +export async function renderBrowserArtifacts(html: string, formats: string[], width: number, binary: string, profile: string) { + const stem = html.slice(0, -".html".length) + if (formats.includes("png")) await renderPng(html, `${stem}.png`, width, binary, profile) + if (formats.includes("pdf")) { + await chrome(binary, profile, [`--print-to-pdf=${stem}.pdf`, "--no-pdf-header-footer", "--virtual-time-budget=30000", pathToFileURL(html).href]) + if (!existsSync(`${stem}.pdf`) || statSync(`${stem}.pdf`).size === 0) throw new CliError("浏览器未生成 PDF 文件。", 1) + } +} diff --git a/src/domains/seal/reports/files.test.ts b/src/domains/seal/reports/files.test.ts index 8fdf983..d6ff4f5 100644 --- a/src/domains/seal/reports/files.test.ts +++ b/src/domains/seal/reports/files.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { PNG } from "pngjs"; import { runCli } from "../../../cli/runner.js"; import { buildMonthlyReport } from "./monthly.js"; import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js"; @@ -108,7 +109,7 @@ describe("local report CLI", () => { expect(JSON.parse(bad.stdout)).toMatchObject({ valid: false, issues: expect.arrayContaining([expect.objectContaining({ code: "IMG001" })]) }); }); - test("renders self-contained HTML without Chrome, npm, or Seal credentials", async () => { + test("renders self-contained HTML without Python, Chrome, npm, or Seal credentials", async () => { const dir = workspace(); writeFileSync(join(dir, "image.svg"), '<svg xmlns="http://www.w3.org/2000/svg"><text>hello</text></svg>'); const file = localReport(dir, validReport + "\n![image](image.svg)\n"); @@ -137,7 +138,9 @@ describe("local report CLI", () => { const file = localReport(dir); const cases: Array<[string[], number]> = [ [["report", "validate", join(dir, "absent.md")], 13], - [["report", "validate", file, "--python", join(dir, "absent-python")], 13], + [["report", "validate", file, "--python", join(dir, "absent-python")], 2], + [["report", "render", file, "--out", join(dir, "out"), "--python=python3"], 2], + [["report", "monthly", "--month", "2026-08", "--python=python3"], 2], [["report", "render", file], 2], [["report", "render", file, "--out", join(dir, "out"), "--format", "docx"], 2], [["report", "render", file, "--out", join(dir, "out"), "--width", "10"], 2] @@ -155,4 +158,31 @@ describe("local report CLI", () => { expect(readFileSync(out + ".html", "utf8")).toBe("existing html"); expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf"); }); + + test("browser failure after HTML generation preserves outputs and keeps child logs out of stdout", async () => { + const dir = workspace(); + const file = localReport(dir), out = join(dir, "result"); + const chrome = join(dir, "fake chrome"); + writeFileSync(chrome, "#!/bin/sh\nprintf 'browser fixture failed\\n' >&2\nexit 1\n", { mode: 0o755 }); + writeFileSync(out + ".html", "existing html"); + writeFileSync(out + ".pdf", "existing pdf"); + const result = await runCli(["report", "render", file, "--out", out, "--format", "pdf", "--chrome", chrome, "--overwrite"]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("browser fixture failed"); + expect(readFileSync(out + ".html", "utf8")).toBe("existing html"); + expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf"); + }); + + test("large browser DOM output and split measurement tags do not impose an export buffer limit", async () => { + const dir = workspace(), file = localReport(dir), out = join(dir, "large"); + const screenshot = new PNG({ width: 320, height: 2000 }); + screenshot.data.fill(255); + const fixture = join(dir, "fixture.png"), chrome = join(dir, "fake chrome"); + writeFileSync(fixture, PNG.sync.write(screenshot)); + writeFileSync(chrome, `#!${process.execPath}\nimport {copyFileSync} from "node:fs";\nconst args=process.argv.slice(2);\nif(args.includes("--dump-dom")){process.stdout.write(Buffer.alloc(17*1024*1024,120));process.stdout.write("<tit");process.stdout.write("le>PAGEH:2000")}\nelse{const target=args.find(arg=>arg.startsWith("--screenshot="));if(!target)process.exit(1);copyFileSync(${JSON.stringify(fixture)},target.slice("--screenshot=".length))}\n`, { mode: 0o755 }); + const result = await renderReportFile(file, { out, format: "png", width: 320, chrome }); + expect(result.artifacts.map((artifact) => artifact.format)).toEqual(["html", "png"]); + expect(existsSync(out + ".png")).toBe(true); + }); }); diff --git a/src/domains/seal/reports/files.ts b/src/domains/seal/reports/files.ts index 418d8d1..c8e00a0 100644 --- a/src/domains/seal/reports/files.ts +++ b/src/domains/seal/reports/files.ts @@ -1,21 +1,14 @@ import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { execFile } from "node:child_process"; -import { tmpdir } from "node:os"; -import { basename, dirname, extname, join, resolve } from "node:path"; -import { promisify } from "node:util"; -import { marked } from "marked"; -import { z } from "zod"; -import { CliError, usageError, validationError } from "../../../core/errors.js"; -import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS, REPORT_SCRIPTS } from "./resources.js"; +import { tmpdir } from "node:os" +import { basename, dirname, extname, join, resolve } from "node:path" +import { CliError, usageError, validationError } from "../../../core/errors.js" +import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS } from "./resources.js" +import { validateReportDocument, type ReportValidation } from "./validate.js" +import { buildReportHtml } from "./html.js" +import { findReportChrome, renderBrowserArtifacts } from "./browser.js" -const execute = promisify(execFile); -const validationSchema = z.object({ - file: z.string(), valid: z.boolean(), tables: z.number(), figures: z.number(), - issues: z.array(z.object({ level: z.enum(["ERROR", "WARN"]), code: z.string(), message: z.string() })) -}); -export type ReportValidation = z.infer; -type LocalToolOptions = { python?: string }; -export type ReportRenderOptions = LocalToolOptions & { +export type { ReportValidation } from "./validate.js" +export type ReportRenderOptions = { out: string; format?: string; width?: number; @@ -63,45 +56,12 @@ export function saveReportMarkdown(content: string, templatePath: string, output return { file, assets: [...files.keys()].filter((path) => path !== file) }; } -async function withTools(options: LocalToolOptions, operation: (dir: string, python: string) => Promise): Promise { - const python = Bun.which(options.python ?? "python3"); - if (!python) throw validationError("报告工具需要 Python 3。请安装 Python 3,或通过 --python <可执行文件> 指定。"); - const dir = mkdtempSync(join(tmpdir(), "seal-report-tools-")); - try { - for (const [name, content] of Object.entries(REPORT_SCRIPTS)) writeFileSync(join(dir, name), content); - return await operation(dir, python); - } finally { - rmSync(dir, { recursive: true, force: true }); - } +/** Local validation deliberately needs no tenant selection, token, HTTP client or external interpreter. */ +export async function validateReportFile(file: string): Promise { + return validateReportDocument(inputFile(file)) } -async function runTool(python: string, args: string[], allowInvalid = false): Promise { - let stdout: string; - try { - stdout = (await execute(python, args, { encoding: "utf8", timeout: 600_000, maxBuffer: 16 * 1024 * 1024 })).stdout; - } catch (error) { - const failure = error as { code?: number; stdout?: string; stderr?: string; message?: string }; - if (allowInvalid && failure.code === 1 && failure.stdout?.trim()) stdout = failure.stdout; - else { - const message = failure.stderr?.trim() || failure.message || String(error); - if (/^(?:未找到 Chrome\/Chromium|PNG 导出需要 Pillow)/.test(message)) throw validationError(message); - throw new CliError(`报告工具执行失败:${message}`, 1); - } - } - return JSON.parse(stdout); -} - -async function validateWithTools(file: string, dir: string, python: string): Promise { - return z.array(validationSchema).length(1).parse(await runTool(python, [join(dir, "validate.py"), "--json", file], true))[0]!; -} - -/** Local validation deliberately needs no tenant selection, token, or HTTP client. */ -export async function validateReportFile(file: string, options: LocalToolOptions = {}): Promise { - const path = inputFile(file); - return withTools(options, (dir, python) => validateWithTools(path, dir, python)); -} - -/** Preserve the existing Python layout engine while bundling Markdown parsing and returning clean JSON. */ +/** Render through bundled TypeScript modules and the existing browser, returning clean JSON. */ export async function renderReportFile(file: string, options: ReportRenderOptions) { const path = inputFile(file); const format = options.format ?? "all"; @@ -113,24 +73,33 @@ export async function renderReportFile(file: string, options: ReportRenderOption const destinations = formats.map((extension) => `${stem}.${extension}`); if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。"); for (const destination of destinations) checkOutput(destination, options.overwrite); - return withTools(options, async (dir, python) => { - const validation = await validateWithTools(path, dir, python); - if (!validation.valid) return { file: path, validation, artifacts: [] }; - // The same pinned marked major as the original renderer, embedded in the CLI instead of downloaded by npx. - const bodyFile = join(dir, "body.html"); - writeFileSync(bodyFile, marked.parse(readFileSync(path, "utf8"), { async: false })); - const args = [join(dir, "render.py"), path, "--out", join(dir, "report"), "--body-file", bodyFile, - "--format", format, "--width", String(width), "--json"]; - if (options.chrome) args.push("--chrome", options.chrome); - const rendered = z.object({ artifacts: z.array(z.object({ path: z.string(), format: z.string(), bytes: z.number().positive() })) }) - .parse(await runTool(python, args)); + const validation = await validateReportFile(path) + if (!validation.valid) return { file: path, validation, artifacts: [] } + const binary = formats.length > 1 ? findReportChrome(options.chrome) : undefined + const stage = mkdtempSync(join(tmpdir(), "seal-report-render-")) + try { + const html = join(stage, "report.html") + writeFileSync(html, await buildReportHtml(path)) + if (binary) { + const profile = join(stage, "browser-profile") + mkdirSync(profile, { mode: 0o700 }) + await renderBrowserArtifacts(html, formats, width, binary, profile) + } + const rendered = formats.map((format) => { + const file = join(stage, `report.${format}`) + const bytes = statSync(file).size + if (!bytes) throw new CliError(`报告渲染产物为空:${format}`, 1) + return { file, format, bytes } + }) // Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact. - mkdirSync(dirname(stem), { recursive: true }); - const artifacts = rendered.artifacts.map((artifact) => { - const destination = `${stem}.${artifact.format}`; - copyFileSync(artifact.path, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL); - return { ...artifact, path: destination }; - }); - return { file: path, validation, artifacts }; - }); + mkdirSync(dirname(stem), { recursive: true }) + const artifacts = rendered.map((artifact) => { + const destination = `${stem}.${artifact.format}` + copyFileSync(artifact.file, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL) + return { path: destination, format: artifact.format, bytes: artifact.bytes } + }) + return { file: path, validation, artifacts } + } finally { + rmSync(stage, { recursive: true, force: true }) + } } diff --git a/src/domains/seal/reports/html.test.ts b/src/domains/seal/reports/html.test.ts new file mode 100644 index 0000000..5cf37d8 --- /dev/null +++ b/src/domains/seal/reports/html.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { dirname, join } from "node:path" +import { buildReportHtml } from "./html.js" + +const dirs: string[] = [] +const originalFetch = globalThis.fetch +const originalCache = process.env.SEAL_REPORT_CACHE_DIR +afterEach(() => { + globalThis.fetch = originalFetch + if (originalCache === undefined) delete process.env.SEAL_REPORT_CACHE_DIR; else process.env.SEAL_REPORT_CACHE_DIR = originalCache + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) +}) +function source(content: string) { + const dir = mkdtempSync(join(tmpdir(), "seal-html-test-")) + dirs.push(dir) + process.env.SEAL_REPORT_CACHE_DIR = join(dir, "cache") + const file = join(dir, "报告.md") + writeFileSync(file, content) + return file +} + +describe("native report HTML", () => { + test("preserves code escaping and leaves code examples and escaped dollars out of math rendering", async () => { + globalThis.fetch = Object.assign(async () => { throw new Error("must not fetch") }, { preconnect: originalFetch.preconnect }) + const html = await buildReportHtml(source('# Title\n\n```text\n\n$example$\n```\n\n\\$5\n')) + expect(html).toContain("<img") + expect(html).toContain("$example$") + expect(html).not.toContain("renderMathInElement") + }) + test("embeds math resources and fonts, and reuses the existing cache layout offline", async () => { + const calls: string[] = [] + globalThis.fetch = Object.assign(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + return new Response(url.endsWith("katex.min.css") ? ".katex{src:url(fonts/Mock.woff2)}" : "fixture") + }, { preconnect: originalFetch.preconnect }) + const file = source("# Math\n\n$a_b < c$\n\n$$\\frac{100}{100} = 100\\%$$\n") + const html = await buildReportHtml(file) + expect(html).toContain("a_b < c") + expect(html).not.toContain("") + expect(html).toContain("\\displaystyle \\frac{100}{100} = 100\\%") + expect(html).not.toContain("100\\\\%") + expect(html).toContain("data:font/woff2;base64,") + expect(html).toContain("renderMathInElement") + expect(html).not.toContain("cdn.jsdelivr") + expect(calls).toHaveLength(4) + globalThis.fetch = Object.assign(async () => { throw new Error("offline cache miss") }, { preconnect: originalFetch.preconnect }) + expect(await buildReportHtml(file)).toBe(html) + }) + test("failed formula downloads produce domain errors instead of an incomplete HTML", async () => { + globalThis.fetch = Object.assign(async () => new Response("not found", { status: 404 }), { preconnect: originalFetch.preconnect }) + await expect(buildReportHtml(source("# Math\n\n$x$"))).rejects.toMatchObject({ exitCode: 1 }) + }) + test("percent-encoded literal entity names are decoded only once", async () => { + const file = source("# Image\n\n![image](%26amp%3B.svg)") + writeFileSync(join(dirname(file), "&.svg"), '') + expect(await buildReportHtml(file)).toContain("data:image/svg+xml;base64,") + }) +}) diff --git a/src/domains/seal/reports/html.ts b/src/domains/seal/reports/html.ts new file mode 100644 index 0000000..2ce9377 --- /dev/null +++ b/src/domains/seal/reports/html.ts @@ -0,0 +1,97 @@ +import { randomUUID } from "node:crypto" +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { basename, dirname, extname, join, resolve } from "node:path" +import { Marked, type TokenizerExtension, type Tokens } from "marked" +import { CliError } from "../../../core/errors.js" +import { REPORT_CSS } from "./resources.js" + +const katexBase = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/" +const mimeTypes: Record = { + ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", + ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf" +} + +function escapeHtml(text: string) { + return text.replace(/[&<>"']/g, (character) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[character]!) +} + +function decodeHtml(text: string) { + return text.replace(/&(?:amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (entity) => { + if (entity.startsWith("&#")) { + const number = entity.toLowerCase().startsWith("&#x") ? parseInt(entity.slice(3, -1), 16) : Number(entity.slice(2, -1)) + return number > 0 && number <= 0x10ffff ? String.fromCodePoint(number) : "�" + } + return ({ "&": "&", "<": "<", ">": ">", """: '"', "'": "'" })[entity.toLowerCase()] ?? entity + }) +} + +/** CDN 资源缓存命中不联网;原子写入避免并发导出或中途失败留下半个文件。 */ +async function localAsset(name: string, resource = name): Promise { + const root = process.env.SEAL_REPORT_CACHE_DIR || join(homedir(), ".cache", "seal-use", "report-render", "katex-0.16.11") + const path = join(root, name) + if (existsSync(path) && statSync(path).size > 0) return readFileSync(path) + const response = await fetch(katexBase + resource, { signal: AbortSignal.timeout(30_000) }) + if (!response.ok) throw new CliError(`公式资源下载失败:${name}(HTTP ${response.status})`, 1) + const content = Buffer.from(await response.arrayBuffer()) + if (!content.length) throw new CliError(`公式资源下载为空:${name}`, 1) + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }) + const temporary = `${path}.${randomUUID()}.tmp` + try { + writeFileSync(temporary, content, { mode: 0o600 }) + renameSync(temporary, path) + } finally { + rmSync(temporary, { force: true }) + } + return content +} + +/** 字体也内嵌,避免 HTML 引用临时目录或缺少 KaTeX 字体。 */ +async function mathAssets(): Promise<{ styles: string; scripts: string }> { + let css = (await localAsset("katex.min.css")).toString("utf8") + const names = [...new Set([...css.matchAll(/url\((fonts\/[^)]+)\)/g)].map((match) => match[1]!))] + const fonts = new Map() + // Limit font downloads to the same eight concurrent requests as the previous renderer. + for (let start = 0; start < names.length; start += 8) { + await Promise.all(names.slice(start, start + 8).map(async (name) => { fonts.set(name, await localAsset(name)) })) + } + css = css.replace(/url\((fonts\/[^)]+)\)/g, (_, name: string) => `url(data:${mimeTypes[extname(name)] ?? "application/octet-stream"};base64,${fonts.get(name)!.toString("base64")})`) + const scripts = await Promise.all(["katex.min.js", "auto-render.min.js"].map(async (name) => { + const resource = name === "auto-render.min.js" ? "contrib/" + name : name + return `` + })) + return { styles: `\n`, scripts: scripts.join("\n") } +} + +/** 渲染完整 HTML;标题取自正文 H1,并剥掉可能夹在里面的 HTML 注释。 */ +export async function buildReportHtml(file: string): Promise { + const text = readFileSync(file, "utf8").replace(/\r\n?/g, "\n") + let hasMath = false + const math: TokenizerExtension = { + name: "reportMath", level: "inline", start: (source) => source.indexOf("$"), + tokenizer(source) { + const display = source.match(/^\$\$([\s\S]+?)\$\$/) + const inline = display ?? source.match(/^\$([^$\n]+?)\$(?!\$)/) + if (!inline) return undefined + hasMath = true + return { type: "reportMath", raw: inline[0], text: inline[1]!, display: Boolean(display) } + } + } + // Tokenize math before Markdown emphasis; escape only the math text, never unescape the full HTML. + const markdown = new Marked({ extensions: [{ ...math, renderer(token: Tokens.Generic) { + const expression = String(token.text).replace(/(? { + if (/^(?:https?:|file:|data:)/.test(source)) return match + const path = resolve(dirname(file), decodeURIComponent(decodeHtml(source))) + const data = readFileSync(path).toString("base64") + return match.replace(source, `data:${mimeTypes[extname(path).toLowerCase()] ?? "application/octet-stream"};base64,${data}`) + }) + const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(//g, "").trim() || basename(file, extname(file)) + const assets = hasMath ? await mathAssets() : { styles: "", scripts: "" } + const init = hasMath ? '' : "" + return `\n\n\n\n${escapeHtml(title)}\n${assets.styles}\n\n\n${assets.scripts}\n${body}\n${init}\n\n\n` +} diff --git a/src/domains/seal/reports/png.test.ts b/src/domains/seal/reports/png.test.ts new file mode 100644 index 0000000..dc7199c --- /dev/null +++ b/src/domains/seal/reports/png.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { PNG } from "pngjs" +import { offsetReportBand } from "./browser.js" +import { pngDimensions, stitchPngBands } from "./png.js" + +const dirs: string[] = [] +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) }) +function workspace() { const dir = mkdtempSync(join(tmpdir(), "seal-png-test-")); dirs.push(dir); return dir } +function image(dir: string, name: string, width: number, height: number, red: number) { + const png = new PNG({ width, height }) + for (let i = 0; i < png.data.length; i += 4) { png.data[i] = red; png.data[i + 3] = 255 } + const file = join(dir, name) + writeFileSync(file, PNG.sync.write(png)) + return file +} + +describe("native report PNG", () => { + test("stitches bands in order including the final short band, preserving seam pixels", () => { + const dir = workspace() + const first = image(dir, "first.png", 2, 3, 11), second = image(dir, "second.png", 2, 2, 22) + const output = join(dir, "all.png") + stitchPngBands([{ file: first, height: 3 }, { file: second, height: 2 }], 2, 5, output) + expect(pngDimensions(output)).toEqual({ width: 2, height: 5 }) + const png = PNG.sync.read(readFileSync(output)) + expect(png.data[2 * 2 * 4]).toBe(11) + expect(png.data[3 * 2 * 4]).toBe(22) + expect(png.data[4 * 2 * 4]).toBe(22) + }) + test("rejects mismatched dimensions and totals without publishing an image", () => { + const dir = workspace() + const first = image(dir, "first.png", 3, 2, 11), output = join(dir, "all.png") + expect(() => stitchPngBands([{ file: first, height: 2 }], 2, 2, output)).toThrow("截图尺寸") + expect(() => stitchPngBands([{ file: first, height: 2 }], 3, 3, output)).toThrow("分带高度") + expect(existsSync(output)).toBe(false) + }) + test("rejects files masquerading as PNG output", () => { + const dir = workspace(), file = join(dir, "bad.png") + writeFileSync(file, "not a PNG") + expect(() => pngDimensions(file)).toThrow("有效的 PNG") + }) + test("band displacement overrides the final stylesheet", () => { + const html = 'report' + expect(offsetReportBand(html, 14000)).toContain('') + }) +}) diff --git a/src/domains/seal/reports/png.ts b/src/domains/seal/reports/png.ts new file mode 100644 index 0000000..5b1a167 --- /dev/null +++ b/src/domains/seal/reports/png.ts @@ -0,0 +1,31 @@ +import { closeSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs" +import { PNG } from "pngjs" +import { CliError } from "../../../core/errors.js" + +export type PngBand = { file: string; height: number } + +export function pngDimensions(file: string): { width: number; height: number } { + const header = Buffer.alloc(24) + const descriptor = openSync(file, "r") + try { + if (readSync(descriptor, header, 0, header.length, 0) !== header.length || + !header.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || header.toString("ascii", 12, 16) !== "IHDR") { + throw new CliError("浏览器未生成有效的 PNG 图片。", 1) + } + return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) } + } finally { closeSync(descriptor) } +} + +/** 按分带顺序拼接,逐带解码,避免同时保留所有分带的像素副本。 */ +export function stitchPngBands(bands: PngBand[], width: number, height: number, output: string) { + if (!bands.length || bands.reduce((total, band) => total + band.height, 0) !== height) throw new CliError("PNG 分带高度与报告高度不一致。", 1) + const canvas = new PNG({ width, height }) + let offset = 0 + for (const band of bands) { + const image = PNG.sync.read(readFileSync(band.file)) + if (image.width !== width || image.height !== band.height) throw new CliError("浏览器截图尺寸与请求不一致,未发布 PNG。", 1) + image.data.copy(canvas.data, offset * width * 4) + offset += image.height + } + writeFileSync(output, PNG.sync.write(canvas, { colorType: 2 })) +} diff --git a/src/domains/seal/reports/resources.ts b/src/domains/seal/reports/resources.ts index 9d84a81..3511dc0 100644 --- a/src/domains/seal/reports/resources.ts +++ b/src/domains/seal/reports/resources.ts @@ -1,6 +1,5 @@ import monthly from "../../../../report-templates/monthly.md" with { type: "text" }; -import validate from "../../../../report-templates/validate.py" with { type: "text" }; -import render from "../../../../report-templates/render.py" with { type: "text" }; +import css from "../../../../report-templates/report.css" with { type: "text" }; import accuracy from "../../../../report-templates/assets/图1-准确率对比.svg" with { type: "text" }; import benefits from "../../../../report-templates/assets/图2-综合效益.svg" with { type: "text" }; import screenshot from "../../../../report-templates/assets/图3-示例截图.svg" with { type: "text" }; @@ -9,7 +8,7 @@ import screenshot from "../../../../report-templates/assets/图3-示例截图.sv // Loading the built-in template never depends on cwd, a checkout, or skill installation. export const BUILTIN_TEMPLATE_PATH = "builtin:report-templates/monthly.md"; export const BUILTIN_MONTHLY_TEMPLATE = monthly; -export const REPORT_SCRIPTS = { "validate.py": validate, "render.py": render }; +export const REPORT_CSS = css; export const REPORT_ASSETS: Record = { "assets/图1-准确率对比.svg": accuracy, "assets/图2-综合效益.svg": benefits, diff --git a/src/domains/seal/reports/validate.test.ts b/src/domains/seal/reports/validate.test.ts new file mode 100644 index 0000000..db5b528 --- /dev/null +++ b/src/domains/seal/reports/validate.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { validateReportDocument } from "./validate.js" + +const valid = "# 报告\n\n| 报告信息 | 内容 |\n| --- | --- |\n| 报告编号 | TEST |\n| 客户名称 | 企业 |\n| 统计期间 | 2026-08 |\n| 报告状态 | 草稿 |\n| 生成日期 | 2026-10-12 |\n" +const dirs: string[] = [] +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) }) +function check(content: string) { + const dir = mkdtempSync(join(tmpdir(), "seal-validator-test-")) + dirs.push(dir) + const file = join(dir, "report.md") + writeFileSync(file, content) + return validateReportDocument(file) +} + +describe("native report validator", () => { + test("valid information and CRLF have the same clean result", () => { + expect(check(valid)).toMatchObject({ valid: true, tables: 1, figures: 0, issues: [] }) + expect(check(valid.replaceAll("\n", "\r\n"))).toMatchObject({ valid: true, issues: [] }) + }) + test.each(["