/**
* 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(`${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(line)}
`) i++ } return out.join('\n') }