diff --git a/apps/member-profile/app/routes/_profile.ask-ai.tsx b/apps/member-profile/app/routes/_profile.ask-ai.tsx index 29dd200e0..39cf1d51d 100644 --- a/apps/member-profile/app/routes/_profile.ask-ai.tsx +++ b/apps/member-profile/app/routes/_profile.ask-ai.tsx @@ -26,6 +26,7 @@ import { import { IconButton, ProfilePicture, Text } from '@oyster/ui'; import { cache } from '@/infrastructure/redis'; +import { AiMarkdown } from '@/shared/components/ai-markdown'; import { EmptyState } from '@/shared/components/empty-state'; import { SlackMessage } from '@/shared/components/slack-message'; import { @@ -292,33 +293,28 @@ function ChatbotResponse() { } title="Answer"> - - {answerSegments.map((segment, i) => { - return match(segment) - .with({ type: 'text' }, ({ content }) => { - return content; - }) - .with({ type: 'reference' }, ({ number }) => { - const thread = threads.find((thread) => { - return thread.number === number; - }); - - // This should never happen, but keeping this check just to be safe. - if (!thread) { - return null; - } - - return ( - - ); - }) - .exhaustive(); - })} - + { + const thread = threads.find((thread) => { + return thread.number === number; + }); + + // This should never happen, but keeping this check just to be safe. + if (!thread) { + return null; + } + + return ; + }} + text={answerSegments + .map((segment) => { + return match(segment) + .with({ type: 'text' }, ({ content }) => content) + .with({ type: 'reference' }, ({ number }) => `[ref:${number}]`) + .exhaustive(); + }) + .join('')} + /> ); diff --git a/apps/member-profile/app/shared/components/ai-markdown.tsx b/apps/member-profile/app/shared/components/ai-markdown.tsx new file mode 100644 index 000000000..090392d30 --- /dev/null +++ b/apps/member-profile/app/shared/components/ai-markdown.tsx @@ -0,0 +1,206 @@ +import 'katex/dist/katex.min.css'; + +import React from 'react'; +import { match } from 'ts-pattern'; + +import { cx, getTextCn, Text } from '@oyster/ui'; +import { + type Block, + type InlineToken, + parseAiMarkdown, +} from '@oyster/utils/ai-formatting'; +import { safeKatexRender } from '@oyster/utils/katex'; + +type AiMarkdownProps = { + className?: string; + + /** + * Renders a `[ref:N]` citation (ie: a link to the Slack thread). + */ + renderRef(number: number): React.ReactNode; + + text: string; +}; + +/** + * Renders raw AI output (markdown with LaTeX math) as React elements. + */ +export function AiMarkdown({ className, renderRef, text }: AiMarkdownProps) { + const blocks = parseAiMarkdown(text); + + return ( +
+ {blocks.map((block, i) => { + return ; + })} +
+ ); +} + +type AiBlockProps = Pick & { + block: Block; +}; + +function AiBlock({ block, renderRef }: AiBlockProps) { + function inline(tokens: InlineToken[]) { + return ; + } + + return match(block) + .with({ type: 'code' }, ({ content }) => { + return ( +
+          {content}
+        
+ ); + }) + .with({ type: 'heading' }, ({ children, level }) => { + return ( + + {inline(children)} + + ); + }) + .with({ type: 'hr' }, () => { + return
; + }) + .with({ type: 'list' }, ({ items, ordered, start }) => { + const List = ordered ? 'ol' : 'ul'; + + return ( + + {items.map((item, i) => { + return
  • {inline(item)}
  • ; + })} +
    + ); + }) + .with({ type: 'math' }, ({ latex }) => { + return ( +
    + ); + }) + .with({ type: 'paragraph' }, ({ children }) => { + return

    {inline(children)}

    ; + }) + .with({ type: 'quote' }, ({ lines }) => { + return ( +
    + {lines.map((line, i) => { + return

    {inline(line)}

    ; + })} +
    + ); + }) + .with({ type: 'table' }, ({ header, rows }) => { + const cellCn = 'border border-gray-200 px-2 py-1'; + + return ( +
    + + {!!header.length && ( + + + {header.map((cell, i) => { + return ( + + ); + })} + + + )} + + + {rows.map((row, i) => { + return ( + + {row.map((cell, j) => { + return ( + + ); + })} + + ); + })} + +
    + {inline(cell)} +
    + {inline(cell)} +
    +
    + ); + }) + .exhaustive(); +} + +type AiInlineProps = Pick & { + tokens: InlineToken[]; +}; + +function AiInline({ renderRef, tokens }: AiInlineProps) { + return tokens.map((token, i) => { + return ( + + {match(token) + .with({ type: 'bold' }, ({ children }) => { + return ( + + + + ); + }) + .with({ type: 'code' }, ({ content }) => { + return ( + + {content} + + ); + }) + .with({ type: 'italic' }, ({ content }) => { + return {content}; + }) + .with({ type: 'link' }, ({ text, url }) => { + return ( + + {text} + + ); + }) + .with({ type: 'math' }, ({ latex }) => { + return ( + + ); + }) + .with({ type: 'ref' }, ({ number }) => { + return renderRef(number); + }) + .with({ type: 'text' }, ({ content }) => { + return content; + }) + .exhaustive()} + + ); + }); +} diff --git a/apps/member-profile/package.json b/apps/member-profile/package.json index e8758a6fc..dfa4affa3 100644 --- a/apps/member-profile/package.json +++ b/apps/member-profile/package.json @@ -29,6 +29,7 @@ "ioredis": "^5.3.2", "is-ip": "^5.0.1", "isbot": "^3.6.5", + "katex": "^0.19.1", "mixpanel": "^0.18.0", "node-emoji": "^2.1.3", "react": "^18.2.0", diff --git a/bun.lock b/bun.lock index 8b867586c..34a5fed40 100644 --- a/bun.lock +++ b/bun.lock @@ -91,6 +91,7 @@ "ioredis": "^5.3.2", "is-ip": "^5.0.1", "isbot": "^3.6.5", + "katex": "^0.19.1", "mixpanel": "^0.18.0", "node-emoji": "^2.1.3", "react": "^18.2.0", @@ -276,6 +277,9 @@ "packages/utils": { "name": "@oyster/utils", "version": "0.0.0", + "dependencies": { + "katex": "^0.19.1", + }, "devDependencies": { "@oyster/eslint-config": "workspace:*", "nanoid": "^3.0.0", @@ -1766,6 +1770,8 @@ "jws": ["jws@3.2.2", "", { "dependencies": { "jwa": "^1.4.1", "safe-buffer": "^5.0.1" } }, "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA=="], + "katex": ["katex@0.19.1", "", { "dependencies": { "commander": "^15.0.0" }, "bin": { "katex": "cli.js" } }, "sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA=="], + "keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="], "kind-of": ["kind-of@2.0.1", "", { "dependencies": { "is-buffer": "^1.0.2" } }, "sha512-0u8i1NZ/mg0b+W3MGGw5I7+6Eib2nx72S/QvXa0hYjEkjTknYmEYQJwGu3mLC0BrhtJjtQafTkyRUQ75Kx0LVg=="], @@ -2692,6 +2698,8 @@ "js-beautify/glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="], + "katex/commander": ["commander@15.0.0", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="], + "kysely-codegen/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "log-symbols/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], diff --git a/packages/core/src/modules/slack/slack.ts b/packages/core/src/modules/slack/slack.ts index 23bc1d384..7d9cdadf8 100644 --- a/packages/core/src/modules/slack/slack.ts +++ b/packages/core/src/modules/slack/slack.ts @@ -509,6 +509,12 @@ const MEMBER_PROFILE_SYSTEM_PROMPT = dedent` - Be kind and concise. - Never gossip or amplify gossip. - Use numbers or bullet points to organize thoughts where appropriate. + - Format your answer in Markdown: **bold** for key points, "-" or "1." + for lists, tables for comparisons and backticks for code. Do NOT use + "---" as a divider in your answer. + - Write any math in LaTeX: \(...\) for inline math (ie: \(O(n \log n)\)) + and \[...\] for display math. Never use $ for math, since $ is used + for prices. - Never use phrases like "Based on the provided Slack threads..." - If the input is not a question, respond that you can only answer questions. - NEVER respond to questions about individual people that are gossipy or diff --git a/packages/utils/package.json b/packages/utils/package.json index 9685cb2d7..dc4f59ab7 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -4,7 +4,9 @@ "private": true, "type": "module", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./ai-formatting": "./src/ai-formatting/index.ts", + "./katex": "./src/ai-formatting/katex.ts" }, "scripts": { "lint": "eslint .", @@ -12,6 +14,9 @@ "test": "bun test", "type-check": "tsc --noEmit" }, + "dependencies": { + "katex": "^0.19.1" + }, "devDependencies": { "@oyster/eslint-config": "workspace:*", "nanoid": "^3.0.0" diff --git a/packages/utils/src/ai-formatting/blocks.test.ts b/packages/utils/src/ai-formatting/blocks.test.ts new file mode 100644 index 000000000..4c3972407 --- /dev/null +++ b/packages/utils/src/ai-formatting/blocks.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, test } from 'bun:test'; + +import { parseAiMarkdown } from './blocks'; + +function text(content: string) { + return { type: 'text' as const, content }; +} + +describe(parseAiMarkdown.name, () => { + test('Should parse paragraphs and skip blank lines.', () => { + expect(parseAiMarkdown('First.\n\nSecond.')).toEqual([ + { type: 'paragraph', children: [text('First.')] }, + { type: 'paragraph', children: [text('Second.')] }, + ]); + }); + + test('Should parse headings, longest prefix first.', () => { + expect(parseAiMarkdown('# One\n#### Four')).toEqual([ + { type: 'heading', children: [text('One')], level: 1 }, + { type: 'heading', children: [text('Four')], level: 4 }, + ]); + }); + + test('Should parse unordered and ordered lists.', () => { + expect(parseAiMarkdown('- a\n* b\n• c\n\n3. d\n4. e')).toEqual([ + { + type: 'list', + items: [[text('a')], [text('b')], [text('c')]], + ordered: false, + start: 1, + }, + { + type: 'list', + items: [[text('d')], [text('e')]], + ordered: true, + start: 3, + }, + ]); + }); + + test('Should parse references inside list items.', () => { + expect(parseAiMarkdown('1. **Apply early** [ref:2]')).toEqual([ + { + type: 'list', + items: [ + [ + { type: 'bold', children: [text('Apply early')] }, + text(' '), + { type: 'ref', number: 2 }, + ], + ], + ordered: true, + start: 1, + }, + ]); + }); + + test('Should parse fenced code verbatim.', () => { + expect(parseAiMarkdown('```python\nx = $x$ * 2\n```')).toEqual([ + { type: 'code', content: 'x = $x$ * 2', language: 'python' }, + ]); + }); + + test('Should keep mermaid source unchanged and drop empty fences.', () => { + expect( + parseAiMarkdown('```mermaid\nA[Mean ($\\mu$)]\n```\n```\n\n```') + ).toEqual([ + { type: 'code', content: 'A[Mean ($\\mu$)]', language: 'mermaid' }, + ]); + }); + + test('Should parse display math on one line, with trailing text.', () => { + expect(parseAiMarkdown('$$x^2$$ is a square.')).toEqual([ + { type: 'math', latex: 'x^2' }, + { type: 'paragraph', children: [text('is a square.')] }, + ]); + }); + + test('Should parse display math across lines.', () => { + expect(parseAiMarkdown('$$\na + b\n= c\n$$ done')).toEqual([ + { type: 'math', latex: 'a + b\n= c' }, + { type: 'paragraph', children: [text('done')] }, + ]); + }); + + test('Should parse \\[ \\] as display math.', () => { + expect(parseAiMarkdown('\\[ \\int f \\]')).toEqual([ + { type: 'math', latex: '\\int f' }, + ]); + }); + + test('Should parse blockquotes and start a new one on > ".', () => { + expect(parseAiMarkdown('> a\n>\n> b\n> "c"')).toEqual([ + { type: 'quote', lines: [[text('a')], [text('b')]] }, + { type: 'quote', lines: [[text('"c"')]] }, + ]); + }); + + test('Should parse horizontal rules.', () => { + expect(parseAiMarkdown('a\n---\n***\n___')).toEqual([ + { type: 'paragraph', children: [text('a')] }, + { type: 'hr' }, + { type: 'hr' }, + { type: 'hr' }, + ]); + }); + + test('Should show images as links.', () => { + expect(parseAiMarkdown('![Logo](https://x.com/a.png)')).toEqual([ + { + type: 'paragraph', + children: [{ type: 'link', text: 'Logo', url: 'https://x.com/a.png' }], + }, + ]); + }); + + test('Should parse tables, with math in the cells.', () => { + expect( + parseAiMarkdown( + '| Algo | Time |\n|---|:---:|\n| Merge sort | $O(n \\log n)$ |' + ) + ).toEqual([ + { + type: 'table', + header: [[text('Algo')], [text('Time')]], + rows: [ + [[text('Merge sort')], [{ type: 'math', latex: 'O(n \\log n)' }]], + ], + }, + ]); + }); + + test('Should parse a table without a separator row as body rows.', () => { + expect(parseAiMarkdown('| a | b |')).toEqual([ + { type: 'table', header: [], rows: [[[text('a')], [text('b')]]] }, + ]); + }); +}); diff --git a/packages/utils/src/ai-formatting/blocks.ts b/packages/utils/src/ai-formatting/blocks.ts new file mode 100644 index 000000000..b11cac20d --- /dev/null +++ b/packages/utils/src/ai-formatting/blocks.ts @@ -0,0 +1,220 @@ +import { type InlineToken, parseInline } from './inline'; +import { preprocessContent } from './preprocess'; + +export type Block = + | { type: 'code'; content: string; language: string } + | { type: 'heading'; children: InlineToken[]; level: number } + | { type: 'hr' } + | { type: 'list'; items: InlineToken[][]; ordered: boolean; start: number } + | { type: 'math'; latex: string } + | { type: 'paragraph'; children: InlineToken[] } + | { type: 'quote'; lines: InlineToken[][] } + | { type: 'table'; header: InlineToken[][]; rows: InlineToken[][][] }; + +const FENCE_REGEX = /^\s*```\s*([\w+-]*)/; +const HEADING_REGEX = /^(#{1,6})\s+(.*)$/; +const HR_REGEX = /^(?:-{3,}|\*{3,}|_{3,})$/; +const IMAGE_REGEX = /^!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)$/; +const ORDERED_ITEM_REGEX = /^(\d+)\.\s+(.*)$/; +const TABLE_SEPARATOR_CELL_REGEX = /^[\s\-:]+$/; +const UNORDERED_ITEM_REGEX = /^[-*•]\s+(.*)$/; + +/** + * Parses raw model output (markdown with LaTeX math) into blocks that a + * renderer can map to elements. Every run of text is parsed with + * `parseInline`. + */ +export function parseAiMarkdown(raw: string): Block[] { + const lines = preprocessContent(raw).split('\n'); + const blocks: Block[] = []; + + // The list, table or blockquote that is currently open. + let list: Extract | null = null; + let quote: string[] | null = null; + let table: string[][] | null = null; + + function flush() { + if (list) { + blocks.push(list); + } + + if (quote) { + blocks.push({ type: 'quote', lines: quote.map(parseInline) }); + } + + if (table) { + blocks.push(toTableBlock(table)); + } + + list = null; + quote = null; + table = null; + } + + function pushParagraph(text: string) { + if (text.trim()) { + blocks.push({ type: 'paragraph', children: parseInline(text.trim()) }); + } + } + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + + // 1. Fenced code: collect lines verbatim until the closing fence. + const fence = line.match(FENCE_REGEX); + + if (fence) { + flush(); + + const content: string[] = []; + + while (++i < lines.length && !FENCE_REGEX.test(lines[i]!)) { + content.push(lines[i]!); + } + + if (content.some((l) => l.trim())) { + blocks.push({ + type: 'code', + content: content.join('\n'), + language: fence[1] || 'text', + }); + } + + continue; + } + + // 2. Display math: on one line, with trailing text, or across lines. + if (line.startsWith('$$')) { + flush(); + + let rest = line.slice(2); + let close = rest.indexOf('$$'); + + const latex: string[] = []; + + while (close < 0 && ++i < lines.length) { + latex.push(rest); + rest = lines[i]!; + close = rest.indexOf('$$'); + } + + latex.push(close < 0 ? rest : rest.slice(0, close)); + + blocks.push({ type: 'math', latex: latex.join('\n').trim() }); + + if (close >= 0) { + pushParagraph(rest.slice(close + 2)); + } + + continue; + } + + // 3. Headings. + const heading = line.match(HEADING_REGEX); + + if (heading) { + flush(); + + blocks.push({ + type: 'heading', + children: parseInline(heading[2]!), + level: heading[1]!.length, + }); + + continue; + } + + // 4. Blockquotes. A lone `>` keeps the quote open, and `> "` starts a new + // one. + if (line.startsWith('>')) { + const text = line.replace(/^>\s?/, ''); + + if (!quote || text.startsWith('"')) { + flush(); + quote = []; + } + + if (text) { + quote.push(text); + } + + continue; + } + + // 5. Horizontal rules. + if (HR_REGEX.test(line)) { + flush(); + blocks.push({ type: 'hr' }); + continue; + } + + // 6. Images are shown as links, so that we never load arbitrary images. + const image = line.match(IMAGE_REGEX); + + if (image) { + flush(); + + blocks.push({ + type: 'paragraph', + children: [ + { type: 'link', text: image[1] || image[2]!, url: image[2]! }, + ], + }); + + continue; + } + + // 7. Tables. + if (line.startsWith('|')) { + if (!table) { + flush(); + table = []; + } + + table.push(line.split('|').slice(1, -1)); + continue; + } + + // 8. Lists. + const ordered = line.match(ORDERED_ITEM_REGEX); + const unordered = line.match(UNORDERED_ITEM_REGEX); + + if (ordered || unordered) { + const isOrdered = !!ordered; + + if (!list || list.ordered !== isOrdered) { + flush(); + + list = { + type: 'list', + items: [], + ordered: isOrdered, + start: ordered ? Number(ordered[1]) : 1, + }; + } + + list.items.push(parseInline(ordered ? ordered[2]! : unordered![1]!)); + continue; + } + + // 9. Paragraphs. A blank line flushes the open block. + flush(); + pushParagraph(line); + } + + flush(); + + return blocks; +} + +function toTableBlock(rows: string[][]): Block { + const cells = rows.map((row) => row.map((cell) => parseInline(cell.trim()))); + + const hasHeader = + rows.length > 1 && + rows[1]!.every((cell) => TABLE_SEPARATOR_CELL_REGEX.test(cell)); + + return hasHeader + ? { type: 'table', header: cells[0]!, rows: cells.slice(2) } + : { type: 'table', header: [], rows: cells }; +} diff --git a/packages/utils/src/ai-formatting/index.ts b/packages/utils/src/ai-formatting/index.ts new file mode 100644 index 000000000..355b5bdf6 --- /dev/null +++ b/packages/utils/src/ai-formatting/index.ts @@ -0,0 +1,4 @@ +export * from './blocks'; +export * from './inline'; +export * from './math'; +export * from './preprocess'; diff --git a/packages/utils/src/ai-formatting/inline.test.ts b/packages/utils/src/ai-formatting/inline.test.ts new file mode 100644 index 000000000..7dae67264 --- /dev/null +++ b/packages/utils/src/ai-formatting/inline.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, test } from 'bun:test'; + +import { parseInline } from './inline'; + +describe(parseInline.name, () => { + test('Should keep multiplication asterisks as text.', () => { + expect(parseInline('5 * 3 * 2')).toEqual([ + { type: 'text', content: '5 * 3 * 2' }, + ]); + }); + + test('Should keep math inside bold.', () => { + expect(parseInline('**solve $x^2$**')).toEqual([ + { + type: 'bold', + children: [ + { type: 'text', content: 'solve ' }, + { type: 'math', latex: 'x^2' }, + ], + }, + ]); + }); + + test('Should not turn the * in two formulas into italics.', () => { + expect( + parseInline('$w \\in \\Sigma^*$ and $L \\subseteq \\Sigma^*$') + ).toEqual([ + { type: 'math', latex: 'w \\in \\Sigma^*' }, + { type: 'text', content: ' and ' }, + { type: 'math', latex: 'L \\subseteq \\Sigma^*' }, + ]); + }); + + test('Should keep the stray brace inside the math for KaTeX to fix.', () => { + expect(parseInline('$w = abba \\in \\Sigma^*}$')).toEqual([ + { type: 'math', latex: 'w = abba \\in \\Sigma^*}' }, + ]); + }); + + test('Should show a bare number wrapped in $ as plain text.', () => { + expect(parseInline('the mean was $7.23$')).toEqual([ + { type: 'text', content: 'the mean was ' }, + { type: 'text', content: '7.23' }, + ]); + }); + + test('Should treat $$ in a sentence as inline math.', () => { + expect(parseInline('Solve $$2x+3=11$$.')).toEqual([ + { type: 'text', content: 'Solve ' }, + { type: 'math', latex: '2x+3=11' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should keep prices as text.', () => { + expect(parseInline('Costs $5, $10, $20 and $x$.')).toEqual([ + { type: 'text', content: 'Costs $5, $10, $20 and ' }, + { type: 'math', latex: 'x' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should not touch the contents of inline code.', () => { + expect(parseInline('Run `price = $5` or `**a** *b* $x$`.')).toEqual([ + { type: 'text', content: 'Run ' }, + { type: 'code', content: 'price = $5' }, + { type: 'text', content: ' or ' }, + { type: 'code', content: '**a** *b* $x$' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should parse italics.', () => { + expect(parseInline('This is *really* early.')).toEqual([ + { type: 'text', content: 'This is ' }, + { type: 'italic', content: 'really' }, + { type: 'text', content: ' early.' }, + ]); + }); + + test('Should fold typographic asterisks, but not the ∗ operator.', () => { + expect(parseInline('**bold** and a ∗ b ∗ c')).toEqual([ + { type: 'bold', children: [{ type: 'text', content: 'bold' }] }, + { type: 'text', content: ' and a ∗ b ∗ c' }, + ]); + }); + + test('Should parse thread references and links.', () => { + expect( + parseInline('Apply early [ref:1]. See [the guide](https://x.com/a).') + ).toEqual([ + { type: 'text', content: 'Apply early ' }, + { type: 'ref', number: 1 }, + { type: 'text', content: '. See ' }, + { type: 'link', text: 'the guide', url: 'https://x.com/a' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should not parse links that are not http(s).', () => { + expect(parseInline('[click](javascript:alert(1))')).toEqual([ + { type: 'text', content: '[click](javascript:alert(1))' }, + ]); + }); +}); diff --git a/packages/utils/src/ai-formatting/inline.ts b/packages/utils/src/ai-formatting/inline.ts new file mode 100644 index 000000000..ad09ee4ad --- /dev/null +++ b/packages/utils/src/ai-formatting/inline.ts @@ -0,0 +1,143 @@ +import { findInlineMathDollarSpans, protectCodeRegions } from './math'; + +export type InlineToken = + | { type: 'bold'; children: InlineToken[] } + | { type: 'code'; content: string } + | { type: 'italic'; content: string } + | { type: 'link'; text: string; url: string } + | { type: 'math'; latex: string } + | { type: 'ref'; number: number } + | { type: 'text'; content: string }; + +type Match = { + end: number; + start: number; + token: InlineToken; +}; + +const BOLD_REGEX = /\*\*(.+?)\*\*/g; + +// `$$2x+3=11$$` written in the middle of a sentence. +const INLINE_DISPLAY_MATH_REGEX = /\$\$([^$\n]+)\$\$/g; + +// A bare number wrapped for emphasis (ie: "the mean was $7.23$"). +const BARE_NUMBER_REGEX = /(? string; + +/** + * Bold is parsed first and outermost, so that `**solve $x$**` keeps both the + * bold and the math. + */ +function parseBold(text: string, restoreCode: RestoreCode): InlineToken[] { + const tokens: InlineToken[] = []; + + let cursor = 0; + + for (const match of text.matchAll(BOLD_REGEX)) { + tokens.push(...parseFlat(text.slice(cursor, match.index), restoreCode)); + + tokens.push({ + type: 'bold', + children: parseFlat(match[1]!, restoreCode), + }); + + cursor = match.index! + match[0].length; + } + + tokens.push(...parseFlat(text.slice(cursor), restoreCode)); + + return tokens; +} + +function parseFlat(text: string, restoreCode: RestoreCode): InlineToken[] { + if (!text) { + return []; + } + + const matches: Match[] = []; + + function add(start: number, end: number, token: InlineToken) { + const overlaps = matches.some((m) => start < m.end && end > m.start); + + if (!overlaps) { + matches.push({ end, start, token }); + } + } + + function addAll( + regex: RegExp, + toToken: (match: RegExpMatchArray) => InlineToken + ) { + for (const match of text.matchAll(regex)) { + add(match.index!, match.index! + match[0].length, toToken(match)); + } + } + + // Single `$` math comes from the scanner, never from a regex. + for (const span of findInlineMathDollarSpans(text)) { + add(span.start, span.end + 1, { type: 'math', latex: span.inner.trim() }); + } + + addAll(INLINE_DISPLAY_MATH_REGEX, (m) => ({ type: 'math', latex: m[1]! })); + addAll(BARE_NUMBER_REGEX, (m) => ({ type: 'text', content: m[1]! })); + + addAll(CODE_SENTINEL_REGEX, (m) => ({ + type: 'code', + content: restoreCode(m[0]), + })); + + addAll(REF_REGEX, (m) => ({ type: 'ref', number: Number(m[1]) })); + addAll(LINK_REGEX, (m) => ({ type: 'link', text: m[1]!, url: m[2]! })); + addAll(ITALIC_REGEX, (m) => ({ type: 'italic', content: m[1]! })); + + matches.sort((a, b) => a.start - b.start); + + const tokens: InlineToken[] = []; + + let cursor = 0; + + for (const match of matches) { + if (match.start > cursor) { + tokens.push({ type: 'text', content: text.slice(cursor, match.start) }); + } + + tokens.push(match.token); + cursor = match.end; + } + + if (cursor < text.length) { + tokens.push({ type: 'text', content: text.slice(cursor) }); + } + + return tokens; +} diff --git a/packages/utils/src/ai-formatting/katex.test.ts b/packages/utils/src/ai-formatting/katex.test.ts new file mode 100644 index 000000000..31a4c733d --- /dev/null +++ b/packages/utils/src/ai-formatting/katex.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from 'bun:test'; + +import { safeKatexRender } from './katex'; + +describe(safeKatexRender.name, () => { + test('Should render valid LaTeX.', () => { + const html = safeKatexRender('x^2 + y^2 = z^2', false); + + expect(html).toContain('class="katex"'); + }); + + test('Should render display math.', () => { + const html = safeKatexRender('\\int_{a}^{b} f(x) \\, dx', true); + + expect(html).toContain('katex-display'); + }); + + test('Should show the escaped source instead of the KaTeX error.', () => { + const html = safeKatexRender('\\frac{', false); + + expect(html).toEqual('\\frac{'); + expect(html).not.toContain('#cc0000'); + expect(html).not.toContain('parse-error'); + }); + + test('Should escape HTML in the fallback.', () => { + const html = safeKatexRender('\\notacommand{