import type { MarkdownIt } from "markdown-it"; import { escapeHtml } from "../html.ts"; import { type VizType, validate } from "./schemas.ts"; const VIZ_PREFIX = "viz-"; const SUPPORTED_TYPES: ReadonlySet = new Set(["graph", "sunburst"]); export interface VizPluginEnv { hasViz?: boolean; } function vizError(message: string): string { return `
${escapeHtml(message)}
\n`; } function renderVizBlock(info: string, content: string, env: unknown): string { const vizType = info.slice(VIZ_PREFIX.length) as VizType; if (!SUPPORTED_TYPES.has(vizType)) { return `
Unknown visualization type: ${escapeHtml(vizType)}
\n`; } const raw = content.trimEnd(); const result = validate(vizType, raw); if (!result.ok) { return vizError(`Invalid viz data: ${result.error ?? "unknown error"}`); } // Buffer, not btoa: btoa throws on any code point above U+00FF, and the // hydrator decodes these bytes back as UTF-8. const encoded = Buffer.from(raw, "utf8").toString("base64"); (env as VizPluginEnv).hasViz = true; return `
\n`; } export function vizPlugin(md: MarkdownIt): void { const defaultFence = md.renderer.rules["fence"] ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); md.renderer.rules["fence"] = (tokens, idx, options, env, self) => { const token = tokens[idx]; if (!token) return defaultFence(tokens, idx, options, env, self); const info = token.info.trim(); if (!info.startsWith(VIZ_PREFIX)) { return defaultFence(tokens, idx, options, env, self); } try { return renderVizBlock(info, token.content, env); } catch (err) { // A throw here escapes renderMarkdown and 500s the note on every // request, so one bad block must never take the page down. return vizError( `Viz render failed: ${err instanceof Error ? err.message : String(err)}`, ); } }; }