import DOMPurify from 'dompurify'; import { Marked, Renderer, type TokenizerAndRendererExtension, type Tokens, } from 'marked'; // Transcripts carry text from models and tools, including whatever a tool // fetched, so nothing in them may run in this page: raw HTML is shown as text, // links keep only web and mail schemes, and images become links instead of // loading. DOMPurify then keeps only the tags and attributes listed below, so // a renderer mistake or a new marked token still cannot reach the page. const escapes: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; function escapeHtml(text: string): string { return text.replace(/[&<>"']/g, (char) => escapes[char]); } /** The URL if it is http, https or mailto, else null. */ export function safeHref(href: string): string | null { try { const url = new URL(href, 'https://invalid.example/'); return ['http:', 'https:', 'mailto:'].includes(url.protocol) && url.host !== 'invalid.example' ? url.href : null; } catch { return null; } } // Math and diagrams are left as placeholders whose text is their source, // shown as is until `enhance` (enhance.ts) draws them; KaTeX and Pele load // only when a message needs them. The source stays text, not an attribute: // DOMPurify drops attribute values holding "-->", which every diagram arrow is. interface Math extends Tokens.Generic { text: string; display: boolean; } function mathHtml(text: string, display: boolean) { const tag = display ? 'div' : 'span'; return `<${tag} class="math" data-display="${display ? 1 : 0}">${escapeHtml(text)}`; } // $$…$$ or \[…\] standing as a block. const mathBlock: TokenizerAndRendererExtension = { name: 'mathBlock', level: 'block', start: (src) => src.match(/\$\$|\\\[/)?.index, tokenizer(src) { const match = /^(?:\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\])[ \t]*(?:\n|$)/.exec(src); if (match) return { type: 'mathBlock', raw: match[0], text: (match[1] ?? match[2]).trim(), display: true, }; }, renderer: (token) => mathHtml((token as Math).text, true), }; // $…$, \(…\) or $$…$$ inside a line. A dollar amount is not maths: the // opening $ must touch its text, the closing one too, and no digit may // follow it ("$5 and $10" stays prose). const mathInline: TokenizerAndRendererExtension = { name: 'mathInline', level: 'inline', start: (src) => src.match(/\$|\\\(/)?.index, tokenizer(src) { const display = /^\$\$([^\n]+?)\$\$/.exec(src); if (display) return { type: 'mathInline', raw: display[0], text: display[1].trim(), display: true, }; const match = /^\$(?![\s$])((?:\\.|[^\\$\n])+?)(? mathHtml((token as Math).text, (token as Math).display), }; const marked = new Marked({ extensions: [mathBlock, mathInline], gfm: true, breaks: false, renderer: { html({ text }: Tokens.HTML | Tokens.Tag) { return escapeHtml(text); }, link({ href, tokens }: Tokens.Link) { const text = this.parser.parseInline(tokens); const safe = safeHref(href); return safe ? `${text}` : text; }, code({ text, lang }: Tokens.Code) { if (lang?.trim().toLowerCase() !== 'mermaid') return false; return `
${escapeHtml(text)}
`; }, // A cell of prose keeps a reading width (Markdown.svelte), so a narrow // chat scrolls a table sideways instead of wrapping it a few letters a line. tablecell(token: Tokens.TableCell) { const cell = Renderer.prototype.tablecell.call(this, token); return /\s/.test(token.text.trim()) && token.text.length > 24 ? cell.replace(/^${escapeHtml(text || safe)}` : escapeHtml(text); }, }, }); const allowed = { ALLOWED_TAGS: [ 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'em', 'strong', 'del', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'span', 'input', ], // data-display, which tells enhance.ts maths from display maths, passes as data-*. ALLOWED_ATTR: [ 'href', 'target', 'rel', 'class', 'start', 'align', 'type', 'checked', 'disabled', ], ALLOWED_URI_REGEXP: /^(?:https?|mailto):/i, }; /** * Recent renders by source, most recent last: a chat mounting again (another * board, a window reopened) shows the same messages. Bounded by characters, * since a streamed reply passes through as thousands of ever longer texts. */ const rendered = new Map(); let renderedSize = 0; const RENDERED_CHARS = 4_000_000; export function renderMarkdown(text: string): string { const known = rendered.get(text); if (known !== undefined) { rendered.delete(text); rendered.set(text, known); return known; } const html = DOMPurify.sanitize( marked.parse(text, { async: false }), allowed, ); rendered.set(text, html); renderedSize += text.length + html.length; for (const [oldest, gone] of rendered) { if (renderedSize <= RENDERED_CHARS) break; rendered.delete(oldest); renderedSize -= oldest.length + gone.length; } return html; } /** * A document opened as a file, as one block per top-level element, each * carrying the lines it came from (`data-from`, `data-to`) and marked * `changed` when one of them is in `changed`. */ export function renderDocument( text: string, changed: ReadonlySet, ): string { const tokens = marked.lexer(text); let line = 1; let html = ''; for (const token of tokens) { const from = line; line += token.raw.split('\n').length - 1; if (token.type === 'space') continue; const to = Math.max(from, line - (token.raw.endsWith('\n') ? 1 : 0)); let touched = false; for (let n = from; n <= to && !touched; n++) touched = changed.has(n); html += `
${marked.parser(Object.assign([token], { links: tokens.links }))}
`; } return DOMPurify.sanitize(html, allowed); }