/** * Safe markdown renderer for plan bodies. Escapes all HTML first, then applies * markdown formatting on the escaped text. Pure function, no DOM, no side effects. */ function esc(s: string): string { return s .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, ''') } function inlineFormat(line: string): string { line = line.replace(/`([^`]+)`/g, '$1') line = line.replace(/\*\*([^*]+)\*\*/g, '$1') line = line.replace(/__([^_]+)__/g, '$1') line = line.replace(/(?$1') line = line.replace(/(?$1') line = line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, href: string) => { const decoded = href.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'") if (/^https?:\/\//i.test(decoded)) { return `${text}` } return `${text} (${href})` }) return line } export function renderMarkdown(raw: string): string { if (!raw) return '' const escaped = esc(raw) const lines = escaped.split('\n') const out: string[] = [] let i = 0 while (i < lines.length) { const line = lines[i]! if (line.startsWith('```')) { const codeLines: string[] = [] i++ while (i < lines.length && !lines[i]!.startsWith('```')) { codeLines.push(lines[i]!) i++ } if (i < lines.length) i++ out.push(`
${codeLines.join('\n')}
`) continue } if (/^### /.test(line)) { out.push(`

${inlineFormat(line.slice(4))}

`) i++ continue } if (/^## /.test(line)) { out.push(`

${inlineFormat(line.slice(3))}

`) i++ continue } if (/^# /.test(line)) { out.push(`

${inlineFormat(line.slice(2))}

`) i++ continue } if (/^> /.test(line) || line === '>') { const bqLines: string[] = [] while (i < lines.length && (/^> /.test(lines[i]!) || lines[i] === '>')) { bqLines.push(lines[i]!.replace(/^> ?/, '')) i++ } out.push(`
${bqLines.map(inlineFormat).join('
')}
`) continue } const ulMatch = /^(\s*)[-*] (.*)$/.exec(line) if (ulMatch) { const items: string[] = [] while (i < lines.length) { const m = /^(\s*)[-*] (.*)$/.exec(lines[i]!) if (!m) break const content = m[2]! const taskUnchecked = /^\[ \] (.*)$/.exec(content) const taskChecked = /^\[x\] (.*)$/i.exec(content) if (taskChecked) { items.push(`
  • `) } else if (taskUnchecked) { items.push(`
  • `) } else { items.push(`
  • ${inlineFormat(content)}
  • `) } i++ } out.push(``) continue } const olMatch = /^\d+\. (.*)$/.exec(line) if (olMatch) { const items: string[] = [] while (i < lines.length) { const m = /^\d+\. (.*)$/.exec(lines[i]!) if (!m) break items.push(`
  • ${inlineFormat(m[1]!)}
  • `) i++ } out.push(`
      ${items.join('')}
    `) continue } if (line.trim() === '') { i++ continue } out.push(`

    ${inlineFormat(line)}

    `) i++ } return out.join('\n') }