Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

markdown.ts

124 lines · 3.4 KB · TypeScript
/**
 * 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, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#39;')
}

function inlineFormat(line: string): string {
	line = line.replace(/`([^`]+)`/g, '<code>$1</code>')
	line = line.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
	line = line.replace(/__([^_]+)__/g, '<strong>$1</strong>')
	line = line.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')
	line = line.replace(/(?<!_)_([^_]+)_(?!_)/g, '<em>$1</em>')
	line = line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, href: string) => {
		const decoded = href.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'")
		if (/^https?:\/\//i.test(decoded)) {
			return `<a href="${href}" rel="noopener noreferrer" target="_blank">${text}</a>`
		}
		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(`<pre><code>${codeLines.join('\n')}</code></pre>`)
			continue
		}

		if (/^### /.test(line)) {
			out.push(`<h3>${inlineFormat(line.slice(4))}</h3>`)
			i++
			continue
		}
		if (/^## /.test(line)) {
			out.push(`<h2>${inlineFormat(line.slice(3))}</h2>`)
			i++
			continue
		}
		if (/^# /.test(line)) {
			out.push(`<h1>${inlineFormat(line.slice(2))}</h1>`)
			i++
			continue
		}

		if (/^&gt; /.test(line) || line === '&gt;') {
			const bqLines: string[] = []
			while (i < lines.length && (/^&gt; /.test(lines[i]!) || lines[i] === '&gt;')) {
				bqLines.push(lines[i]!.replace(/^&gt; ?/, ''))
				i++
			}
			out.push(`<blockquote>${bqLines.map(inlineFormat).join('<br>')}</blockquote>`)
			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(`<li><label><input type="checkbox" checked disabled> ${inlineFormat(taskChecked[1]!)}</label></li>`)
				} else if (taskUnchecked) {
					items.push(`<li><label><input type="checkbox" disabled> ${inlineFormat(taskUnchecked[1]!)}</label></li>`)
				} else {
					items.push(`<li>${inlineFormat(content)}</li>`)
				}
				i++
			}
			out.push(`<ul>${items.join('')}</ul>`)
			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(`<li>${inlineFormat(m[1]!)}</li>`)
				i++
			}
			out.push(`<ol>${items.join('')}</ol>`)
			continue
		}

		if (line.trim() === '') {
			i++
			continue
		}

		out.push(`<p>${inlineFormat(line)}</p>`)
		i++
	}

	return out.join('\n')
}