import mermaid from 'mermaid'; let currentTheme = ''; function configure(theme: string) { if (theme === currentTheme) return; currentTheme = theme; mermaid.initialize({ startOnLoad: false, theme: theme as any, securityLevel: 'loose', fontFamily: 'inherit', flowchart: { useMaxWidth: true, htmlLabels: true }, }); } let renderSeq = 0; export type RenderResult = { svg: string } | { error: string }; /** Render Mermaid source to an SVG string, capturing syntax errors. */ export async function renderMermaid(code: string, theme: string): Promise { configure(theme); if (!code.trim()) return { svg: '' }; const id = `mmx-render-${++renderSeq}`; try { const { svg } = await mermaid.render(id, code); return { svg }; } catch (e) { return { error: e instanceof Error ? e.message : String(e) }; } finally { // Mermaid may leave a stray measurement node behind on failure. document.getElementById(`d${id}`)?.remove(); } }