/** * Turns `docs/using-fablewright.md` into HTML for `/help`. It is not a Markdown * library: it handles only the shapes the guide uses, and every character is * escaped before any rule runs, so a document is text and never markup. Emphasis * skips code spans, and its underscore form needs a word boundary, so `snake_case` * stays literal. */ const ESCAPES: Record = { '&': '&', '<': '<', '>': '>', '"': '"' }; function escapeHtml(text: string): string { return text.replace(/[&<>"]/g, (character) => ESCAPES[character]); } const GUIDES_URL = 'https://tangled.org/katsuricata.com/Fablewright/blob/main/docs/'; const COMPANION_GUIDES = new Set([ 'installation.md', 'operations.md', 'recovery.md', 'import-export.md' ]); function guideHref(href: string): string | null { if (/^https?:\/\//.test(href)) return href; const file = href.split('#', 1)[0]; return COMPANION_GUIDES.has(file) ? `${GUIDES_URL}${href}` : null; } function inline(text: string): string { let html = escapeHtml(text); html = html.replace(/`([^`]+)`/g, '$1'); html = html.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_whole, label: string, href: string) => { const destination = guideHref(href); return destination ? `${label}` : label; }); return html .split(/([\s\S]*?<\/code>)/) .map(emphasise) .join(''); } function emphasise(part: string): string { if (part.startsWith('')) return part; return part .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*\s][^*]*)\*/g, '$1') .replace(/(?$1'); } export function renderGuide(markdown: string): string { const lines = markdown.replace(/\r\n/g, '\n').split('\n'); const out: string[] = []; let paragraph: string[] = []; let list: { ordered: boolean; items: string[] } | null = null; function flushParagraph() { if (paragraph.length === 0) return; out.push(`

${inline(paragraph.join(' '))}

`); paragraph = []; } function flushList() { if (!list) return; const tag = list.ordered ? 'ol' : 'ul'; const items = list.items.map((item) => `
  • ${inline(item)}
  • `).join(''); out.push(`<${tag}>${items}`); list = null; } for (const line of lines) { const trimmed = line.trim(); if (trimmed === '') { flushParagraph(); flushList(); continue; } const heading = /^(#{1,3})\s+(.*)$/.exec(trimmed); if (heading) { flushParagraph(); flushList(); const level = heading[1].length; out.push(`${inline(heading[2])}`); continue; } const bullet = /^[-*]\s+(.*)$/.exec(line); const numbered = /^\d+\.\s+(.*)$/.exec(line); if (bullet || numbered) { flushParagraph(); const ordered = numbered !== null; const text = (bullet ?? numbered)![1]; if (!list || list.ordered !== ordered) { flushList(); list = { ordered, items: [] }; } list.items.push(text); continue; } // The guide wraps its lines; a line indented inside an item continues it. if (list && /^\s{2,}/.test(line)) { list.items[list.items.length - 1] += ` ${trimmed}`; continue; } flushList(); paragraph.push(trimmed); } flushParagraph(); flushList(); return out.join('\n'); }