import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { detectType, load, render } from "pele/lazy"; import { canvasTextMeasurer } from "../components/markdown-diagrams/render"; import { diagramImageTemplate, DiagramImageError } from "../components/markdown-diagrams/svg-image"; import { OUTPUT_LIMIT, SOURCE_LIMIT, type DiagramInput, type DiagramReply } from "../components/markdown-diagrams/types"; const fonts: DiagramInput["fonts"] = { sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', mono: 'ui-monospace, "Cascadia Code", monospace', size: 14, }; const source = 'flowchart LR\n A["`**粗体** _italic_ 中文 😀`"] --> B[Result]'; let base: string; async function peleSvg(text: string, measurer: ReturnType = { width: (text) => text.length * 7 }): Promise { await load(detectType(text)); return render(text, { fontFamily: fonts.sans, fontFamilyMono: fonts.mono, fontSize: fonts.size, measurer, links: false, images: false, responsive: false, maxWidth: 600, maxEdges: 500, }).svg; } function documentSvg(body: string): string { return base.slice(0, base.indexOf(">") + 1) + body + ""; } function reject(svg: string, reason = "policy"): void { expect(() => diagramImageTemplate(svg, fonts)).toThrowError( expect.objectContaining({ reason }), ); } function canvasFixture() { const context = { font: "", measureText: vi.fn((text: string) => ({ width: text.length * 7 })), }; vi.stubGlobal("OffscreenCanvas", class { getContext() { return context; } }); return context; } beforeAll(async () => { base = await peleSvg(source); }); afterEach(() => { vi.unstubAllGlobals(); }); describe("Pele image-only output", () => { it.each([ source, "sequenceDiagram\n Alice->>Bob: 中文 and emoji 😀\n Note over Alice,Bob: two lines
second", "stateDiagram-v2\n [*] --> Active\n state Active {\n [*] --> Ready\n Ready --> [*]\n }", ])("accepts the published engine's measured geometries: %s", async (text) => { const svg = await peleSvg(text); const image = diagramImageTemplate(svg, fonts); expect(image.content).toContain(" { const image = diagramImageTemplate(await peleSvg(`${source}\n classDef measured font-size:18px,font-weight:bold,font-style:italic\n class B measured`), fonts); expect(image.style).toContain("--_w:bold"); expect(image.content).toContain("font-size:18px"); expect(image.content).toContain("font-style:italic"); expect(image.content).toContain('font-weight="var(--_w)"'); }); it.each([ 'flowchart LR\n A["H2O x2 under List key sample type"] --> B', 'sequenceDiagram\n Alice->>Bob: H2O x2 under List key sample type', 'stateDiagram-v2\n state "H2O x2 under List key sample type" as Active\n [*] --> Active', ])("retains measured subscript, superscript, underline and monospace runs: %s", async (text) => { const image = diagramImageTemplate(await peleSvg(text), fonts); const document = new DOMParser().parseFromString(`${image.content}`, "image/svg+xml"); expect(document.querySelector('tspan[baseline-shift="sub"][font-size="smaller"]')?.textContent).toBe("2"); expect(document.querySelector('tspan[baseline-shift="super"][font-size="smaller"]')?.textContent).toBe("2"); expect(document.querySelector('tspan[text-decoration="underline"]')?.textContent).toBe("under"); const mono = Array.from(document.querySelectorAll('tspan[font-family="var(--_fm)"]')); expect(mono.map((span) => span.textContent)).toEqual(["List", "key", "sample", "type"]); expect(mono[0].getAttribute("font-weight")).toBe("var(--_w)"); expect(mono[0].getAttribute("font-style")).toBe("italic"); }); it("preserves generic type text without interpreting it as markup", async () => { const image = diagramImageTemplate(await peleSvg('flowchart LR\n A["List"] --> B["Map"]'), fonts); expect(image.content).toContain("List<T>"); expect(image.content).toContain("Map<K, V>"); }); it("wraps Chinese labels without spaces while preserving the full text", async () => { const label = "接收用户请求并检查工作区权限保留中文长标签以及多语言自动换行"; const image = diagramImageTemplate(await peleSvg(`%%{init: {"flowchart":{"wrappingWidth":100}}}%%\nflowchart TD\n A["${label}"] --> B[完成]`), fonts); const document = new DOMParser().parseFromString(`${image.content}`, "image/svg+xml"); const lines = Array.from(document.querySelector('g[data-id="A"] text')!.querySelectorAll("tspan"), (span) => span.textContent ?? ""); expect(lines.length).toBeGreaterThan(1); expect(lines.join("")).toBe(label); for (const line of lines) expect(line.length * 7).toBeLessThanOrEqual(100); }); it.each([ "font-family:fantasy", "letter-spacing:4px", "word-spacing:1em", "font-size:2em", "font-size:smaller", "font-size:larger", "font-size:83.33%", "font-size:201px", "font-weight:600", "font-style:oblique", ])("rejects unmeasured author typography even alongside measured subscript: %s", async (authorStyle) => { reject(await peleSvg(`flowchart LR\n A["H2O"] --> B\n style A ${authorStyle}`), "unsupported"); }); it("does not promote author HTML attributes, scripts or resources into the image", async () => { const image = diagramImageTemplate(await peleSvg('flowchart LR\n A["safe foreign"] --> B\n click A "https://bad.test/click"'), fonts); expect(image.content).toContain('baseline-shift="sub" font-size="smaller">safe'); expect(image.content).toContain("<foreignObject>"); expect(image.content).not.toMatch(/<(?:script|image|foreignObject|a)\b|onclick|onerror|999em|bad\.test/i); }); it("preserves and resolves local marker/clip references and monospace attributes", () => { const image = diagramImageTemplate(documentSvg('code'), fonts); expect(image.content).toContain('marker-end="url(#arrow)"'); expect(image.content).toContain('style="clip-path:url(#clip)"'); expect(image.content).toContain('font-family="var(--_fm)"'); reject(documentSvg('')); reject(documentSvg('')); }); it("serializes XML and extracts an inert plain accessible label", () => { const image = diagramImageTemplate(documentSvg('A & B <img>中文\n description & "quoted"]]>'), fonts); expect(image.label).toBe("A & B . 中文 description"); expect(image.content).toContain("<script> & "quoted""); expect(image.content).not.toContain("alert(1)', '', '', '', 'link', '', '', '', '&unknown;', '', '', '', '', '', '', '', ])("rejects active/resource/unsupported XML or CSS: %s", (body) => { reject(documentSvg(body)); }); it("rejects DTD/entity declarations and processing instructions", () => { reject(']>' + documentSvg("&value;")); reject('' + base); }); it("bounds dimensions, finite geometry, element count and final UTF-8 bytes", () => { reject(base.replace(/width="\d+"/, 'width="8193"'), "limit"); reject(base.replace(/viewBox="[^"]+"/, 'viewBox="0 0 1 1"'), "limit"); reject(base.replace(/viewBox="[^"]+"/, 'viewBox="0 0 3000 3000"').replace(/width="\d+"/, 'width="3000"').replace(/height="\d+"/, 'height="3000"'), "limit"); reject(documentSvg(''), "limit"); reject(documentSvg("".repeat(10_000)), "limit"); const multibyte = documentSvg(`${"中".repeat(360_000)}`); expect(multibyte.length).toBeLessThan(OUTPUT_LIMIT); reject(multibyte, "limit"); reject(documentSvg(``), "limit"); }); }); describe("canvas-only typography", () => { it("uses the exact sans/mono size and shrinks sub/sup once without changing underline width", () => { const context = canvasFixture(); const measurer = canvasTextMeasurer(fonts); for (const [flags, expected] of [ [0, `18px ${fonts.sans}`], [1, `bold 18px ${fonts.sans}`], [2, `italic 18px ${fonts.sans}`], [4, `18px ${fonts.mono}`], [7, `italic bold 18px ${fonts.mono}`], [8, `15px ${fonts.sans}`], [16, `15px ${fonts.sans}`], [32, `18px ${fonts.sans}`], [47, `italic bold 15px ${fonts.mono}`], [55, `italic bold 15px ${fonts.mono}`], ] as const) { expect(measurer.width("中文 emoji 😀", 18, flags)).toBe(77); expect(context.font).toBe(expected); } }); it("measures actual engine mixed styles at their effective numeric author size", async () => { const context = canvasFixture(); const measured: { text: string; font: string }[] = []; context.measureText.mockImplementation((text) => { measured.push({ text, font: context.font }); return { width: text.length * 7 }; }); const svg = await peleSvg('flowchart LR\n A["plain sub sup under"]\n style A font-size:18px', canvasTextMeasurer(fonts)); expect(diagramImageTemplate(svg, fonts).content).toContain("font-size:18px"); expect(measured).toEqual(expect.arrayContaining([ { text: "sub", font: `italic bold 15px ${fonts.mono}` }, { text: "sup", font: `italic bold 15px ${fonts.mono}` }, { text: "under", font: `18px ${fonts.sans}` }, ])); }); it("fails explicitly without OffscreenCanvas rather than using approximate metrics", () => { vi.stubGlobal("OffscreenCanvas", undefined); expect(() => canvasTextMeasurer(fonts)).toThrowError(new DiagramImageError("capability")); }); }); describe("single-input Worker protocol", () => { async function run(text: string): Promise { vi.resetModules(); const replies: DiagramReply[] = []; const worker: { onmessage: ((event: MessageEvent) => Promise) | null; postMessage(reply: DiagramReply): void; } = { onmessage: null, postMessage: (reply) => { replies.push(reply); } }; vi.stubGlobal("self", worker); const canvas = canvasFixture(); canvas.measureText.mockImplementation((text) => { expect(replies.at(-1)?.kind).toBe("started"); return { width: text.length * 7 }; }); await import("../components/markdown-diagrams/pele.worker"); if (!worker.onmessage) throw new Error("Worker handler missing"); await worker.onmessage(new MessageEvent("message", { data: { source: text, width: 600, fonts }, })); expect(worker.onmessage).toBeNull(); return replies; } it("loads the actual engine, announces sync work, and returns only an image template", async () => { const replies = await run('---\ntitle: Supported frontmatter\nconfig:\n links: true\n images: true\n---\n%%{init: {"flowchart":{"wrappingWidth":120}}}%%\nflowchart LR\n A["中文 H2O x2 under List"] --> B\n click A "https://bad.test/"\n'); expect(replies.map((reply) => reply.kind)).toEqual(["started", "image"]); const image = replies[1]; if (image.kind !== "image") throw new Error("Image missing"); expect(image.template.content).toContain("Supported frontmatter"); expect(image.template.content).toContain('baseline-shift="sub" font-size="smaller"'); expect(image.template.content).toContain('baseline-shift="super" font-size="smaller"'); expect(image.template.content).toContain('text-decoration="underline"'); expect(image.template.content).toContain("List<T>"); expect(image.template.content).not.toMatch(/ { expect(await run("x".repeat(SOURCE_LIMIT + 1))).toEqual([{ kind: "failed", reason: "limit" }]); expect(await run("unknownDiagram A")).toEqual([{ kind: "failed", reason: "unsupported" }]); expect((await run("flowchart LR\n A[unclosed")).at(-1)).toEqual({ kind: "failed", reason: "syntax" }); const edges = Array.from({ length: 501 }, (_, i) => `A${i} --> A${i + 1}`).join("\n"); expect((await run(`flowchart LR\n${edges}`)).at(-1)).toEqual({ kind: "failed", reason: "limit" }); }); });