import { createMermaidPlugin } from '@pierre/words/mermaid'; import { createDomRenderer, createHtmlRenderer, type CodeHighlighterPlugin, type HtmlOptions, } from '@pierre/words/html'; // Transcripts carry text from models and tools, including whatever a tool // fetched, so nothing in them may run in this page. Words never passes raw // HTML through, and `prepareMarkdown` writes tag-shaped text as `<` first, // so it reads as the model wrote it rather than vanishing. Links keep only // web and mail schemes, and images become links instead of loading. /** 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; } } const AUTOLINK = /^<(?:[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*|[\w.!#$%&'*+/=?^`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)>/; // What may come before a block on its line: indentation and quote or list markers. const PREFIX = String.raw`^(?:[ \t>]|(?:[-*+]|\d{1,9}[.)])[ \t])*`; const FENCE = new RegExp(String.raw`${PREFIX}(\`{3,}|~{3,})(.*)$`); const FENCE_CLOSE = /^(?:[ \t]*>)*[ \t]*(`{3,}|~{3,})[ \t]*$/; const MATH_OPEN = new RegExp(String.raw`${PREFIX}(\$\$|\\\[)(.*)$`); const LINE_START = new RegExp(`${PREFIX}$`); // A line that may start a block of its own: a heading, a list item, a table // row, a thematic break, or a tag that would open an HTML block. A quote // starts one unless the line before is in the quote too. Code spans and // inline maths never cross such a line, and a delimiter left open before it // is escaped, so Words cannot pair it across the line either. const BLOCK_START = /^[ \t]*(?:#{1,6}(?:[ \t]|$)|[-*+][ \t]|\d{1,9}[.)][ \t]|\||(?:[-*_=][ \t]*){3,}$|<[A-Za-z/!?])/; const SINGLE_LINE = new RegExp( String.raw`${PREFIX}(?:#{1,6}(?:[ \t]|$)|\||(?:[-*_=][ \t]*){3,}$)`, ); const QUOTE = /^[ \t]*>/; const SPECIAL = /[\\`$<]/g; function startsBlock(line: string, previous: string): boolean { if (QUOTE.test(line)) return !QUOTE.test(previous); return BLOCK_START.test(line) || SINGLE_LINE.test(previous); } /** * Where a block sits: inside how many quotes, and the column its content * keeps when it is in a list item, else 0. */ interface Container { quotes: number; indent: number; } interface Fence extends Container { char: string; length: number; } /** `text` without up to `most` leading quote markers, and how many it had. */ function unquote(text: string, most = Infinity): [number, string] { let quotes = 0; for ( let marker; quotes < most && (marker = /^[ \t]*>[ \t]?/.exec(text)); quotes++ ) text = text.slice(marker[0].length); return [quotes, text]; } /** The container of a block whose line begins with `prefix`. */ function container(prefix: string): Container { const [quotes, inner] = unquote(prefix); return { quotes, indent: /[-*+]|\d[.)]/.test(inner) ? inner.length : 0 }; } /** Whether `line` is still inside `block`'s container. */ function within(block: Container, line: string): boolean { const [quotes, rest] = unquote(line, block.quotes); if (quotes < block.quotes) return false; return ( !block.indent || !rest.trim() || /^[ \t]*/.exec(rest)![0].length >= block.indent ); } /** The fence `line` opens, if it opens one. */ function opens(line: string): Fence | null { const match = FENCE.exec(line); if (!match || (match[1][0] === '`' && match[2].includes('`'))) return null; const prefix = line.slice(0, line.length - match[1].length - match[2].length); return { char: match[1][0], length: match[1].length, ...container(prefix) }; } /** Whether `line` closes `fence`. */ function closes(fence: Fence, line: string): boolean { const match = FENCE_CLOSE.exec(line); return ( !!match && match[1][0] === fence.char && match[1].length >= fence.length && unquote(line)[0] === fence.quotes ); } /** * The last line of the display maths block `lines[at]` opens, or -1. As in * Words, `$$` with no other dollar on its line opens one, closed by a line * ending in `$$`, or by the end of the text if no blank line comes first. * A `\[` line opens one closed by a line ending in `\]`. */ function mathBlock(lines: string[], at: number): number { const open = MATH_OPEN.exec(lines[at]); if ( !open || open[2].includes('$') || (open[1] === '\\[' && /\\\][ \t]*$/.test(open[2])) ) return -1; const close = open[1] === '$$' ? /(?= 0; at = text.indexOf(needle, at + 1) ) { let slashes = 0; while (text[at - 1 - slashes] === '\\') slashes++; if (slashes % 2 === 0) return at; } return -1; } /** Where the run of `char` starting at `at` ends. */ function runEnd(text: string, at: number, char: string): number { let end = at; while (text[end] === char) end++; return end; } /** The end of the code span or inline formula opened at `at`, or -1. */ function spanEnd(text: string, at: number, end: number): number { const length = end - at; if (text[at] === '`') { for (let from = end; ;) { const found = text.indexOf('`', from); if (found < 0) return -1; const after = runEnd(text, found, '`'); if (after - found === length) return after; from = after; } } if (length === 2) { const close = unescaped(text, '$$', end); return close < 0 ? -1 : close + 2; } // As in Pandoc: the next dollar closes it if no space comes before it and // no digit after; otherwise the opening one is plain text. if (length > 2 || /\s/.test(text[end] ?? '')) return -1; const close = unescaped(text, '$', end); return close > 0 && !/\s/.test(text[close - 1]) && !/\d/.test(text[close + 1] ?? '') ? close + 1 : -1; } /** * One paragraph, a stretch of lines no block starts within: tag-shaped `<` * outside code spans and maths as `<`, and `\(…\)` and a one-line * `\[…\]` in dollars. `open` keeps a code span or formula still open at the * end as it is, since a streamed reply has not closed it yet. */ function prepareParagraph(text: string, open: boolean): string { let out = ''; let at = 0; while (at < text.length) { SPECIAL.lastIndex = at; const plain = SPECIAL.exec(text)?.index ?? text.length; out += text.slice(at, plain); at = plain; if (at === text.length) break; const char = text[at]; if (char === '\\') { const next = text[at + 1]; const close = next === '(' || (next === '[' && LINE_START.test(text.slice(text.lastIndexOf('\n', at - 1) + 1, at))) ? unescaped(text, next === '(' ? '\\)' : '\\]', at + 2) : -1; const inner = close > at ? text.slice(at + 2, close).trim() : ''; // A dollar closes inline maths only with no digit after it. if ( inner && !/[$\n]/.test(inner) && !inner.endsWith('\\') && (next === '[' ? /^[ \t]*(?:\n|$)/.test(text.slice(close + 2)) : !/\d/.test(text[close + 2] ?? '')) ) { out += next === '(' ? `$${inner}$` : `$$${inner}$$`; at = close + 2; } else { out += text.slice(at, at + 2); at += 2; } } else if (char === '`' || char === '$') { const end = runEnd(text, at, char); const close = spanEnd(text, at, end); if (close > 0) { out += text.slice(at, close); at = close; } else if ( open && (char === '`' || (end - at < 3 && !/\s/.test(text[end] ?? '') && !text.includes('$', end))) ) { return out + text.slice(at); } else { // A delimiter read as text is escaped, so Words cannot pair it with // one this did not, or with a dollar written in for `\(`. out += `\\${char}`.repeat(end - at); at = end; } } else if (/[A-Za-z/!?]/.test(text[at + 1] ?? '')) { const link = AUTOLINK.exec(text.slice(at, at + 512))?.[0]; out += link ?? '<'; at += link?.length ?? 1; } else { out += char; at++; } } return out; } /** * `text` as Words should read it. Words drops raw HTML, which would lose the * `Vec` and `` that models write in prose, so tag-shaped text * outside code and maths is written as `<` and shows as written. It reads * maths only between dollars, so `\(…\)` and `\[…\]` become dollars too. * `streaming` leaves a code span or formula still open at the end as it is, * and holds back a final `<` until the next character says what it is. */ export function prepareMarkdown(text: string, streaming = false): string { return prepare(text, streaming).out; } /** * `prepareMarkdown`, and the length of `text` (`done`) and of its output * (`doneOut`) up to the last blank line outside a fence: no text added later * changes what comes before it. */ function prepare(text: string, streaming: boolean) { if (!/[<\\]/.test(text)) return { out: text, done: 0, doneOut: 0 }; const lines = text.split('\n'); const out: string[] = []; let paragraph: string[] = []; let fence: Fence | null = null; let read = 0; let written = 0; let done = 0; let doneOut = 0; const write = (...pieces: string[]) => { out.push(...pieces); for (const piece of pieces) written += piece.length + 1; }; const flush = (open: boolean) => { if (paragraph.length) write(prepareParagraph(paragraph.join('\n'), open)); paragraph = []; }; for (let at = 0; at < lines.length; read += lines[at].length + 1, at++) { const line = lines[at]; if (fence && within(fence, line)) { if (closes(fence, line)) fence = null; write(line); continue; } fence = opens(line); const math = fence ? -1 : mathBlock(lines, at); const last = at === lines.length - 1; if (fence || !line.trim()) { flush(streaming && !fence && last); write(line); if (!fence && !last) [done, doneOut] = [read + line.length + 1, written]; } else if (math >= 0) { flush(false); const block = lines.slice(at, math + 1); if (MATH_OPEN.exec(line)?.[1] === '\\[') { block[0] = line.replace('\\[', '$$$$'); block[block.length - 1] = block[block.length - 1].replace( /\\\]([ \t]*)$/, '$$$$$1', ); } write(...block); for (; at < math; at++) read += lines[at].length + 1; } else { if ( paragraph.length && startsBlock(line, paragraph[paragraph.length - 1]) ) flush(false); paragraph.push(line); } } flush(streaming); const prepared = out.join('\n'); return { out: streaming && prepared.endsWith('<') ? prepared.slice(0, -1) : prepared, done, doneOut, }; } /** * `prepareMarkdown` for a reply that grows as it streams: what a blank line * finished is prepared once, not again with every delta. */ export function preparer() { let source = ''; let prepared = ''; return (text: string, streaming: boolean) => { if (!text.startsWith(source)) source = prepared = ''; const rest = prepare(text.slice(source.length), streaming); const out = prepared + rest.out; source = text.slice(0, source.length + rest.done); prepared += rest.out.slice(0, rest.doneOut); return out; }; } /** A link URL Words may keep: an in-page footnote anchor or a safe address. */ function urlTransform(url: string, key: 'href' | 'src') { // An image's address is checked where it becomes a link, below. if (key === 'src' || url.startsWith('#')) return url; return safeHref(url); } const external = ' target="_blank" rel="noopener noreferrer"'; const attribute = (html: string, name: string) => new RegExp(`\\s${name}="([^"]*)"`).exec(html)?.[1]; type Hook = (html: string) => string; // HTML hooks: each gets and returns the HTML Words made for one element. const hooks: [RegExp, Record][] = [ [ /\]\(|\]\[|\]:|https?:|www\.|mailto:|@/i, { // A link whose address was refused keeps only its text. a: (html) => !/^]*href=/.test(html) ? html.replace(/^]*>|<\/a>$/g, '') : /^]*href="#/.test(html) ? html : html.replace(' { const src = attribute(html, 'src') ?? ''; const alt = attribute(html, 'alt') ?? ''; return safeHref(decodeEntities(src)) ? `${alt || src}` : alt; }, }, ], // 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. // A table has a delimiter row; a pipe alone is as likely |x| in maths. [/^[ \t>]*\|?[ \t]*:?-+:?[ \t]*\|/m, { td: proseCell, th: proseCell }], [ /\$\$|\\\[|math/, { // Display maths in a box of its own, which scrolls a formula too wide // (Markdown.svelte). It costs most while maths streams, so a streamed // reply goes without it until it ends. svg: (html) => /^]*data-markdown="math-display"/.test(html) ? `
${html}
` : html, }, ], ]; const hookSets = new Map | undefined>(); /** * The hooks `text` can need. Any hook makes Words format each update in full * rather than append to the open paragraph or fence, so a reply carries only * those its text calls for; equal sets are the same object. */ function components(text: string, streaming: boolean) { let key = 0; hooks.forEach(([test, set], bit) => { if (test.test(text) && !(streaming && set.svg)) key |= 1 << bit; }); if (!hookSets.has(key)) hookSets.set( key, key ? Object.assign( {}, ...hooks.filter((_, bit) => key & (1 << bit)).map(([, set]) => set), ) : undefined, ); return hookSets.get(key); } function proseCell(html: string) { const text = html.replace(/<[^>]*>/g, '').trim(); return /\s/.test(text) && text.length > 24 ? html.replace(/^ ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'" })[name] ?? '', ); } // Mermaid diagrams are drawn by Pele, loaded the first time a message holds // one and each diagram kind on first use; until then the block shows as code. // Pele draws from text the model wrote, so only drawing is kept of what it // returns: links, animation (which can set an href), style elements (which // would style the whole page) and foreign content are dropped too. type Pele = typeof import('pele/lazy'); type Purify = (typeof import('dompurify'))['default']; let pele: { draw: Pele; purify: Purify } | undefined; let peleLoad: Promise | undefined; const kindsLoading = new Set(); const FORBID = [ 'a', 'style', 'animate', 'animateMotion', 'animateTransform', 'set', 'image', 'use', 'foreignObject', ]; // Pele reads anything shaped like a tag in a label as markup, and keeps only // , , , and
: `Vec` would draw as "Vec". Any // other tag-shaped text is written with Mermaid's own escapes, which every // diagram kind reads as the characters; `<>` annotations are left. const KEPT_TAGS = new Set(['b', 'i', 'strong', 'em', 'br']); function escapeTags(source: string): string { return source.replace( /(?\n]*)>(?!>)/g, (tag, close, name, rest) => KEPT_TAGS.has(name.toLowerCase()) ? tag : `#lt;${close}${name}${rest}#gt;`, ); } /** Pele as Words' Mermaid plugin calls it; it throws until Pele can draw. */ const drawer = { render(source: string): { svg: string } { if (!pele) { peleLoad ??= Promise.all([import('pele/lazy'), import('dompurify')]).then( ([draw, purify]) => { pele = { draw, purify: purify.default }; redraw(); }, () => {}, ); throw new Error('Pele is loading'); } let kind = null; try { kind = pele.draw.detectType(source); } catch {} if (kind && !pele.draw.registered(kind)) { if (!kindsLoading.has(kind)) { kindsLoading.add(kind); void pele.draw.load(kind).then(redraw, () => {}); } throw new Error(`Pele is loading ${kind}`); } const svg = pele.purify.sanitize(pele.draw.render(escapeTags(source)).svg, { USE_PROFILES: { svg: true }, FORBID_TAGS: FORBID, }); if (!svg.startsWith(' | undefined; let highlighting: CodeHighlighterPlugin = { highlight() { highlightsLoad ??= Promise.all([ import('@pierre/words/highlights'), import('@pierre/highlights/themes/pierre-light'), import('@pierre/highlights/themes/pierre-dark'), ]).then( ([{ createHighlightsPlugin }, light, dark]) => { highlighting = createHighlightsPlugin({ themes: { light: light.default, dark: dark.default }, defaultColor: false, }); redraw(); }, () => {}, ); return null; }, }; const views = new Set(); /** * Draw again the blocks that waited for Pele or the highlighter, with new * plugins: Words keeps what it formatted for a finished block. */ function redraw() { diagrams = createMermaidPlugin(drawer); for (const view of views) view.refresh(); } const FENCED = new RegExp( String.raw`${PREFIX}(?:\`{3,}|~{3,})[ \t]*[\w+#.-]`, 'm', ); const MERMAID = new RegExp( String.raw`${PREFIX}(?:\`{3,}|~{3,})[ \t]*mermaid\b`, 'im', ); let made = 0; /** How Words renders `text`; `prefix` keeps footnote ids apart on the page. */ export function markdownOptions( text: string, prefix: string, streaming = false, ): HtmlOptions { return { math: true, lineNumbers: false, controls: { code: { copy: true, download: false } }, urlTransform, components: components(text, streaming), idPrefix: prefix, // Any plugin makes Words format every update in full, so only a reply // with a code block that names its language carries them. ...(FENCED.test(text) && { plugins: { code: highlighting, ...(MERMAID.test(text) && { mermaid: diagrams }), }, }), }; } interface View { refresh(): void; } /** * Markdown rendered into `root` and patched as `update` gives it more text: * a streamed reply reuses the blocks it finished and redraws only its end. */ export function markdownView(root: HTMLElement) { const prefix = `md${++made}-`; let text = ''; let streaming = false; let current = markdownOptions('', prefix); const renderer = createDomRenderer(root, current); const prepareGrowing = preparer(); const draw = () => { const next = markdownOptions(text, prefix, streaming); if ( next.components !== current.components || next.plugins?.code !== current.plugins?.code || next.plugins?.mermaid !== current.plugins?.mermaid ) renderer.configure((current = next)); renderer.update(prepareGrowing(text, streaming), streaming, streaming); }; const view: View = { refresh: () => current.plugins && draw() }; renderer.connect(); views.add(view); return { update(next: string, live: boolean) { text = next; streaming = live; draw(); }, destroy() { views.delete(view); renderer.disconnect(); }, }; } const MARK = '\uE000'; const LIST_ITEM = /^(?:[-*+]|\d{1,9}[.)])(?:\s|$)/; /** * The first line of each top-level block of a document, zero-based: a line at * the margin after a blank one, outside fences. A list keeps its items. */ function blockStarts(lines: string[]): number[] { const starts: number[] = []; let fence: Fence | null = null; let list = false; lines.forEach((line, index) => { if (fence && within(fence, line)) { if (closes(fence, line)) fence = null; return; } const begins = (index === 0 || !lines[index - 1].trim()) && /^\S/.test(line); if (begins && !(list && LIST_ITEM.test(line))) { starts.push(index); list = LIST_ITEM.test(line); } fence = opens(line); }); return starts; } /** * A document opened as a file, as one block per top-level element, each * carrying the lines it came from (`data-from`, `data-to`, one-based) and * marked `changed` when one of them is in `changed`. */ export function documentHtml( text: string, changed: ReadonlySet, prefix = 'doc-', ): string { const lines = text.split('\n'); const starts = blockStarts(lines); // Each block but the first follows a paragraph naming its index, which // the HTML is split at: Words parses the whole document once, so links // and footnotes defined anywhere in it still resolve. const blocks = new Map(starts.map((line, block) => [line, block])); const annotated = lines.flatMap((line, index) => { const block = blocks.get(index) ?? 0; return block > 0 ? [`${MARK}${block}`, '', line] : [line]; }); const formatter = createHtmlRenderer(markdownOptions(text, prefix)); const html = formatter.render( prepareMarkdown(annotated.join('\n')), false, ).html; formatter.dispose(); return html .split(new RegExp(`

${MARK}(\\d+)

\\n`)) .map((part, at, parts) => { if (at % 2 || !part.trim()) return ''; const block = at ? Number(parts[at - 1]) : 0; const from = (starts[block] ?? 0) + 1; let to = starts[block + 1] ?? lines.length; while (to > from && !lines[to - 1].trim()) to--; let touched = false; for (let n = from; n <= to && !touched; n++) touched = changed.has(n); return `
${part}
`; }) .join(''); } /** `documentHtml` rendered into `root`. Returns what removes it. */ export function renderDocument( root: HTMLElement, text: string, changed: ReadonlySet, ): () => void { const prefix = `doc${++made}-`; let revision = 0; // The document is one finished block to the DOM renderer, which still // patches the page and answers the code blocks' copy buttons. const renderer = createDomRenderer(root, markdownOptions(text, prefix), { configure() {}, dispose() {}, render() { const html = documentHtml(text, changed, prefix); return { html, stable: html, addition: html, pending: '', reset: true, revision: ++revision, }; }, }); const view: View = { refresh: () => renderer.update(text, false) }; renderer.connect(); renderer.update(text, false); if (FENCED.test(text)) views.add(view); return () => { views.delete(view); renderer.disconnect(); root.replaceChildren(); }; }