/** * A small, safe Markdown renderer for the bio: paragraphs, `#`–`###` headings, * `-`/`1.` lists, **bold**, *italic*, and [links](https://…). Raw HTML is * always escaped, and links only allow http(s), mailto, tel, or relative URLs. */ export function renderMarkdown(source: string): string { const blocks = source .replace(/\r\n?/g, '\n') .trim() .split(/\n{2,}/) return blocks.map(renderBlock).filter(Boolean).join('\n') } function renderBlock(block: string): string { const lines = block.split('\n').map((line) => line.trimEnd()) const heading = /^(#{1,3})\s+(.+)$/.exec(lines[0] ?? '') if (heading && lines.length === 1) { const level = heading[1]!.length + 1 return `${renderInline(heading[2]!)}` } if (lines.every((line) => /^\s*[-*]\s+/.test(line))) { const items = lines.map( (line) => `
  • ${renderInline(line.replace(/^\s*[-*]\s+/, ''))}
  • `, ) return `` } if (lines.every((line) => /^\s*\d+[.)]\s+/.test(line))) { const items = lines.map( (line) => `
  • ${renderInline(line.replace(/^\s*\d+[.)]\s+/, ''))}
  • `, ) return `
      ${items.join('')}
    ` } const text = lines.join('\n').trim() if (!text) return '' return `

    ${lines.map(renderInline).join('
    ')}

    ` } export function escapeHtml(value: string) { return value .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, ''') } function safeHref(raw: string): string | null { const href = raw.trim() if (/^(https?:|mailto:|tel:)/i.test(href)) return href if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return null if (href.startsWith('//')) return null return href } function renderInline(text: string): string { const tokens: Array = [] const stash = (html: string) => `\u0000${tokens.push(html) - 1}\u0000` let working = text.replace( /\[([^\]]+)\]\(([^)\s]+)\)/g, (match, label: string, href: string) => { const safe = safeHref(href) if (!safe) return match const external = /^https?:/i.test(safe) return stash( `${renderEmphasis(escapeHtml(label))}`, ) }, ) working = renderEmphasis(escapeHtml(working)) return working.replace( /\u0000(\d+)\u0000/g, (_m, index: string) => tokens[Number(index)] ?? '', ) } function renderEmphasis(escaped: string) { return escaped .replace(/\*\*(.+?)\*\*/g, '$1') .replace(/(^|[^\w*])\*(?!\s)(.+?)\*(?!\w)/g, '$1$2') .replace(/(^|[^\w])_(?!\s)(.+?)_(?!\w)/g, '$1$2') } /** Plain-text excerpt (for meta descriptions and teasers). */ export function markdownToText(source: string, maxLength = 200) { const plain = source .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') .replace(/[*_#>`]/g, '') .replace(/^\s*[-\d.)]+\s+/gm, '') .replace(/\s+/g, ' ') .trim() if (plain.length <= maxLength) return plain return `${plain.slice(0, maxLength - 1).replace(/\s+\S*$/, '')}…` }