import { Fragment, type ReactNode } from 'react'; /** * Tiny dependency-free markdown renderer, scoped to what the EULA / PRIVACY * documents actually use: headings (#..####), horizontal rules, blockquotes, * ordered / unordered lists, fenced code blocks, paragraphs, and the inline * spans bold / italic / code / links. * * It renders to React elements (never dangerouslySetInnerHTML), so all text is * auto-escaped by React and the renderer cannot introduce XSS even though the * source text comes over the wire. Links are additionally restricted to * http/https/mailto; anything else renders as plain text. */ export function Markdown({ content }: { content: string }): ReactNode { const blocks = parseBlocks(content.replace(/\r\n?/g, '\n')); return (
{block.lines.map((l, i) => (); case 'ul': return ({renderInline(l)}
))}
{block.text}
);
case 'p':
return {renderInline(block.text)}
; } } // Inline spans: `code`, **bold**, *italic* / _italic_, [text](url). // // Scanned in ONE pass with a global regex (lastIndex advances), and every // span uses a *bounded* negated class (`{1,N}`). Both matter: a greedy // UNbounded negated class (`[^\]]+`) on bracket-/asterisk-dense text causes // O(n²) catastrophic backtracking and can hang the render thread on a large // doc. The caps are far larger than any real inline span; anything longer // renders literally rather than risking a hang. const INLINE_RE = /`[^`\n]{1,2048}`|\*\*[^*\n]{1,2048}\*\*|\*[^*\n]{1,2048}\*|_[^_\n]{1,2048}_|\[[^\]\n]{1,512}\]\([^)\s]{1,2048}\)/g; function renderInline(text: string): ReactNode[] { const out: ReactNode[] = []; const re = new RegExp(INLINE_RE.source, 'g'); // fresh instance: own lastIndex let last = 0; let key = 0; let m: RegExpExecArray | null; while ((m = re.exec(text)) !== null) { if (m.index > last) { out.push(text.slice(last, m.index)); } const tok = m[0]; if (tok.startsWith('`')) { out.push(
{tok.slice(1, -1)}
,
);
} else if (tok.startsWith('**')) {
out.push({renderInline(tok.slice(2, -2))});
} else if (tok.startsWith('*') || tok.startsWith('_')) {
out.push({renderInline(tok.slice(1, -1))});
} else {
// [label](href) ā tok already matched the bounded link shape.
const link = tok.match(/^\[([^\]]*)\]\(([^)\s]+)\)$/);
if (link) {
out.push(safeLink(link[2], link[1], key++));
} else {
out.push(tok);
}
}
last = m.index + tok.length;
}
if (last < text.length) {
out.push(text.slice(last));
}
return out;
}
function safeLink(href: string, label: string, key: number): ReactNode {
const ok = /^(https?:|mailto:)/i.test(href);
if (!ok) {
return