refactor(make-pdf): print through Aside first, the bundled browser otherwise

asideClient.ts replaces the direct $B client with one render() call per PDF (the exact option mapping the browse pdf command had: paper, margins, header/footer/page numbers, tagged, outline, printBackground, preferCSSPageSize, Paged.js wait); the diagram pre-pass, oversized-image downscale and DOCX rasters each run as one render script with per-fence try/catch; exit 4 now means no browser is available and names both remedies; $P setup reports which engine it found. The e2e gates run on whichever engine is present, so the Linux lane exercises the fallback.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Sina
2026-09-05 16:48:37 -04:00
co-authored by Claude Fable 5.1
parent c0ac82461e
commit f74d3a1a63
29 changed files with 976 additions and 1262 deletions
+151
View File
@@ -0,0 +1,151 @@
/**
* asideClient unit tests — PdfOptions → CDP Page.printToPDF mapping, the
* staging/failure shape of renderPdf (render function injected), and the
* no-browser classification (BrowserUnavailableError, exit 4). No live
* browser needed.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { pdfStepOptions, renderFailure, renderPdf } from "../src/asideClient";
import { BrowserUnavailableError, ExitCode } from "../src/types";
import { NO_BROWSER, NO_BROWSER_HELP, type RenderResult, type RenderSpec } from "../../lib/aside-render";
describe("pdfStepOptions", () => {
test("defaults: Letter paper, zero margins, no header/footer, nothing else set", () => {
const o = pdfStepOptions({ output: "/tmp/x.pdf" });
expect(o.paperWidth).toBe(8.5);
expect(o.paperHeight).toBe(11);
expect([o.marginTop, o.marginRight, o.marginBottom, o.marginLeft]).toEqual([0, 0, 0, 0]);
expect(o.displayHeaderFooter).toBeUndefined();
expect(o.generateTaggedPDF).toBeUndefined();
expect(o.generateDocumentOutline).toBeUndefined();
expect(o.printBackground).toBeUndefined();
expect(o.preferCSSPageSize).toBeUndefined();
expect(o.waitForPagedJs).toBeUndefined();
});
test("named formats map to paper inches, case-insensitively", () => {
expect(pdfStepOptions({ output: "o", format: "a4" }).paperWidth).toBeCloseTo(8.27);
expect(pdfStepOptions({ output: "o", format: "A4" }).paperHeight).toBeCloseTo(11.7);
expect(pdfStepOptions({ output: "o", format: "legal" }).paperHeight).toBe(14);
expect(() => pdfStepOptions({ output: "o", format: "napkin" })).toThrow(/unknown page size/);
});
test("explicit width/height lengths win only when no format is given", () => {
const o = pdfStepOptions({ output: "o", width: "10in", height: "254mm" });
expect(o.paperWidth).toBe(10);
expect(o.paperHeight).toBeCloseTo(10);
const withFormat = pdfStepOptions({ output: "o", format: "letter", width: "10in", height: "10in" });
expect(withFormat.paperWidth).toBe(8.5);
});
test("margins convert per side (in/pt/cm/mm/px)", () => {
const o = pdfStepOptions({ output: "o", marginTop: "1in", marginRight: "72pt", marginBottom: "2.54cm", marginLeft: "96px" });
expect(o.marginTop).toBe(1);
expect(o.marginRight).toBeCloseTo(1);
expect(o.marginBottom).toBeCloseTo(1);
expect(o.marginLeft).toBeCloseTo(1);
});
test("header only: footer gets the empty <div></div> so Chromium prints no default URL/date", () => {
const o = pdfStepOptions({ output: "o", headerTemplate: "<b>H</b>" });
expect(o.displayHeaderFooter).toBe(true);
expect(o.headerTemplate).toBe("<b>H</b>");
expect(o.footerTemplate).toBe("<div></div>");
});
test("footer only: header gets the empty <div></div>", () => {
const o = pdfStepOptions({ output: "o", footerTemplate: "<i>F</i>" });
expect(o.headerTemplate).toBe("<div></div>");
expect(o.footerTemplate).toBe("<i>F</i>");
});
test("pageNumbers builds the 'N of M' footer and overrides a custom footer", () => {
const o = pdfStepOptions({ output: "o", pageNumbers: true, footerTemplate: "<i>ignored</i>" });
expect(o.displayHeaderFooter).toBe(true);
expect(o.headerTemplate).toBe("<div></div>");
expect(o.footerTemplate).toContain('class="pageNumber"');
expect(o.footerTemplate).toContain('class="totalPages"');
expect(o.footerTemplate).not.toContain("ignored");
});
test("pageNumbers:false alone does not turn on header/footer", () => {
expect(pdfStepOptions({ output: "o", pageNumbers: false }).displayHeaderFooter).toBeUndefined();
});
test("tagged/outline/printBackground/preferCSSPageSize/toc map to their CDP names", () => {
const o = pdfStepOptions({ output: "o", tagged: true, outline: true, printBackground: true, preferCSSPageSize: true, toc: true });
expect(o.generateTaggedPDF).toBe(true);
expect(o.generateDocumentOutline).toBe(true);
expect(o.printBackground).toBe(true);
expect(o.preferCSSPageSize).toBe(true);
expect(o.waitForPagedJs).toBe(true);
// false never emits the key (CDP defaults apply)
expect(pdfStepOptions({ output: "o", tagged: false, outline: false }).generateTaggedPDF).toBeUndefined();
});
});
describe("renderPdf", () => {
test("stages the HTML into a private dir, asks for one pdf step, and cleans up", async () => {
const seen: RenderSpec[] = [];
const fakeRender = async (spec: RenderSpec): Promise<RenderResult> => {
seen.push(spec);
expect(fs.readFileSync(spec.file, "utf8")).toBe("<p>hi</p>");
return { ok: true, outputs: [], evals: {}, stdout: "" };
};
const out = path.join(os.tmpdir(), `aside-client-${process.pid}.pdf`);
await renderPdf("<p>hi</p>", { output: out, format: "a4", tagged: true }, fakeRender);
expect(seen).toHaveLength(1);
expect(seen[0].steps).toHaveLength(1);
const step = seen[0].steps[0];
expect(step.kind).toBe("pdf");
if (step.kind === "pdf") {
expect(step.out).toBe(out);
expect(step.options?.generateTaggedPDF).toBe(true);
expect(step.options?.paperWidth).toBeCloseTo(8.27);
}
// Staging dir is gone after the render.
expect(fs.existsSync(path.dirname(seen[0].file))).toBe(false);
});
test("a failed render with a browser up is a plain render error (exit 2 class), never silent", async () => {
const failing = async (): Promise<RenderResult> => ({ ok: false, engine: "aside", outputs: [], evals: {}, stdout: "", error: "render script did not finish" });
const err = await renderPdf("<p></p>", { output: "/tmp/never.pdf" }, failing).catch((e: Error) => e);
expect(err).toBeInstanceOf(Error);
expect(err).not.toBeInstanceOf(BrowserUnavailableError);
expect((err as Error).message).toMatch(/PDF render failed: render script did not finish/);
});
test("no browser at all (render() found neither Aside nor the browse binary) is BrowserUnavailableError", async () => {
const none = async (): Promise<RenderResult> => ({ ok: false, outputs: [], evals: {}, stdout: "", error: `${NO_BROWSER}: ${NO_BROWSER_HELP} (NEEDS_ASIDE: aside not on PATH)` });
const err = await renderPdf("<p></p>", { output: "/tmp/never.pdf" }, none).catch((e: Error) => e);
expect(err).toBeInstanceOf(BrowserUnavailableError);
expect((err as Error).message).toContain("aside.com");
expect((err as Error).message).toContain("./setup");
expect((err as Error).message).toContain("GSTACK_BROWSE_BIN");
});
test("the fallback engine's failures are render errors too (engine picked ≠ engine missing)", async () => {
const browseFail = async (): Promise<RenderResult> => ({ ok: false, engine: "browse", outputs: [], evals: {}, stdout: "", error: "browse pdf failed: boom" });
await expect(renderPdf("<p></p>", { output: "/tmp/never.pdf" }, browseFail)).rejects.toThrow(/PDF render failed: browse pdf failed: boom/);
});
});
describe("BrowserUnavailableError", () => {
test("renderFailure classifies on the NO_BROWSER prefix only", () => {
expect(renderFailure(`${NO_BROWSER}: x`)).toBeInstanceOf(BrowserUnavailableError);
expect(renderFailure("no browser available")).toBeInstanceOf(BrowserUnavailableError);
expect(renderFailure("Aside closed mid-run")).not.toBeInstanceOf(BrowserUnavailableError);
expect(new BrowserUnavailableError("m").name).toBe("BrowserUnavailableError");
});
test("exit code 4 is no-browser (the old Aside/browse slot, same value)", () => {
expect(ExitCode.BrowserUnavailable).toBe(4);
expect((ExitCode as Record<string, number>).AsideUnavailable).toBeUndefined();
expect((ExitCode as Record<string, number>).BrowseUnavailable).toBeUndefined();
});
});
-218
View File
@@ -1,218 +0,0 @@
/**
* browseClient unit tests — binary resolution and error mapping.
*
* These are pure unit tests; they do NOT require a running browse daemon.
* Cross-platform: assertions that pin POSIX behavior early-return on win32
* and vice versa, so both lanes only exercise their own branch.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { BrowseClientError } from "../src/types";
import { resolveBrowseBin, findExecutable } from "../src/browseClient";
// A real, always-present executable for the test platform — `cmd.exe` on
// Windows (System32 is on every install) and `/bin/sh` on POSIX. Lets the
// "honors override when it points at a real executable" test work in both
// lanes without writing a temp script.
const REAL_EXE: string =
process.platform === "win32"
? path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "cmd.exe")
: "/bin/sh";
function withEnv<T>(overrides: Record<string, string | undefined>, fn: () => T): T {
const saved: Record<string, string | undefined> = {};
for (const k of Object.keys(overrides)) saved[k] = process.env[k];
for (const [k, v] of Object.entries(overrides)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
try {
return fn();
} finally {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
}
describe("findExecutable", () => {
test("returns the bare path on POSIX when it's executable", () => {
if (process.platform === "win32") return;
const found = findExecutable("/bin/sh");
expect(found).toBe("/bin/sh");
});
test("on win32, probes .exe / .cmd / .bat after the bare-path miss", () => {
if (process.platform !== "win32") return;
// cmd.exe lives at System32\cmd.exe — probe with the bare base.
const base = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "cmd");
const found = findExecutable(base);
expect(found).toBe(base + ".exe");
});
test("returns null when no extension matches", () => {
const found = findExecutable("/nonexistent/path/to/nothing");
expect(found).toBeNull();
});
// access(X_OK) is TRUE for directories — they carry the execute/traverse bit — so a
// bare X_OK test returned ~/.claude/skills/browse, the skill's docs folder, as "the
// browse binary". Every browse call then failed with an empty error, which surfaced
// as make-pdf reporting "Chromium failed to launch".
test("rejects a DIRECTORY even though it passes access(X_OK)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-dir-"));
try {
// Prove the precondition: the directory really does pass the old test.
let passesXok = true;
try {
fs.accessSync(dir, fs.constants.X_OK);
} catch {
passesXok = false;
}
expect(passesXok).toBe(true);
expect(findExecutable(dir)).toBeNull();
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("rejects a directory that shadows a real binary name", () => {
// The exact shape of the bug: a directory named like the thing being looked for.
const base = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-shadow-"));
const shadow = path.join(base, "browse");
fs.mkdirSync(shadow);
fs.writeFileSync(path.join(shadow, "SKILL.md"), "# not a binary\n");
try {
expect(findExecutable(shadow)).toBeNull();
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
});
describe("resolveBrowseBin", () => {
test("throws BrowseClientError with setup hint when nothing is found", () => {
// Point overrides at non-existent paths and clear PATH so Bun.which finds
// nothing. Sibling/global probes go through findExecutable on real paths,
// but the test asserts on the error shape rather than depending on whether
// a real browse install exists on the box.
let thrown: unknown = null;
try {
withEnv(
{
GSTACK_BROWSE_BIN: "/nonexistent/gstack-browse-bin",
BROWSE_BIN: "/nonexistent/browse-bin",
PATH: "",
Path: "",
},
() => resolveBrowseBin(),
);
} catch (err) {
thrown = err;
}
if (thrown) {
expect(thrown).toBeInstanceOf(BrowseClientError);
expect((thrown as BrowseClientError).message).toContain("browse binary not found");
expect((thrown as BrowseClientError).message).toContain("./setup");
expect((thrown as BrowseClientError).message).toContain("GSTACK_BROWSE_BIN");
// Back-compat alias still surfaces in the diagnostic.
expect((thrown as BrowseClientError).message).toContain("BROWSE_BIN");
}
// If the test box has a real browse install on disk, sibling/global may
// resolve and the helper won't throw — that's fine; the assertion is
// gated on whether it threw at all.
});
test("honors GSTACK_BROWSE_BIN when it points at a real executable", () => {
const resolved = withEnv({ GSTACK_BROWSE_BIN: REAL_EXE }, () => resolveBrowseBin());
expect(resolved).toBe(REAL_EXE);
});
test("honors BROWSE_BIN as a back-compat alias", () => {
const resolved = withEnv(
{ GSTACK_BROWSE_BIN: undefined, BROWSE_BIN: REAL_EXE },
() => resolveBrowseBin(),
);
expect(resolved).toBe(REAL_EXE);
});
test("GSTACK_BROWSE_BIN takes precedence over BROWSE_BIN", () => {
const resolved = withEnv(
{ GSTACK_BROWSE_BIN: REAL_EXE, BROWSE_BIN: "/nonexistent/legacy" },
() => resolveBrowseBin(),
);
expect(resolved).toBe(REAL_EXE);
});
test("strips wrapping double quotes from override values", () => {
const resolved = withEnv({ GSTACK_BROWSE_BIN: `"${REAL_EXE}"` }, () => resolveBrowseBin());
expect(resolved).toBe(REAL_EXE);
});
});
describe("BrowseClientError", () => {
test("captures exit code, command, and stderr", () => {
const err = new BrowseClientError(127, "pdf", "Chromium not found");
expect(err.exitCode).toBe(127);
expect(err.command).toBe("pdf");
expect(err.stderr).toBe("Chromium not found");
expect(err.message).toContain("browse pdf exited 127");
expect(err.message).toContain("Chromium not found");
expect(err.name).toBe("BrowseClientError");
});
});
describe("resolveBrowseBin — sibling resolution from execPath (#2156)", () => {
// In a bun-compiled binary argv[0] is the raw invocation string (often
// relative), so the old dirname(argv[0]) built sibling candidates against
// the CWD. Under `bun test` the process path is the bun runtime, so these
// shapes are only reachable through the selfPath seam.
test("sibling browse next to the install dir is found via selfPath", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-sib-"));
try {
const distDir = path.join(base, "browse", "dist");
fs.mkdirSync(distDir, { recursive: true });
const sibling = path.join(distDir, "browse");
fs.writeFileSync(sibling, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const selfPath = path.join(base, "make-pdf", "dist", "pdf");
// Receipts: pre-fix code ignores the selfPath seam entirely, so it can
// never produce this sibling — it either finds a global install (wrong
// value) or throws (PATH is empty). Red on v1.68.3.0 either way.
const resolved = resolveBrowseBin({ PATH: "" }, selfPath);
expect(resolved).toBe(path.resolve(path.join(base, "make-pdf"), "../browse/dist/browse"));
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
test("a decoy browse DIRECTORY near selfPath never shadows a real PATH binary", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-decoy-"));
try {
// The ~/.claude/skills/browse alias-directory shape from #2156: a
// directory named exactly like the third sibling candidate.
fs.mkdirSync(path.join(base, "browse"), { recursive: true });
const pathDir = path.join(base, "pathbin");
fs.mkdirSync(pathDir, { recursive: true });
const onPath = path.join(pathDir, "browse");
fs.writeFileSync(onPath, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const selfPath = path.join(base, "tools", "pdf");
// os.homedir() ignores a $HOME override under bun, so the global-install
// probe may legitimately win on boxes with a real ~/.claude install. The
// invariant under test is narrower: the decoy DIRECTORY never wins, and
// whatever wins is a regular file.
const resolved = resolveBrowseBin({ PATH: pathDir }, selfPath);
expect(resolved).not.toBe(path.join(base, "browse"));
expect(fs.statSync(resolved).isFile()).toBe(true);
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
});
+56 -42
View File
@@ -1,6 +1,6 @@
/**
* Coverage-gap fills from the v1.58.0.0 ship audit — the branches the main
* suites couldn't reach without a live browse tab (mock-tab here), plus the
* suites couldn't reach without a live bundle page (mock runner here), plus the
* pure-function stragglers (WebP probing, landscape geometry, bundle path
* resolution, screen CSS).
*/
@@ -10,8 +10,8 @@ import * as os from "node:os";
import * as path from "node:path";
import {
RenderCallError,
type RenderTab,
type BundleCall,
type BundleResult,
landscapeContentBox,
rasterizeDiagramFigures,
renderFenceSlots,
@@ -21,19 +21,22 @@ import {
import { imageDims } from "../src/image-size";
import { screenCss } from "../src/print-css";
/** Duck-typed RenderTab: scripted call results + a loadBundle counter. */
function mockTab(script: (fn: string, ...args: Array<string | number>) => string) {
/** Scripted BundleRun: a throwing script call becomes an ERR result, plus counters. */
function mockRun(script: (fn: string, ...args: unknown[]) => string) {
const calls: string[] = [];
let reloads = 0;
const tab = {
call: (fn: string, ...args: Array<string | number>) => {
calls.push(fn);
return script(fn, ...args);
},
loadBundle: () => { reloads++; },
close: () => {},
} as unknown as RenderTab;
return { tab, calls, reloadCount: () => reloads };
let batches = 0;
const run = async (batch: BundleCall[]): Promise<BundleResult[]> => {
batches++;
return batch.map((c) => {
calls.push(c.fn);
try {
return { ok: true, value: script(c.fn, ...c.args) };
} catch (e: any) {
return { ok: false, error: e.message };
}
});
};
return { run, calls, batchCount: () => batches };
}
const fence = (over: Partial<{ lang: string; source: string; ordinal: number }>) => ({
@@ -49,88 +52,99 @@ const fence = (over: Partial<{ lang: string; source: string; ordinal: number }>)
// ─── renderFenceSlots: reset contract + excalidraw branches ───────────
describe("renderFenceSlots (mock tab)", () => {
test("reset contract: a failure reloads the bundle and the NEXT fence still renders", () => {
const { tab, reloadCount } = mockTab((fn, ...args) => {
if (String(args[1] ?? "").includes("BROKEN")) throw new RenderCallError("Parse error on line 1");
describe("renderFenceSlots (mock runner)", () => {
test("one batch for all fences: a failure is a diagnostic block and the NEXT fence still renders", async () => {
const { run, batchCount } = mockRun((fn, ...args) => {
if (String(args[1] ?? "").includes("BROKEN")) throw new Error("Parse error on line 1");
return "<svg><g/></svg>";
});
const warnings: string[] = [];
const slots = renderFenceSlots(
const slots = await renderFenceSlots(
[
fence({ ordinal: 1 }),
fence({ ordinal: 2, source: "BROKEN" }),
fence({ ordinal: 3 }),
],
tab,
run,
(m) => warnings.push(m),
);
expect(slots.get("tok-1")).toContain("<svg>");
expect(slots.get("tok-2")).toContain("diagram-error");
expect(slots.get("tok-2")).toContain("Parse error on line 1");
expect(slots.get("tok-3")).toContain("<svg>"); // post-failure fence rendered
expect(reloadCount()).toBe(1); // exactly one reset reload
expect(batchCount()).toBe(1); // one script for the whole document
expect(warnings[0]).toContain("failed to render");
});
test("excalidraw fence renders via __excalidrawToSvg", () => {
const { tab, calls } = mockTab(() => "<svg data-x><g/></svg>");
const slots = renderFenceSlots(
test("excalidraw fence renders via __excalidrawToSvg", async () => {
const { run, calls } = mockRun(() => "<svg data-x><g/></svg>");
const slots = await renderFenceSlots(
[fence({ lang: "excalidraw", source: '{"type":"excalidraw","elements":[]}' })],
tab,
run,
() => {},
);
expect(calls).toEqual(["__excalidrawToSvg"]);
expect(slots.get("tok-1")).toContain("<svg");
});
test("invalid excalidraw JSON fails fast into a diagnostic WITHOUT calling the tab", () => {
const { tab, calls, reloadCount } = mockTab(() => "<svg/>");
test("invalid excalidraw JSON fails fast into a diagnostic WITHOUT a bundle call", async () => {
const { run, calls } = mockRun(() => "<svg/>");
const warnings: string[] = [];
const slots = renderFenceSlots(
const slots = await renderFenceSlots(
[fence({ lang: "excalidraw", source: "{not json" })],
tab,
run,
(m) => warnings.push(m),
);
expect(calls).toEqual([]); // JSON.parse threw before any bundle call
expect(slots.get("tok-1")).toContain("diagram-error");
expect(reloadCount()).toBe(1);
expect(warnings).toHaveLength(1);
});
});
// ─── rasterizeDiagramFigures: svg-data-URI + error fallbacks ──────────
describe("rasterizeDiagramFigures (mock tab)", () => {
describe("rasterizeDiagramFigures (mock runner)", () => {
const figure = `<figure class="diagram" role="img" aria-label="flow"><svg viewBox="0 0 10 10"><g/></svg></figure>`;
test("svg data-URI images rasterize to PNG", () => {
test("figures and svg data-URI images rasterize to PNG in ONE batch", async () => {
const svgUri = `data:image/svg+xml;base64,${Buffer.from("<svg/>").toString("base64")}`;
const { tab } = mockTab(() => "data:image/png;base64,AAAA");
const out = rasterizeDiagramFigures(`<img src="${svgUri}" alt="v">`, tab, 6.5, () => {});
expect(out).toContain('src="data:image/png;base64,AAAA"');
const { run, calls, batchCount } = mockRun((_fn, svg) => `data:image/png;base64,${String(svg).includes("viewBox") ? "FIG" : "IMG"}`);
const out = await rasterizeDiagramFigures(`${figure}<img src="${svgUri}" alt="v">`, run, 6.5, () => {});
expect(calls).toEqual(["__rasterize", "__rasterize"]);
expect(batchCount()).toBe(1);
expect(out).toContain('<p><img src="data:image/png;base64,FIG" alt="flow"></p>');
expect(out).toContain('src="data:image/png;base64,IMG" alt="v"');
expect(out).not.toContain("gstack-raster-slot");
});
test("figure rasterization failure surfaces the SOURCE as text (never silent loss)", () => {
test("no rasterizable content → no bundle call at all", async () => {
const { run, batchCount } = mockRun(() => "x");
const html = `<p>plain</p><img src="data:image/png;base64,AAAA">`;
expect(await rasterizeDiagramFigures(html, run, 6.5, () => {})).toBe(html);
expect(batchCount()).toBe(0);
});
test("figure rasterization failure surfaces the SOURCE as text (never silent loss)", async () => {
// Returning the figure unchanged would make the diagram vanish in DOCX
// (the converter drops <figure>/<svg>) — the failure must be visible.
const { tab } = mockTab(() => { throw new RenderCallError("tainted"); });
const { run } = mockRun(() => { throw new Error("tainted"); });
const warnings: string[] = [];
const srcFigure = figure.replace(
'<figure class="diagram"',
`<figure class="diagram" data-gstack-source="${Buffer.from("graph LR\n A --> B").toString("base64")}"`,
);
const out = rasterizeDiagramFigures(srcFigure, tab, 6.5, (m) => warnings.push(m));
const out = await rasterizeDiagramFigures(srcFigure, run, 6.5, (m) => warnings.push(m));
expect(out).toContain("could not be rasterized");
expect(out).toContain("A --&gt; B"); // source visible (escaped), not dropped
expect(out).not.toContain("<figure");
expect(warnings[0]).toContain("rasterization failed");
});
test("svg data-URI rasterization failure keeps the original tag", () => {
test("svg data-URI rasterization failure keeps the original tag", async () => {
const svgUri = `data:image/svg+xml;base64,${Buffer.from("<svg/>").toString("base64")}`;
const { tab } = mockTab(() => { throw new RenderCallError("decode failed"); });
const { run } = mockRun(() => { throw new Error("decode failed"); });
const tagIn = `<img src="${svgUri}">`;
const out = rasterizeDiagramFigures(tagIn, tab, 6.5, () => {});
const out = await rasterizeDiagramFigures(tagIn, run, 6.5, () => {});
expect(out).toBe(tagIn);
});
});
+163 -34
View File
@@ -1,8 +1,9 @@
/**
* Unit tests for the diagram pre-pass: fence extraction, info-string parsing,
* slot substitution, diagnostic blocks, image inlining policy, and the
* byte-level image dimension prober. No browse daemon required — the tab
* factory returns null so downscale paths are exercised as no-ops.
* byte-level image dimension prober, and the bundle runner's script shape
* (render function injected). No live Aside required — `run: null` makes
* downscale paths no-ops.
*/
import { afterAll, describe, expect, test } from "bun:test";
import * as fs from "node:fs";
@@ -13,6 +14,7 @@ import zlib from "node:zlib";
import {
StrictModeError,
buildDiagnosticBlock,
bundleRunner,
buildDiagramFigure,
contentWidthInches,
dimToInches,
@@ -23,6 +25,7 @@ import {
decodeFigureSource,
} from "../src/diagram-prepass";
import { imageDims } from "../src/image-size";
import type { RenderResult, RenderSpec } from "../../lib/aside-render";
// ─── fence extraction ─────────────────────────────────────────────────
@@ -251,51 +254,51 @@ describe("inlineLocalImages", () => {
strict: false,
allowNetwork: false,
contentWidthIn: 6.5,
getTab: () => null,
run: null,
};
test("local image becomes a data URI with probed dimensions", () => {
test("local image becomes a data URI with probed dimensions", async () => {
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="ok.png" alt="x">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="ok.png" alt="x">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain("data:image/png;base64,");
expect(out).toContain('data-gstack-px-width="40"');
expect(out).toContain('data-gstack-px-height="20"');
expect(warnings).toHaveLength(0);
});
test("missing image → visible placeholder + warning", () => {
test("missing image → visible placeholder + warning", async () => {
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="nope.png">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="nope.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain("image-missing");
expect(out).toContain("nope.png");
expect(warnings.length).toBe(1);
});
test("missing image + --strict → StrictModeError", () => {
expect(() =>
test("missing image + --strict → StrictModeError", async () => {
await expect(
inlineLocalImages(`<img src="nope.png">`, { ...base, strict: true, warn: () => {} }),
).toThrow(StrictModeError);
).rejects.toThrow(StrictModeError);
});
test("remote image is BLOCKED with a visible placeholder (offline posture)", () => {
test("remote image is BLOCKED with a visible placeholder (offline posture)", async () => {
// Leaving the tag would make Chromium fetch it at print time anyway —
// the offline posture must remove the src, not just warn about it.
const warnings: string[] = [];
const tag = `<img src="https://example.com/x.png">`;
const out = inlineLocalImages(tag, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(tag, { ...base, warn: (m) => warnings.push(m) });
expect(out).not.toContain("https://example.com/x.png\"");
expect(out).toContain("remote image blocked");
expect(warnings[0]).toContain("offline");
});
test("symlink escaping the input dir is caught by the realpath check", () => {
test("symlink escaping the input dir is caught by the realpath check", async () => {
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "prepass-symlink-"));
fs.writeFileSync(path.join(outside, "secret.png"), tinyPng(5, 5));
const link = path.join(dir, "innocent.png");
try {
fs.symlinkSync(path.join(outside, "secret.png"), link);
const warnings: string[] = [];
inlineLocalImages(`<img src="innocent.png">`, { ...base, warn: (m) => warnings.push(m) });
await inlineLocalImages(`<img src="innocent.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(warnings.some((w) => w.includes("OUTSIDE the input directory"))).toBe(true);
} finally {
try { fs.unlinkSync(link); } catch { /* ignore */ }
@@ -303,48 +306,48 @@ describe("inlineLocalImages", () => {
}
});
test("special files and oversized images degrade to placeholders, never hang", () => {
test("special files and oversized images degrade to placeholders, never hang", async () => {
// Directory masquerading as an image — not a regular file.
fs.mkdirSync(path.join(dir, "dir.png"), { recursive: true });
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="dir.png">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="dir.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain("image-missing");
expect(warnings.some((w) => w.includes("not a regular file"))).toBe(true);
});
test("malformed percent-encoding degrades to missing-image, never throws", () => {
test("malformed percent-encoding degrades to missing-image, never throws", async () => {
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="foo%zz.png">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="foo%zz.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain("image-missing");
});
test("remote image + --allow-network passes silently", () => {
test("remote image + --allow-network passes silently", async () => {
const warnings: string[] = [];
const tag = `<img src="https://example.com/x.png">`;
const out = inlineLocalImages(tag, { ...base, allowNetwork: true, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(tag, { ...base, allowNetwork: true, warn: (m) => warnings.push(m) });
expect(out).toBe(tag);
expect(warnings).toHaveLength(0);
});
test("remote image + --strict → StrictModeError", () => {
expect(() =>
test("remote image + --strict → StrictModeError", async () => {
await expect(
inlineLocalImages(`<img src="https://example.com/x.png">`, { ...base, strict: true, warn: () => {} }),
).toThrow(StrictModeError);
).rejects.toThrow(StrictModeError);
});
test("existing data URI gets dimension annotations only", () => {
test("existing data URI gets dimension annotations only", async () => {
const uri = `data:image/png;base64,${tinyPng(33, 44).toString("base64")}`;
const out = inlineLocalImages(`<img src="${uri}">`, { ...base, warn: () => {} });
const out = await inlineLocalImages(`<img src="${uri}">`, { ...base, warn: () => {} });
expect(out).toContain('data-gstack-px-width="33"');
expect(out).toContain('data-gstack-px-height="44"');
});
test("out-of-tree image reads warn (never silent) and still inline", () => {
test("out-of-tree image reads warn (never silent) and still inline", async () => {
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "prepass-outside-"));
fs.writeFileSync(path.join(outside, "ext.png"), tinyPng(10, 10));
try {
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="${path.join(outside, "ext.png")}">`, {
const out = await inlineLocalImages(`<img src="${path.join(outside, "ext.png")}">`, {
...base, warn: (m) => warnings.push(m),
});
expect(out).toContain("data:image/png;base64,");
@@ -354,26 +357,26 @@ describe("inlineLocalImages", () => {
}
});
test("out-of-tree image + --strict → StrictModeError", () => {
test("out-of-tree image + --strict → StrictModeError", async () => {
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "prepass-outside-"));
fs.writeFileSync(path.join(outside, "ext.png"), tinyPng(10, 10));
try {
expect(() =>
await expect(
inlineLocalImages(`<img src="${path.join(outside, "ext.png")}">`, {
...base, strict: true, warn: () => {},
}),
).toThrow(StrictModeError);
).rejects.toThrow(StrictModeError);
} finally {
fs.rmSync(outside, { recursive: true, force: true });
}
});
test("Windows drive-letter src is treated as a local path, not a URL scheme", () => {
test("Windows drive-letter src is treated as a local path, not a URL scheme", async () => {
// C:/x.png matches the single-letter-scheme regex — it must reach the
// local-path branch (and the missing-file placeholder), never silently
// pass through as an unknown URL.
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="C:/missing/x.png">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="C:/missing/x.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain("image-missing");
// Two warnings: it's out-of-tree (resolved outside inputDir) AND missing.
expect(warnings.some((w) => w.includes("image not found"))).toBe(true);
@@ -393,11 +396,137 @@ describe("inlineLocalImages", () => {
expect(markdown).toBe(md);
});
test("oversized raster without a tab inlines at full size with no downscale", () => {
test("oversized raster without a tab inlines at full size with no downscale", async () => {
// 6000px-wide PNG header (body irrelevant for probing; file must exist)
fs.writeFileSync(path.join(dir, "wide.png"), tinyPng(6000, 100));
const warnings: string[] = [];
const out = inlineLocalImages(`<img src="wide.png">`, { ...base, warn: (m) => warnings.push(m) });
const out = await inlineLocalImages(`<img src="wide.png">`, { ...base, warn: (m) => warnings.push(m) });
expect(out).toContain('data-gstack-px-width="6000"');
});
test("oversized raster WITH a runner: one __downscaleRaster batch, token swapped for the scaled bytes", async () => {
fs.writeFileSync(path.join(dir, "wide2.png"), tinyPng(6000, 100));
const calls: Array<{ fn: string; args: unknown[] }> = [];
const run = async (batch: Array<{ fn: string; args: unknown[] }>) => {
calls.push(...batch);
return batch.map(() => ({ ok: true as const, value: "data:image/png;base64,U0NBTEVE" }));
};
const warnings: string[] = [];
// Same image twice: read/downscaled once, both tags rewritten.
const out = await inlineLocalImages(`<img src="wide2.png"> <img src="wide2.png" alt="b">`, { ...base, run, warn: (m) => warnings.push(m) });
expect(calls).toHaveLength(1);
expect(calls[0].fn).toBe("__downscaleRaster");
expect(String(calls[0].args[0])).toStartWith("data:image/png;base64,");
expect(calls[0].args[1]).toBe(1950); // 6.5in × 300dpi
expect(out.match(/data:image\/png;base64,U0NBTEVE/g)).toHaveLength(2);
expect(out).toContain('data-gstack-px-width="1950"');
expect(out).not.toContain("gstack-downscale-slot");
expect(warnings.some((w) => w.includes("downscaled wide2.png 6000px"))).toBe(true);
});
test("a failed downscale falls back to the full-size bytes with a warning", async () => {
fs.writeFileSync(path.join(dir, "wide3.png"), tinyPng(6000, 100));
const run = async (batch: unknown[]) => batch.map(() => ({ ok: false as const, error: "image decode failed" }));
const warnings: string[] = [];
const out = await inlineLocalImages(`<img src="wide3.png">`, { ...base, run, warn: (m) => warnings.push(m) });
expect(out).toContain('data-gstack-px-width="6000"');
expect(out).toContain("data:image/png;base64,");
expect(out).not.toContain("gstack-downscale-slot");
expect(warnings.some((w) => w.includes("downscale failed"))).toBe(true);
});
});
// ─── bundle runner (script shape, injected render) ────────────────────
describe("bundleRunner", () => {
const bundle = path.join(os.tmpdir(), `fake-bundle-${process.pid}.html`);
fs.writeFileSync(bundle, "<!doctype html><div id=done>ready</div>");
afterAll(() => { try { fs.unlinkSync(bundle); } catch { /* best-effort */ } });
/** Fake Aside: asserts the spec shape and writes OK:/ERR: result files. */
function fakeRender(script: (fn: string, args: unknown[]) => string) {
const specs: RenderSpec[] = [];
const render = async (spec: RenderSpec): Promise<RenderResult> => {
specs.push(spec);
for (const step of spec.steps) {
if (step.kind !== "eval" || !step.out) throw new Error("expected eval steps with out files");
const i = Number(step.expression.match(/call-(\d+)\.json/)![1]);
const fn = step.expression.match(/window\["(__\w+)"\]/)![1];
const args = JSON.parse(fs.readFileSync(path.join(spec.serveRoot!, `call-${i}.json`), "utf8"));
let text: string;
try { text = "OK:" + script(fn, args); } catch (e: any) { text = "ERR:" + e.message; }
fs.writeFileSync(step.out, text);
}
return { ok: true, outputs: [], evals: {}, stdout: "" };
};
return { render, specs };
}
test("stages the bundle + one JSON args file per call in a served dir, waits for #done, reads results back", async () => {
const { render, specs } = fakeRender((fn, args) => `${fn}(${args.join(",")})`);
const run = bundleRunner({ bundlePath: bundle, render });
const results = await run([
{ fn: "__renderMermaid", args: ["mermaid-fence-1", "graph LR"] },
{ fn: "__excalidrawToSvg", args: ["{}"] },
]);
expect(results).toEqual([
{ ok: true, value: "__renderMermaid(mermaid-fence-1,graph LR)" },
{ ok: true, value: "__excalidrawToSvg({})" },
]);
expect(specs).toHaveLength(1);
const spec = specs[0];
expect(spec.waitFor).toEqual({ selector: "#done", timeoutMs: 20_000 });
expect(path.dirname(spec.file)).toBe(spec.serveRoot);
expect(spec.steps).toHaveLength(2);
// Payload rides the served dir, not argv: the expression stays tiny.
for (const step of spec.steps) expect(step.kind === "eval" && step.expression.length < 300).toBe(true);
// Private per-script dir is cleaned up.
expect(fs.existsSync(spec.serveRoot!)).toBe(false);
});
test("a throwing call is an ERR result; the other calls in the script still succeed", async () => {
const { render } = fakeRender((_fn, args) => {
if (String(args[1]).includes("BROKEN")) throw new Error("Parse error on line 1");
return "<svg/>";
});
const run = bundleRunner({ bundlePath: bundle, render });
const results = await run([
{ fn: "__renderMermaid", args: ["a", "ok"] },
{ fn: "__renderMermaid", args: ["b", "BROKEN"] },
{ fn: "__renderMermaid", args: ["c", "ok"] },
]);
expect(results.map((r) => r.ok)).toEqual([true, false, true]);
expect(results[1]).toEqual({ ok: false, error: "Parse error on line 1" });
});
test("chunks at 40 calls per script (Aside's 120s script cap)", async () => {
const { render, specs } = fakeRender(() => "x");
const run = bundleRunner({ bundlePath: bundle, render });
const results = await run(Array.from({ length: 85 }, (_, i) => ({ fn: "__renderMermaid", args: [`m${i}`, "g"] })));
expect(results).toHaveLength(85);
expect(specs.map((s) => s.steps.length)).toEqual([40, 40, 5]);
});
test("a whole-script failure fails every call in it with the renderer's message", async () => {
const render = async (): Promise<RenderResult> => ({ ok: false, outputs: [], evals: {}, stdout: "", error: "aside repl did not run: spawn aside ENOENT" });
const run = bundleRunner({ bundlePath: bundle, render });
const results = await run([{ fn: "__renderMermaid", args: ["a", "g"] }, { fn: "__renderMermaid", args: ["b", "g"] }]);
expect(results).toHaveLength(2);
for (const r of results) {
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toContain("diagram renderer: aside repl did not run");
}
});
test("an unreadable bundle fails every call without touching Aside; zero calls run nothing", async () => {
let rendered = 0;
const render = async (): Promise<RenderResult> => { rendered++; return { ok: true, outputs: [], evals: {}, stdout: "" }; };
const run = bundleRunner({ bundlePath: "/nonexistent/diagram-render.html", render });
expect(await run([])).toEqual([]);
const results = await run([{ fn: "__renderMermaid", args: ["a", "g"] }, { fn: "__renderMermaid", args: ["b", "g"] }]);
expect(results.map((r) => r.ok)).toEqual([false, false]);
if (!results[0].ok) expect(results[0].error).toContain("ENOENT");
expect(rendered).toBe(0);
});
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Gate prerequisite shared by the make-pdf e2e gates: SOME browser the
* compiled binary can print through — the Aside app (macOS dev machines) or
* gstack's own browse binary (what the Linux free-tests lane builds via
* build:gates). Mirrors lib/aside-render's pickEngine() order.
*/
import { resolveBrowseBin } from "../../../lib/aside-render";
import { asideAvailable } from "../../../test/helpers/aside-available";
export const NO_BROWSER_REASON =
"no browser available (open the Aside app, or build gstack's own browser with `bun run build:gates`; GSTACK_SKIP_ASIDE=1 skips Aside).";
export function browserAvailable(): boolean {
return asideAvailable() || resolveBrowseBin() !== null;
}
+4
View File
@@ -25,6 +25,10 @@ const EXPECT_BINARIES = process.env.GSTACK_EXPECT_BINARIES === "1";
describe("gate prerequisites (CI tripwire)", () => {
test.skipIf(!EXPECT_BINARIES)("gate artifacts and tools exist when the lane promises them", () => {
const missing: string[] = [];
// Aside itself is deliberately NOT asserted: CI runners have no Aside. The
// gates print through gstack's own browse binary there (the fallback in
// lib/aside-render), so THAT build artifact is promised alongside the
// make-pdf binary, the diagram bundle, and poppler.
for (const rel of [
"make-pdf/dist/pdf",
"browse/dist/browse",
+8 -11
View File
@@ -11,8 +11,8 @@
* user actually cares about — features interact, and the combined
* extraction is what predicts production quality.
*
* Gating: only runs when the compiled binary + browse + pdftotext are all
* available. Skipped cleanly otherwise (local dev without full install).
* Gating: only runs when the compiled binary + a browser (Aside or browse) + pdftotext
* are all available. Skipped cleanly otherwise (local dev, CI runners).
*/
import { describe, expect, test } from "bun:test";
@@ -22,16 +22,17 @@ import * as os from "node:os";
import * as path from "node:path";
import { copyPasteGate, resolvePdftotext } from "../../src/pdftotext";
import { browserAvailable, NO_BROWSER_REASON } from "./browser-available";
const FIXTURE = path.resolve(__dirname, "../fixtures/combined-gate.md");
const EXPECTED = path.resolve(__dirname, "../fixtures/combined-gate.expected.txt");
const ROOT = path.resolve(__dirname, "../../..");
const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf");
const BROWSE_BIN = path.join(ROOT, "browse/dist/browse");
function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string } {
if (!fs.existsSync(PDF_BIN)) return { ok: false, reason: `make-pdf binary missing (${PDF_BIN}). Run bun run build.` };
if (!fs.existsSync(BROWSE_BIN)) return { ok: false, reason: `browse binary missing (${BROWSE_BIN}).` };
// Aside (macOS) or gstack's own browse binary (what CI builds) — a skip only when neither exists.
if (!browserAvailable()) return { ok: false, reason: NO_BROWSER_REASON };
if (!fs.existsSync(FIXTURE)) return { ok: false, reason: `fixture missing (${FIXTURE}).` };
if (!fs.existsSync(EXPECTED)) return { ok: false, reason: `expected.txt missing (${EXPECTED}).` };
try { resolvePdftotext(); } catch (err: any) { return { ok: false, reason: err.message }; }
@@ -43,15 +44,11 @@ describe("combined-features copy-paste gate", () => {
test.skipIf(!avail.ok)("fixture PDF extracts cleanly through pdftotext", () => {
if (!avail.ok) return; // satisfies the type checker
// Use /tmp directly (browse's validateOutputPath allows /private/tmp,
// which macOS resolves /tmp to). os.tmpdir() returns /var/folders/...
// which is outside the safe-dirs allowlist.
const outputPdf = `/tmp/make-pdf-combined-gate-${process.pid}.pdf`;
const outputPdf = path.join(os.tmpdir(), `make-pdf-combined-gate-${process.pid}.pdf`);
try {
execFileSync(PDF_BIN, ["generate", FIXTURE, outputPdf, "--quiet"], {
encoding: "utf8",
timeout: 30_000,
env: { ...process.env, BROWSE_BIN },
timeout: 60_000,
stdio: ["ignore", "pipe", "pipe"],
});
expect(fs.existsSync(outputPdf)).toBe(true);
@@ -67,7 +64,7 @@ describe("combined-features copy-paste gate", () => {
} finally {
try { fs.unlinkSync(outputPdf); } catch { /* ignore */ }
}
}, 30000);
}, 60000);
if (!avail.ok) {
test("prerequisites check", () => {
+13 -17
View File
@@ -14,7 +14,8 @@
* colored pixels — text extraction can't fake that.
*
* Free-tier deterministic gate: runs under plain `bun test` when the compiled
* binaries + poppler are available; hard-fails in CI when missing.
* binary, a browser (Aside or the browse binary), and poppler are available; self-skips otherwise (ci-prereqs.test.ts
* is the CI tripwire for the build artifacts).
*/
import { describe, expect, test } from "bun:test";
@@ -23,11 +24,11 @@ import * as fs from "node:fs";
import * as path from "node:path";
import { resolvePopplerTool } from "../../src/pdftotext";
import { browserAvailable, NO_BROWSER_REASON } from "./browser-available";
const FIXTURE = path.resolve(__dirname, "../fixtures/diagram-gate.md");
const ROOT = path.resolve(__dirname, "../../..");
const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf");
const BROWSE_BIN = path.join(ROOT, "browse/dist/browse");
const BUNDLE = path.join(ROOT, "lib/diagram-render/dist/diagram-render.html");
const CHILD_TIMEOUT_MS = 60_000;
@@ -38,7 +39,8 @@ const SATURATION_DELTA = 60;
function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string } {
if (!fs.existsSync(PDF_BIN)) return { ok: false, reason: `make-pdf binary missing (${PDF_BIN}). Run bun run build.` };
if (!fs.existsSync(BROWSE_BIN)) return { ok: false, reason: `browse binary missing (${BROWSE_BIN}).` };
// Aside (macOS) or gstack's own browse binary (what CI builds) — a skip only when neither exists.
if (!browserAvailable()) return { ok: false, reason: NO_BROWSER_REASON };
if (!fs.existsSync(BUNDLE)) return { ok: false, reason: `diagram-render bundle missing (${BUNDLE}). Run bun run build:diagram-render.` };
if (!fs.existsSync(FIXTURE)) return { ok: false, reason: `fixture missing (${FIXTURE}).` };
if (!resolvePopplerTool("pdftotext")) return { ok: false, reason: "pdftotext not found (install poppler-utils)." };
@@ -80,7 +82,6 @@ describe("diagram render gate", () => {
try {
// No --quiet: stderr carries the downscale warning asserted below.
const run = Bun.spawnSync([PDF_BIN, "generate", FIXTURE, outputPdf], {
env: { ...process.env, BROWSE_BIN },
stdout: "pipe",
stderr: "pipe",
timeout: 120_000,
@@ -92,8 +93,8 @@ describe("diagram render gate", () => {
expect(fs.existsSync(outputPdf)).toBe(true);
// 0. Print-resolution downscale fired on the 4200px noise photo — this
// is the only live coverage of __downscaleRaster AND the chunked
// jsViaBuffer transport (the data URI exceeds the 100KB argv path).
// is the only live coverage of __downscaleRaster AND the served-dir
// payload transport (the data URI is far too big for argv).
expect(stderr).toMatch(/downscaled huge-noise\.png 4200px → \d+px/);
const pdftotext = resolvePopplerTool("pdftotext")!;
@@ -101,8 +102,8 @@ describe("diagram render gate", () => {
// 1. Vector text from BOTH diagrams (multi-fence + id-collision check).
// The broken fence sits BETWEEN them in the fixture, so the second
// diagram rendering at all proves the reset contract (D6.2): the
// bundle page reloaded after the failure and kept working.
// diagram rendering at all proves a failed fence never poisons the
// batch (D6.2): the script kept going and the next render succeeded.
for (const label of ["gatealphanode", "gatebetanode", "gategammanode", "gatedeltanode", "gateepsilonnode"]) {
expect(text).toContain(label);
}
@@ -148,8 +149,7 @@ describe("diagram render gate", () => {
try {
execFileSync(PDF_BIN, ["generate", md, path.join(workDir, "out.pdf"), "--quiet", "--strict"], {
encoding: "utf8",
env: { ...process.env, BROWSE_BIN },
stdio: ["ignore", "pipe", "pipe"],
stdio: ["ignore", "pipe", "pipe"],
timeout: CHILD_TIMEOUT_MS,
});
} catch (err: any) {
@@ -164,13 +164,9 @@ describe("diagram render gate", () => {
}, 120000);
if (!avail.ok) {
test("diagram gate prerequisites are present (hard-required in CI)", () => {
// Hard-require only where the binary is expected: the make-pdf gate
// workflow is macOS-only (path-filtered) and builds dist/pdf first.
// The Linux free lane deliberately doesn't build it — warn-skip there.
if (process.env.CI && process.platform === 'darwin') {
throw new Error(`diagram gate prerequisites missing in CI: ${avail.reason}`);
}
// A visible skip, never a failure: ci-prereqs.test.ts is the CI tripwire for
// the build artifacts + poppler this gate needs; CI prints through the browse binary it builds.
test("diagram gate prerequisites are present", () => {
console.warn(`[skip] ${avail.reason}`);
});
}
+11 -20
View File
@@ -22,8 +22,8 @@
* Note: pdfimages -list is intentionally NOT used — macOS embeds color emoji as
* Type 3 fonts, so pdfimages lists nothing even on a correct render.
*
* Gating: runs only when the compiled binary + browse + pdffonts + pdftoppm are
* available AND a color-emoji font is installed for Chromium to fall back to.
* Gating: runs only when the compiled binary + a browser (Aside or browse) + pdffonts +
* pdftoppm are available AND a color-emoji font is installed to fall back to.
* In CI (process.env.CI set) missing prerequisites are a HARD FAILURE, not a
* skip — CI is expected to install poppler-utils + fonts-noto-color-emoji, so a
* silent skip there would let the tofu regression ship behind a green build.
@@ -36,11 +36,11 @@ import * as fs from "node:fs";
import * as path from "node:path";
import { resolvePopplerTool } from "../../src/pdftotext";
import { browserAvailable, NO_BROWSER_REASON } from "./browser-available";
const FIXTURE = path.resolve(__dirname, "../fixtures/emoji-gate.md");
const ROOT = path.resolve(__dirname, "../../..");
const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf");
const BROWSE_BIN = path.join(ROOT, "browse/dist/browse");
// Saturated-pixel floor. Measured ~1650 at 100dpi for the fixture's color
// emoji; a tofu render yields ~0. 200 sits well clear of both.
@@ -50,9 +50,9 @@ const SATURATED_PIXEL_FLOOR = 200;
const SATURATION_DELTA = 40;
// Per-child wall-clock bound. Bun's test timeout doesn't reliably interrupt a
// synchronous execFileSync, so each child gets its own ceiling — a wedged
// browser/poppler binary (or a hostile GSTACK_*_BIN override) fails instead of
// hanging the whole job.
const CHILD_TIMEOUT_MS = 25_000;
// browser session or poppler binary (or a hostile GSTACK_PDF*_BIN poppler override)
// fails instead of hanging the whole job.
const CHILD_TIMEOUT_MS = 60_000;
/** Is a color-emoji font available for Chromium to fall back to? */
function emojiFontAvailable(): boolean {
@@ -78,7 +78,8 @@ function emojiFontAvailable(): boolean {
function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string } {
if (!fs.existsSync(PDF_BIN)) return { ok: false, reason: `make-pdf binary missing (${PDF_BIN}). Run bun run build.` };
if (!fs.existsSync(BROWSE_BIN)) return { ok: false, reason: `browse binary missing (${BROWSE_BIN}).` };
// Aside (macOS) or gstack's own browse binary (what CI builds) — a skip only when neither exists.
if (!browserAvailable()) return { ok: false, reason: NO_BROWSER_REASON };
if (!fs.existsSync(FIXTURE)) return { ok: false, reason: `fixture missing (${FIXTURE}).` };
if (!resolvePopplerTool("pdffonts")) return { ok: false, reason: "pdffonts not found (install poppler-utils)." };
if (!resolvePopplerTool("pdftoppm")) return { ok: false, reason: "pdftoppm not found (install poppler-utils)." };
@@ -142,9 +143,6 @@ describe("emoji render gate", () => {
test.skipIf(!avail.ok)("emoji render as color glyphs, not tofu", () => {
if (!avail.ok) return; // type narrowing
// Private temp dir under /tmp: browse's validateOutputPath only allows
// /tmp and /private/tmp (not os.tmpdir()'s /var/folders), and mkdtemp
// dodges the predictable-path symlink/collision risk.
const workDir = fs.mkdtempSync("/tmp/make-pdf-emoji-gate-");
const outputPdf = path.join(workDir, "out.pdf");
const ppmPrefix = path.join(workDir, "page");
@@ -152,7 +150,6 @@ describe("emoji render gate", () => {
try {
execFileSync(PDF_BIN, ["generate", FIXTURE, outputPdf, "--quiet"], {
encoding: "utf8",
env: { ...process.env, BROWSE_BIN },
stdio: ["ignore", "pipe", "pipe"],
timeout: CHILD_TIMEOUT_MS,
});
@@ -185,15 +182,9 @@ describe("emoji render gate", () => {
}, 60000);
if (!avail.ok) {
// In CI, missing prerequisites are a hard failure — a silent skip would let
// the Linux tofu regression ship behind a green build. Locally, just warn.
test("emoji gate prerequisites are present (hard-required in CI)", () => {
// Hard-require only where the binary is expected: the make-pdf gate
// workflow is macOS-only (path-filtered) and builds dist/pdf first.
// The Linux free lane deliberately doesn't build it — warn-skip there.
if (process.env.CI && process.platform === 'darwin') {
throw new Error(`emoji gate prerequisites missing in CI: ${avail.reason}`);
}
// A visible skip, never a failure: ci-prereqs.test.ts is the CI tripwire for
// the build artifacts + poppler this gate needs; CI prints through the browse binary it builds.
test("emoji gate prerequisites are present", () => {
console.warn(`[skip] ${avail.reason}`);
});
}
+7 -11
View File
@@ -16,17 +16,19 @@ import { execFileSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { browserAvailable, NO_BROWSER_REASON } from "./browser-available";
const FIXTURE = path.resolve(__dirname, "../fixtures/diagram-gate.md");
const ROOT = path.resolve(__dirname, "../../..");
const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf");
const BROWSE_BIN = path.join(ROOT, "browse/dist/browse");
const BUNDLE = path.join(ROOT, "lib/diagram-render/dist/diagram-render.html");
const CHILD_TIMEOUT_MS = 60_000;
function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string } {
if (!fs.existsSync(PDF_BIN)) return { ok: false, reason: `make-pdf binary missing (${PDF_BIN}). Run bun run build.` };
if (!fs.existsSync(BROWSE_BIN)) return { ok: false, reason: `browse binary missing (${BROWSE_BIN}).` };
// Aside (macOS) or gstack's own browse binary (what CI builds) — a skip only when neither exists.
if (!browserAvailable()) return { ok: false, reason: NO_BROWSER_REASON };
if (!fs.existsSync(BUNDLE)) return { ok: false, reason: `diagram-render bundle missing (${BUNDLE}).` };
if (!fs.existsSync(FIXTURE)) return { ok: false, reason: `fixture missing (${FIXTURE}).` };
if (!Bun.which("unzip")) return { ok: false, reason: "unzip not found (needed for docx zip checks)." };
@@ -36,7 +38,6 @@ function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string }
function generate(to: string, outputPath: string): void {
execFileSync(PDF_BIN, ["generate", FIXTURE, outputPath, "--quiet", "--to", to], {
encoding: "utf8",
env: { ...process.env, BROWSE_BIN },
stdio: ["ignore", "pipe", "pipe"],
timeout: CHILD_TIMEOUT_MS,
});
@@ -109,7 +110,6 @@ describe("output format gate", () => {
try {
execFileSync(PDF_BIN, ["generate", FIXTURE, "--to", "epub"], {
encoding: "utf8",
env: { ...process.env, BROWSE_BIN },
stdio: ["ignore", "pipe", "pipe"],
timeout: CHILD_TIMEOUT_MS,
});
@@ -121,13 +121,9 @@ describe("output format gate", () => {
}, 60000);
if (!avail.ok) {
test("format gate prerequisites are present (hard-required in CI)", () => {
// Hard-require only where the binary is expected: the make-pdf gate
// workflow is macOS-only (path-filtered) and builds dist/pdf first.
// The Linux free lane deliberately doesn't build it — warn-skip there.
if (process.env.CI && process.platform === 'darwin') {
throw new Error(`format gate prerequisites missing in CI: ${avail.reason}`);
}
// A visible skip, never a failure: ci-prereqs.test.ts is the CI tripwire for
// the build artifacts + poppler this gate needs; CI prints through the browse binary it builds.
test("format gate prerequisites are present", () => {
console.warn(`[skip] ${avail.reason}`);
});
}
+7 -11
View File
@@ -11,7 +11,7 @@
* - wide mermaid with page=portrait fence → MUST stay portrait (veto)
*
* Also runs the --toc combo: Paged.js isn't shipped in v1 (TOC renders
* without page numbers, browse falls through after 3s), so named-page
* without page numbers, the print falls through after 3s), so named-page
* landscape must survive a --toc run unchanged. If Paged.js ever lands and
* re-paginates, this is the test that catches the interaction.
*/
@@ -22,18 +22,19 @@ import * as fs from "node:fs";
import * as path from "node:path";
import { resolvePopplerTool } from "../../src/pdftotext";
import { browserAvailable, NO_BROWSER_REASON } from "./browser-available";
const FIXTURE = path.resolve(__dirname, "../fixtures/landscape-gate.md");
const ROOT = path.resolve(__dirname, "../../..");
const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf");
const BROWSE_BIN = path.join(ROOT, "browse/dist/browse");
const BUNDLE = path.join(ROOT, "lib/diagram-render/dist/diagram-render.html");
const CHILD_TIMEOUT_MS = 60_000;
function prerequisitesAvailable(): { ok: true } | { ok: false; reason: string } {
if (!fs.existsSync(PDF_BIN)) return { ok: false, reason: `make-pdf binary missing (${PDF_BIN}). Run bun run build.` };
if (!fs.existsSync(BROWSE_BIN)) return { ok: false, reason: `browse binary missing (${BROWSE_BIN}).` };
// Aside (macOS) or gstack's own browse binary (what CI builds) — a skip only when neither exists.
if (!browserAvailable()) return { ok: false, reason: NO_BROWSER_REASON };
if (!fs.existsSync(BUNDLE)) return { ok: false, reason: `diagram-render bundle missing (${BUNDLE}).` };
if (!fs.existsSync(FIXTURE)) return { ok: false, reason: `fixture missing (${FIXTURE}).` };
if (!resolvePopplerTool("pdfinfo")) return { ok: false, reason: "pdfinfo not found (install poppler-utils)." };
@@ -66,7 +67,6 @@ const isLandscape = (b: PageBox) => b.width > b.height;
function generate(args: string[], outputPdf: string): void {
execFileSync(PDF_BIN, ["generate", FIXTURE, outputPdf, "--quiet", ...args], {
encoding: "utf8",
env: { ...process.env, BROWSE_BIN },
stdio: ["ignore", "pipe", "pipe"],
timeout: CHILD_TIMEOUT_MS,
});
@@ -141,13 +141,9 @@ describe("landscape promotion gate", () => {
}, 120000);
if (!avail.ok) {
test("landscape gate prerequisites are present (hard-required in CI)", () => {
// Hard-require only where the binary is expected: the make-pdf gate
// workflow is macOS-only (path-filtered) and builds dist/pdf first.
// The Linux free lane deliberately doesn't build it — warn-skip there.
if (process.env.CI && process.platform === 'darwin') {
throw new Error(`landscape gate prerequisites missing in CI: ${avail.reason}`);
}
// A visible skip, never a failure: ci-prereqs.test.ts is the CI tripwire for
// the build artifacts + poppler this gate needs; CI prints through the browse binary it builds.
test("landscape gate prerequisites are present", () => {
console.warn(`[skip] ${avail.reason}`);
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* Unit tests for the image width policy + conservative auto-landscape
* (image-policy.ts). Pure HTML-in/HTML-out no browse daemon.
* (image-policy.ts). Pure HTML-in/HTML-out, no browser.
*
* The promotion heuristic is deliberately conservative (eng-review P4):
* false negatives are cheap (add {page=landscape}), false positives feel
+24
View File
@@ -147,6 +147,30 @@ describe("findExecutable (pdftotext.ts)", () => {
test("returns null when no extension matches", () => {
expect(findExecutable("/nonexistent/path/to/nothing")).toBeNull();
});
// access(X_OK) is TRUE for directories (they carry the traverse bit), so a bare
// X_OK probe once resolved a docs folder as "the binary". Only regular files count.
test("rejects a DIRECTORY even though it passes access(X_OK)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-dir-"));
try {
fs.accessSync(dir, fs.constants.X_OK); // precondition: the bare probe passes
expect(findExecutable(dir)).toBeNull();
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("rejects a directory that shadows the binary name", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "mkpdf-shadow-"));
const shadow = path.join(base, "pdftotext");
fs.mkdirSync(shadow);
fs.writeFileSync(path.join(shadow, "README.md"), "# not a binary\n");
try {
expect(findExecutable(shadow)).toBeNull();
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
});
describe("resolvePdftotext (override resolution, v1.24-aligned)", () => {
@@ -1,6 +1,6 @@
/**
* Offline-posture sanitizer tests — raw-HTML fetch vectors beyond <img src>
* (which the image inliner owns). No Playwright, no PDF generation.
* (which the image inliner owns). No browser, no PDF generation.
*
* Regression for: <style>@import, inline style="…url(https://…)…", and
* <img srcset> surviving sanitizeUntrustedHtml, letting Chromium fetch
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* Renderer unit tests — pure-function assertions for render.ts, smartypants.ts,
* and print-css.ts. No Playwright, no PDF generation.
* and print-css.ts. No browser, no PDF generation.
*/
import { describe, expect, test } from "bun:test";