llm-message-react 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/completePartialTokens.ts","../src/CopyButton.tsx","../src/preprocess.ts","../src/LLMMessage.tsx","../src/createShikiHighlighter.tsx"],"names":["katex","jsxs","jsx","useState","useRef","useEffect","remarkGfm","remarkMath","rehypeKatex","clsx","Fragment","useMemo","ReactMarkdown"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuCO,SAAS,qBAAA,CACd,MACA,OAAA,EACQ;AACR,EAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAElB,EAAA,MAAM,yBAAA,GAA4B,SAAS,yBAAA,IAA6B,IAAA;AAKxE,EAAA,IAAI,oBAAA,CAAqB,IAAI,CAAA,EAAG;AAC9B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,iBAA2B,EAAC;AAClC,EAAA,MAAM,OAAA,GAAU,CAAC,KAAA,KACf,CAAA,OAAA,EAAc,eAAe,IAAA,CAAK,KAAK,IAAI,CAAC,CAAA,EAAA,CAAA;AAM9C,EAAA,IAAI,OAAA,GAAU,KAAK,OAAA,CAAQ,iBAAA,EAAmB,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAK,CAAC,CAAA;AACvE,EAAA,OAAA,GAAU,QAAQ,OAAA,CAAQ,eAAA,EAAiB,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAK,CAAC,CAAA;AACpE,EAAA,OAAA,GAAU,QAAQ,OAAA,CAAQ,YAAA,EAAc,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAK,CAAC,CAAA;AAIjE,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,WAAA,CAAY,GAAG,CAAA;AAC5C,EAAA,IAAI,iBAAiB,EAAA,EAAI;AAGvB,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,IAAA,EAAM,YAA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C,IAAA,EAAM,OAAO,CAAA,GAAIT,eAAwB,IAAI,CAAA;AAEpD,IAAAE,gBAAU,MAAM;AACd,MAAA,IAAI,SAAA,GAAY,KAAA;AAChB,MAAA,OAAA,CAAQ,OAAA,CAAQ,UAAA,CAAW,IAAA,EAAM,EAAE,IAAA,EAAM,QAAA,EAAU,MAAA,EAAQ,CAAC,CAAA,CACzD,IAAA,CAAK,CAAC,MAAA,KAAW;AAChB,QAAA,IAAI,CAAC,SAAA,EAAW,OAAA,CAAQ,MAAM,CAAA;AAAA,MAChC,CAAC,CAAA,CACA,KAAA,CAAM,MAAM;AAEX,QAAA,IAAI,CAAC,SAAA,EAAW,OAAA,CAAQ,IAAI,CAAA;AAAA,MAC9B,CAAC,CAAA;AACH,MAAA,OAAO,MAAM;AACX,QAAA,SAAA,GAAY,IAAA;AAAA,MACd,CAAA;AAAA,IAIF,CAAA,EAAG,CAAC,IAAA,EAAM,QAAQ,CAAC,CAAA;AAEnB,IAAA,IAAI,IAAA,EAAM;AACR,MAAA,uBACEH,cAAAA;AAAA,QAAC,KAAA;AAAA,QAAA;AAAA,UACC,WAAW,SAAA,IAAa,WAAA;AAAA,UAExB,uBAAA,EAAyB,EAAE,MAAA,EAAQ,IAAA;AAAK;AAAA,OAC1C;AAAA,IAEJ;AAEA,IAAA,uBAAOA,cAAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAU,kBAAkB,QAAA,EAAA,IAAA,EAAK,CAAA;AAAA,EAChD,CAAA;AACF","file":"index.cjs","sourcesContent":["import katex from \"katex\";\n\n/** Options controlling how {@link completePartialTokens} repairs the stream. */\nexport interface CompletePartialTokensOptions {\n /**\n * Progressively render unterminated math by closing the open constructs and\n * keeping the largest prefix KaTeX accepts. This applies to both *block* math\n * (`\\[…`, `$$…`, revealed row by row) and *inline* math (`$…`, `\\(…`, closed\n * in place). It is convenient but costs a synchronous KaTeX parse on every\n * chunk while the math streams. Set to `false` to instead hide the\n * unterminated math entirely until its closing delimiter arrives, skipping the\n * KaTeX work. Defaults to `true`.\n */\n showUnfinishedLatexBlocks?: boolean;\n}\n\n/**\n * Repairs partially-streamed markdown / LaTeX so that incomplete syntax does\n * not leak raw delimiter characters into the rendered output.\n *\n * While an LLM streams a response, the text often ends mid-token, e.g.\n * `**bold`, `` `code ``, `[label](http`, `$E = mc^2` or `\\(a + b`. Rendered\n * as-is, those dangling delimiters show up as literal junk (`**`, `` ` ``, `[`,\n * `$`, `\\(`). This function detects the unterminated constructs at the tail of\n * the string and:\n * - closes safe inline formatting so it renders as intended (`**bold` →\n * `**bold**`, `` `code `` → `` `code` ``);\n * - hides fragments that cannot be completed yet, namely incomplete links and\n * incomplete inline math (`$…`, `\\(…`);\n * - progressively renders incomplete *block* math (`\\[…`, `$$…`): instead of\n * hiding the whole block until it finishes streaming, it closes the open\n * environments/braces and renders the largest prefix KaTeX accepts, so a\n * long aligned block reveals row by row instead of popping in at the end.\n *\n * It is a no-op for already-complete text, so it is safe to run on every chunk.\n *\n * @param text The (possibly mid-stream) markdown string.\n * @returns The string with trailing incomplete tokens repaired.\n */\nexport function completePartialTokens(\n text: string,\n options?: CompletePartialTokensOptions,\n): string {\n if (!text) return text;\n\n const showUnfinishedLatexBlocks = options?.showUnfinishedLatexBlocks ?? true;\n\n // An unterminated fenced code block is fine on its own: remark renders it to\n // the end of the document and the partial content reads correctly as code,\n // so we must not touch any of the (markdown-looking) characters inside it.\n if (hasUnclosedCodeFence(text)) {\n return text;\n }\n\n const protectedSpans: string[] = [];\n const protect = (value: string): string =>\n `\\u0000llmph${protectedSpans.push(value) - 1}\\u0000`;\n\n // Protect complete fenced code blocks and complete inline code spans so their\n // contents are never mistaken for markdown/LaTeX markers. Double-backtick\n // spans are protected before single-backtick ones so a span that itself\n // contains a backtick (`` a`b ``) is not mangled by the single-backtick pass.\n let working = text.replace(/```[\\s\\S]*?```/g, (match) => protect(match));\n working = working.replace(/``[\\s\\S]*?``/g, (match) => protect(match));\n working = working.replace(/`[^`\\n]+`/g, (match) => protect(match));\n\n // A leftover single backtick starts an unterminated inline code span. Protect\n // the rest of the line and close it so the in-progress code renders cleanly.\n const lastBacktick = working.lastIndexOf(\"`\");\n if (lastBacktick !== -1) {\n // Bound the in-progress span to its own line so trailing markdown on later\n // lines is not swallowed into the protected code.\n const newline = working.indexOf(\"\\n\", lastBacktick);\n const end = newline === -1 ? working.length : newline;\n const span = working.slice(lastBacktick, end);\n working =\n working.slice(0, lastBacktick) +\n protect(`${span}\\``) +\n working.slice(end);\n }\n\n working = repairIncompleteMath(working, showUnfinishedLatexBlocks);\n working = hideIncompleteLink(working);\n working = completePartialTable(working);\n working = hideDanglingListMarker(working);\n working = closeUnbalancedEmphasis(working);\n\n return working.replace(\n /\\u0000llmph(\\d+)\\u0000/g,\n (_match, index: string) => protectedSpans[Number(index)] ?? \"\",\n );\n}\n\n/**\n * Completes a partially-streamed GFM table delimiter row.\n *\n * A table needs a full delimiter row (`| --- | --- |`) to be recognised, so\n * while it streams the buffer ends with a header row followed by a fragment like\n * `| ---`. Without a valid delimiter remark-gfm collapses both lines into a\n * paragraph (\"| Feature | Works | | ---\"). Once a delimiter fragment appears we\n * already know the column count from the header, so we expand the fragment to a\n * complete delimiter, preserving any alignment colons that have streamed in.\n */\nfunction completePartialTable(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length < 2) return text;\n\n const last = lines[lines.length - 1];\n // The candidate delimiter must contain only delimiter characters and at least\n // one dash; anything else (letters, etc.) means it is a header or body row.\n if (!/-/.test(last) || !/^[\\s|:-]*$/.test(last)) return text;\n\n const header = lines[lines.length - 2];\n if (!header.includes(\"|\")) return text;\n\n // If the table already has a delimiter row at or above the candidate, then\n // the candidate is just a body row that happens to contain only dashes/pipes\n // (not a streaming delimiter), so the table is complete and must be left\n // untouched. Walk up the contiguous block of pipe rows to detect that.\n for (let i = lines.length - 2; i >= 0; i--) {\n const line = lines[i];\n if (!line.includes(\"|\")) break;\n if (/-/.test(line) && /^[\\s|:-]*$/.test(line)) return text;\n }\n\n const columns = countTableColumns(header);\n lines[lines.length - 1] = buildDelimiterRow(last, columns);\n return lines.join(\"\\n\");\n}\n\n/** Counts the cells in a GFM table row, ignoring the outer pipes. */\nfunction countTableColumns(row: string): number {\n let inner = row.trim();\n if (inner.startsWith(\"|\")) inner = inner.slice(1);\n if (inner.endsWith(\"|\")) inner = inner.slice(0, -1);\n return inner.split(\"|\").length;\n}\n\n/**\n * Builds a delimiter row with `columns` cells, reusing any alignment colons\n * already present in the streamed fragment.\n */\nfunction buildDelimiterRow(fragment: string, columns: number): string {\n let inner = fragment.trim();\n if (inner.startsWith(\"|\")) inner = inner.slice(1);\n if (inner.endsWith(\"|\")) inner = inner.slice(0, -1);\n const existing = inner.split(\"|\").map((cell) => cell.trim());\n\n const cells = Array.from({ length: columns }, (_unused, index) => {\n const spec = existing[index] ?? \"\";\n const left = spec.startsWith(\":\");\n const right = spec.endsWith(\":\");\n if (left && right) return \":---:\";\n if (right) return \"---:\";\n if (left) return \":---\";\n return \"---\";\n });\n\n return `| ${cells.join(\" | \")} |`;\n}\n\n/**\n * Hides a trailing line that would be parsed as a setext heading underline.\n *\n * Mid-stream a bullet list arrives a character at a time, so the buffer briefly\n * ends with `paragraph\\n-` before the item text follows. In CommonMark a lone\n * run of dashes directly beneath a non-blank line is a setext H2 underline, so\n * a line like \"Unordered list:\" would flash as a heading until \"- Item\" streams\n * in. We drop the dangling marker until it gains content. A blank line above the\n * dashes makes them a thematic break instead, which is left untouched.\n */\nfunction hideDanglingListMarker(text: string): string {\n const match = text.match(/\\n[ \\t]{0,3}-+[ \\t]*$/);\n if (match?.index == null) return text;\n\n const before = text.slice(0, match.index);\n const prevLine = before.slice(before.lastIndexOf(\"\\n\") + 1);\n if (prevLine.trim() === \"\") return text;\n\n return before;\n}\n\n/**\n * True when a code fence is left open. Backtick (```) and tilde (~~~) fences are\n * counted separately so that a complete block of one kind that happens to\n * contain a line of the other kind is not mistaken for an unbalanced fence.\n */\nfunction hasUnclosedCodeFence(text: string): boolean {\n const backticks = (text.match(/^[ \\t]{0,3}```/gm) ?? []).length;\n const tildes = (text.match(/^[ \\t]{0,3}~~~/gm) ?? []).length;\n return backticks % 2 === 1 || tildes % 2 === 1;\n}\n\n/**\n * Drops a trailing, still-incomplete link or image, e.g. `[label`, `![alt` or\n * `[label](http`. Closed bracket fragments such as `arr[i]` or `[label]` are\n * left untouched to avoid hiding legitimate text.\n */\nfunction hideIncompleteLink(text: string): string {\n // Find the last \"[\" that is not an escaped LaTeX delimiter (\"\\[\").\n let open = -1;\n for (let i = text.length - 1; i >= 0; i--) {\n if (text[i] === \"[\" && text[i - 1] !== \"\\\\\") {\n open = i;\n break;\n }\n }\n if (open === -1) return text;\n\n const start = open > 0 && text[open - 1] === \"!\" ? open - 1 : open;\n const rest = text.slice(open);\n\n // Label is still open: \"[lab\" / \"![al\".\n if (!rest.includes(\"]\")) {\n return text.slice(0, start);\n }\n // Label closed, destination opened but not yet closed: \"[lab](http\".\n if (/^\\[[^\\]]*\\]\\([^)]*$/.test(rest)) {\n return text.slice(0, start);\n }\n return text;\n}\n\n/** A math delimiter that has been opened but not yet closed in the stream. */\ninterface OpenMath {\n /** Index of the opening delimiter in the source string. */\n index: number;\n /** The opening delimiter itself, e.g. `\"\\\\[\"` or `\"$$\"`. */\n open: string;\n /** The closing delimiter to append once repaired, empty for inline math. */\n close: string;\n /** Whether the math is block (display) math we try to render progressively. */\n block: boolean;\n /** Whether to render in KaTeX display mode when validating a candidate. */\n display: boolean;\n}\n\n/**\n * Repairs an unterminated LaTeX region at the tail of the stream.\n *\n * Both inline math (`$…`, `\\(…`) and block math (`\\[…`, `$$…`) are rendered\n * progressively: we close any open environments/braces and keep the largest\n * leading slice that KaTeX can parse, so the math reveals itself as it streams\n * instead of staying blank until the closing delimiter finally arrives. Inline\n * math additionally drops an incomplete trailing brace group (e.g. `\\text{ kc`)\n * rather than auto-closing it, so a half-streamed word does not flash in the\n * middle of running text. Set `showUnfinishedLatexBlocks` to `false` to instead\n * hide the unterminated math entirely until its closing delimiter arrives.\n */\nfunction repairIncompleteMath(\n text: string,\n showUnfinishedLatexBlocks: boolean,\n): string {\n const countOf = (pattern: RegExp): number =>\n (text.match(pattern) ?? []).length;\n\n const opens: OpenMath[] = [];\n\n // Display math: \\[ ... \\]\n if (countOf(/\\\\\\[/g) > countOf(/\\\\\\]/g)) {\n opens.push({\n index: text.lastIndexOf(\"\\\\[\"),\n open: \"\\\\[\",\n close: \"\\\\]\",\n block: true,\n display: true,\n });\n }\n\n // Inline math: \\( ... \\)\n if (countOf(/\\\\\\(/g) > countOf(/\\\\\\)/g)) {\n opens.push({\n index: text.lastIndexOf(\"\\\\(\"),\n open: \"\\\\(\",\n close: \"\\\\)\",\n block: false,\n display: false,\n });\n }\n\n if (countOf(/\\$\\$/g) % 2 === 1) {\n // Display math: $$ ... $$\n opens.push({\n index: text.lastIndexOf(\"$$\"),\n open: \"$$\",\n close: \"$$\",\n block: true,\n display: true,\n });\n } else {\n // Inline math: $ ... $. Mask complete \"$$\" pairs (keeping indices stable),\n // then ignore escaped \"\\$\" and currency like \"$5\" to avoid false positives.\n let masked = text.replace(/\\$\\$/g, \" \");\n // Also mask complete single-line \"$…$\" spans that contain a LaTeX command\n // (so they are real math, not \"$5\" currency). Their opening \"$\" may be\n // followed by a digit (e.g. \"$15 \\text{ g}$\"), which the currency guard\n // below would otherwise drop from the count while still counting the\n // closing \"$\", flipping the parity and hiding trailing content by mistake.\n masked = masked.replace(\n /(?<!\\\\)\\$(?!\\$)[^$\\n]*?\\\\[a-zA-Z][^$\\n]*?\\$/g,\n (m) => \" \".repeat(m.length),\n );\n // Same parity hazard for command-free numeric spans (e.g. \"$0$\", \"$15$\"):\n // the opening \"$\" is dropped by the currency guard below while the closing\n // \"$\" is still counted. Mask these balanced numeric spans too so neither\n // delimiter is counted. Plain currency (\"$5 and $10\") has prose between the\n // dollars, so it matches neither this nor the command mask and is left for\n // the currency guard to handle.\n masked = masked.replace(\n /(?<!\\\\)\\$(?!\\$)\\d[\\d\\s.,+\\-*/=]*\\$/g,\n (m) => \" \".repeat(m.length),\n );\n const dollars = inlineMathDollarIndices(masked);\n if (dollars.length % 2 === 1) {\n opens.push({\n index: dollars[dollars.length - 1],\n open: \"$\",\n close: \"$\",\n block: false,\n display: false,\n });\n }\n }\n\n const valid = opens.filter((entry) => entry.index >= 0);\n if (valid.length === 0) return text;\n\n // The earliest opener marks where the incomplete math region begins; anything\n // after it is part of the unterminated construct.\n const open = valid.reduce((a, b) => (b.index < a.index ? b : a));\n const before = text.slice(0, open.index);\n\n // When progressive rendering is disabled, hide the unterminated math (inline\n // or block) until its closing delimiter arrives, skipping the KaTeX cost.\n if (!showUnfinishedLatexBlocks) {\n return before;\n }\n\n const inner = text.slice(open.index + open.open.length);\n const body = bestRenderableMathBody(inner, open.display, open.block);\n if (body == null) return before;\n\n // Reproduce the original fenced layout so the markdown math parser can detect\n // the closing delimiter. When the block opens on its own line (`\\[\\n…`), the\n // closing delimiter must also sit on its own line; otherwise micromark treats\n // the run as inline math, never finds the closing fence, and KaTeX renders a\n // parse error that swallows the trailing delimiter.\n const blockLayout = /^[ \\t]*\\r?\\n/.test(inner);\n if (!blockLayout) {\n return before + open.open + body + open.close;\n }\n const opener =\n before === \"\" || before.endsWith(\"\\n\") ? open.open : `\\n${open.open}`;\n return `${before}${opener}${body.replace(/\\s+$/, \"\")}\\n${open.close}`;\n}\n\n/**\n * Returns the indices of the unescaped single `$` characters that act as inline\n * math delimiters in `masked` (complete `$$`/`$…$` spans are expected to have\n * been blanked out by the caller already).\n *\n * A `$` directly followed by a digit is normally currency (`$5`) and ignored.\n * The exception is a span whose body merely *starts* with a number but contains\n * a LaTeX command, e.g. `$1288 \\text{ kcal}`: the `\\text` proves it is real\n * math, so the opening `$` must count as a delimiter instead of being mistaken\n * for `$1288` currency. The span is scanned only up to the next unescaped `$`,\n * a newline, or the end of the string, since inline math stays on one line.\n */\nfunction inlineMathDollarIndices(masked: string): number[] {\n const indices: number[] = [];\n const pattern = /(?<!\\\\)\\$/g;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(masked)) != null) {\n const index = match.index;\n if (/\\d/.test(masked[index + 1] ?? \"\")) {\n const rest = masked.slice(index + 1);\n const end = rest.search(/(?<!\\\\)\\$|\\n/);\n const span = end === -1 ? rest : rest.slice(0, end);\n if (!/\\\\[a-zA-Z]/.test(span)) continue;\n }\n indices.push(index);\n }\n return indices;\n}\n\n/**\n * Returns the largest leading slice of incomplete block-math content that KaTeX\n * can render, with its open environments and braces closed, or `null` when no\n * usable prefix exists yet (in which case the caller hides the fragment).\n *\n * When an environment is still open (e.g. `\\begin{aligned}` mid-stream) we\n * prefer revealing only the complete rows so each equation appears fully formed,\n * falling back to a token-level repair so single-line blocks still stream in.\n */\nfunction bestRenderableMathBody(\n inner: string,\n display: boolean,\n block: boolean,\n): string | null {\n const candidates = unclosedEnvironments(inner).length > 0\n ? [closeOpenMathConstructs(truncateToLastRow(inner)), closeOpenMathConstructs(trimIncompleteMathTail(inner))]\n : [closeOpenMathConstructs(trimIncompleteMathTail(inner))];\n\n // Inline math is short and sits in running text, so a half-streamed brace\n // group (e.g. `\\text{ kc`) would flash a partial word that then changes. For\n // inline math we therefore prefer dropping the incomplete trailing group and\n // keeping the largest stable prefix, only falling back to the brace-closing\n // candidates above when that prefix cannot render on its own.\n if (!block) {\n candidates.unshift(\n closeOpenMathConstructs(\n trimIncompleteMathTail(dropIncompleteBraceGroup(inner)),\n ),\n );\n }\n\n for (const candidate of candidates) {\n if (!hasRenderableMathContent(candidate)) continue;\n if (isRenderableMath(candidate, display)) return candidate;\n }\n return null;\n}\n\n/**\n * Cuts a math fragment back to just before its first still-open `{`, dropping\n * the entire incomplete brace group. Escaped braces (`\\{`, `\\}`) are ignored.\n * Returns the input unchanged when every group is already balanced.\n */\nfunction dropIncompleteBraceGroup(text: string): string {\n const stack: number[] = [];\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\\\\") {\n i++;\n continue;\n }\n if (char === \"{\") stack.push(i);\n else if (char === \"}\" && stack.length > 0) stack.pop();\n }\n if (stack.length === 0) return text;\n return text.slice(0, stack[0]);\n}\n\n/** True when a math body contains something other than empty environment scaffolding. */\nfunction hasRenderableMathContent(body: string): boolean {\n const stripped = body\n .replace(/\\\\(?:begin|end)\\s*\\{[^}]*\\}/g, \"\")\n .replace(/[\\s{}]/g, \"\");\n return stripped.length > 0;\n}\n\n/**\n * True when KaTeX can render the math body without raising a parse error.\n *\n * Uses the public, stable `renderToString` entry point (with `throwOnError`)\n * rather than any internal parse-only API, so it keeps working across KaTeX\n * upgrades. We only care whether it throws; the produced string is discarded.\n */\nfunction isRenderableMath(body: string, display: boolean): boolean {\n try {\n katex.renderToString(body, {\n displayMode: display,\n throwOnError: true,\n strict: false,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Keeps only the complete rows of a multi-line environment by cutting back to\n * the last row separator (`\\\\`), dropping the partially-streamed current row.\n * Returns an empty string when no full row has streamed yet.\n */\nfunction truncateToLastRow(inner: string): string {\n const lastRow = inner.lastIndexOf(\"\\\\\\\\\");\n if (lastRow === -1) return \"\";\n return inner.slice(0, lastRow + 2);\n}\n\n/**\n * Drops trailing tokens that cannot render on their own yet: surrounding\n * whitespace, a dangling backslash, an in-progress control word (`\\frac` may\n * still be `\\fra`), and a subscript/superscript with no argument. A complete\n * `\\\\` row separator is preserved.\n */\nfunction trimIncompleteMathTail(inner: string): string {\n let result = inner;\n let previous: string;\n do {\n previous = result;\n result = result.replace(/\\s+$/, \"\");\n // A trailing odd run of backslashes ends in a lone \"\\\" (an incomplete \"\\\\\"\n // or the start of a command); drop it. An even run is complete \"\\\\\".\n const backslashes = result.match(/\\\\+$/);\n if (backslashes != null && backslashes[0].length % 2 === 1) {\n result = result.slice(0, -1);\n }\n // A trailing control word is ambiguous mid-stream; drop it so it cannot be\n // an unknown (and therefore error-rendered) command.\n result = result.replace(/\\\\[a-zA-Z]+\\*?$/, \"\");\n // A subscript/superscript needs an argument that has not arrived yet.\n result = result.replace(/[_^]$/, \"\");\n } while (result !== previous);\n return result;\n}\n\n/**\n * Closes the constructs left open in a math fragment so KaTeX can parse it:\n * unmatched `\\left`, unbalanced `{` groups, and unclosed environments. Order is\n * a best effort; the caller validates the result with KaTeX regardless.\n */\nfunction closeOpenMathConstructs(inner: string): string {\n let result = inner;\n\n const lefts = (result.match(/\\\\left(?![a-zA-Z])/g) ?? []).length;\n const rights = (result.match(/\\\\right(?![a-zA-Z])/g) ?? []).length;\n result += \"\\\\right.\".repeat(Math.max(0, lefts - rights));\n\n result += \"}\".repeat(openBraceDepth(result));\n\n const environments = unclosedEnvironments(result);\n for (let i = environments.length - 1; i >= 0; i--) {\n result += `\\\\end{${environments[i]}}`;\n }\n return result;\n}\n\n/** Counts unclosed `{` groups, ignoring escaped braces (`\\{`, `\\}`). */\nfunction openBraceDepth(text: string): number {\n let depth = 0;\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\\\\") {\n i++;\n continue;\n }\n if (char === \"{\") depth++;\n else if (char === \"}\" && depth > 0) depth--;\n }\n return depth;\n}\n\n/**\n * Returns the names of environments opened with `\\begin{…}` but not yet closed\n * with a matching `\\end{…}`, outermost first.\n */\nfunction unclosedEnvironments(text: string): string[] {\n const stack: string[] = [];\n const pattern = /\\\\(begin|end)\\s*\\{([^}]*)\\}/g;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(text)) != null) {\n const name = match[2];\n if (match[1] === \"begin\") {\n stack.push(name);\n } else {\n const index = stack.lastIndexOf(name);\n if (index !== -1) stack.splice(index, 1);\n else stack.pop();\n }\n }\n return stack;\n}\n\n/**\n * Closes unterminated emphasis runs: ~~strike~~, **bold**, *italic*, __bold__\n * and _italic_.\n */\nfunction closeUnbalancedEmphasis(text: string): string {\n let result = text;\n result = closeRunMarker(result, \"~~\");\n // Close a single \"*\" first so a \"***\" opener becomes \"*\" + \"**\" and both\n // halves get closed, yielding a balanced \"***…***\".\n result = closeSingleAsterisk(result);\n result = closeRunMarker(result, \"**\");\n result = closeSingleUnderscore(result);\n result = closeDoubleUnderscore(result);\n return result;\n}\n\n/**\n * True when the marker at `index` begins a delimiter run that could open\n * emphasis: it sits at the start of the string or directly after a non-word\n * character (whitespace or punctuation). Underscores require this so intra-word\n * usage (`snake_case`, `__init__`) is never treated as a dangling emphasis\n * opener.\n */\nfunction opensAtWordBoundary(text: string, index: number): boolean {\n if (index <= 0) return true;\n // Whitespace or punctuation before the marker counts as a boundary; an\n // alphanumeric character (or another underscore) does not, so intra-word\n // usage (`snake_case`, `__init__`) is never treated as a dangling opener\n // while a leading-punctuation case like `(_italic` still closes.\n return !/[\\p{L}\\p{N}_]/u.test(text[index - 1]);\n}\n\n/**\n * Closes a single `_` italic marker. `__` pairs are masked out first, and the\n * marker is only closed when it both opens at a word boundary and sits directly\n * before a non-space character, so `snake_case` is left alone.\n */\nfunction closeSingleUnderscore(text: string): string {\n const masked = text.replace(/__/g, \"\");\n const count = (masked.match(/_/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"_\");\n const after = text.slice(lastIndex + 1);\n if (after.length === 0 || /^[\\s_]/.test(after)) return text;\n if (!opensAtWordBoundary(text, lastIndex)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"_\");\n}\n\n/**\n * Closes a `__` bold marker when it is unbalanced, opens at a word boundary,\n * and is directly followed by a non-space character (so `a__b` and `__init__`\n * are left untouched).\n */\nfunction closeDoubleUnderscore(text: string): string {\n const count = (text.match(/__/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"__\");\n const after = text.slice(lastIndex + 2);\n if (after.length === 0 || /^\\s/.test(after)) return text;\n if (!opensAtWordBoundary(text, lastIndex)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"__\");\n}\n\n/**\n * Blanks out asterisks that belong to *block* constructs rather than inline\n * emphasis so they never skew the emphasis parity count: thematic breaks\n * (`***`, `* * *`) and line-leading list bullets (`* item`) at any\n * indentation. Each match is replaced with spaces of equal length so string\n * indices stay stable for the callers that still use the original text.\n */\nfunction maskBlockAsterisks(text: string): string {\n return text\n .replace(/^[ \\t]*\\*(?:[ \\t]*\\*){2,}[ \\t]*$/gm, (m) => \" \".repeat(m.length))\n .replace(/^[ \\t]*\\*(?=[ \\t])/gm, (m) => \" \".repeat(m.length));\n}\n\n/**\n * Closes a two-character emphasis marker (`**` or `~~`) when it is unbalanced\n * and the final marker looks like an opener (immediately followed by a\n * non-space character), which avoids touching list markers or operators.\n */\nfunction closeRunMarker(text: string, marker: string): string {\n const escaped = marker.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Asterisk runs share their character with bullets and thematic breaks, so\n // count them on a text whose block asterisks have been masked away.\n const countSource = marker.includes(\"*\") ? maskBlockAsterisks(text) : text;\n const count = (countSource.match(new RegExp(escaped, \"g\")) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(marker);\n const after = text.slice(lastIndex + marker.length);\n if (after.length === 0 || /^\\s/.test(after)) return text;\n\n return insertBeforeTrailingWhitespace(text, marker);\n}\n\n/**\n * Closes a single `*` italic marker. `**` pairs are masked out first, and the\n * marker is only closed when it sits directly before a non-space character so\n * bullet markers (`* item`) and multiplication (`2 * 3`) are left alone.\n */\nfunction closeSingleAsterisk(text: string): string {\n // Mask block-level asterisks (bullets, thematic breaks) and \"**\" pairs so the\n // marker is not miscounted as a dangling italic opener. Masking only affects\n // the parity count; `lastIndexOf` still operates on the original text.\n const masked = maskBlockAsterisks(text).replace(/\\*\\*/g, \"\");\n const count = (masked.match(/\\*/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"*\");\n const after = text.slice(lastIndex + 1);\n if (after.length === 0 || /^[\\s*]/.test(after)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"*\");\n}\n\n/**\n * Appends a closing emphasis marker, but places it before any trailing\n * whitespace. A closer such as `**` is only valid when it directly follows a\n * non-space character, so `**bold ` must become `**bold** ` rather than the\n * un-renderable `**bold **`.\n */\nfunction insertBeforeTrailingWhitespace(text: string, marker: string): string {\n const trailing = text.match(/\\s+$/)?.[0] ?? \"\";\n const core = text.slice(0, text.length - trailing.length);\n return core + marker + trailing;\n}\n","import { useEffect, useRef, useState } from \"react\";\n\nimport type { CopyButtonProps } from \"./types\";\n\nfunction CopyIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" />\n <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" />\n </svg>\n );\n}\n\nfunction CheckIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n );\n}\n\nexport function CopyButton({ text, className }: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (timeoutRef.current != null) clearTimeout(timeoutRef.current);\n };\n }, []);\n\n const copy = () => {\n const clipboard = navigator.clipboard;\n if (!clipboard) return;\n // Only show the \"copied\" confirmation once the write actually succeeds.\n void clipboard\n .writeText(text)\n .then(() => {\n setCopied(true);\n if (timeoutRef.current != null) clearTimeout(timeoutRef.current);\n timeoutRef.current = setTimeout(() => setCopied(false), 2000);\n })\n .catch(() => {\n // Clipboard write failed; keep the idle state.\n });\n };\n\n return (\n <button\n type=\"button\"\n onClick={copy}\n className={className}\n aria-label={copied ? \"Copied\" : \"Copy code\"}\n data-copied={copied ? \"\" : undefined}\n >\n {copied ? <CheckIcon /> : <CopyIcon />}\n </button>\n );\n}\n","/**\n * Matches a fenced code block or an inline code span. Shared by\n * {@link preprocessLaTeX} and {@link escapeBrackets} so both functions treat\n * code identically; composed into the larger patterns below via `.source`.\n */\nconst CODE_SPAN = /```[\\s\\S]*?```|`[^`\\n]+`/;\n\n/**\n * Preprocesses LaTeX content by replacing delimiters and escaping certain characters.\n *\n * @param content The input string containing LaTeX expressions.\n * @returns The processed string with replaced delimiters and escaped characters.\n */\nexport function preprocessLaTeX(content: string): string {\n // Step 1: Protect code blocks\n const codeBlocks: string[] = [];\n content = content.replace(\n new RegExp(`(${CODE_SPAN.source})`, \"g\"),\n (_match, code) => {\n codeBlocks.push(code);\n return `<<CODE_BLOCK_${codeBlocks.length - 1}>>`;\n },\n );\n\n // Step 2: Protect existing LaTeX expressions. This is what makes the currency\n // escaping in Step 3 safe: by pulling complete `$$…$$` / `\\[…\\]` / `\\(…\\)`\n // regions out of the string first, the `\\$(?=\\d)` pass below cannot corrupt a\n // `$` that legitimately belongs to a math expression (e.g. `$$x = $5$$`).\n //\n // Single-dollar inline math whose content begins with a digit (e.g.\n // `$15 \\text{ g}$`) is protected too: without this its opening `$` would be\n // escaped as currency in Step 3, unbalancing the delimiters so remark-math\n // swallows the rest of the paragraph as one math region. Two shapes qualify:\n // 1. spans containing a LaTeX command (`\\…`), e.g. `$15 \\text{ g}$`;\n // 2. balanced spans whose content is purely numeric/math (digits, spaces\n // and basic operators, no prose letters), e.g. `$0$` or `$1288 / 3$`.\n // Both leave plain currency prose like `$5 and $10` for Step 3, because that\n // text contains letters between the dollars and so matches neither shape.\n const latexExpressions: string[] = [];\n content = content.replace(\n /(\\$\\$[\\s\\S]*?\\$\\$|\\\\\\[[\\s\\S]*?\\\\\\]|\\\\\\(.*?\\\\\\)|\\$(?!\\$)[^$\\n]*?\\\\[a-zA-Z][^$\\n]*?\\$|\\$(?!\\$)\\d[\\d\\s.,+\\-*/=]*\\$)/g,\n (match) => {\n latexExpressions.push(match);\n return `<<LATEX_${latexExpressions.length - 1}>>`;\n },\n );\n\n // Step 3: Escape dollar signs that are likely currency indicators\n content = content.replace(/\\$(?=\\d)/g, \"\\\\$\");\n\n // Step 4: Restore LaTeX expressions\n content = content.replace(\n /<<LATEX_(\\d+)>>/g,\n (_, index) => latexExpressions[parseInt(index, 10)],\n );\n\n // Step 5: Restore code blocks\n content = content.replace(\n /<<CODE_BLOCK_(\\d+)>>/g,\n (_, index) => codeBlocks[parseInt(index, 10)],\n );\n\n // Step 6: Apply additional escaping functions\n content = escapeBrackets(content);\n content = escapeMhchem(content);\n\n return content;\n}\n\nexport function escapeBrackets(text: string): string {\n const pattern = new RegExp(\n `(${CODE_SPAN.source})|` +\n /\\\\\\[((?:[\\s\\S]*?[^\\\\])?)\\\\]|\\\\\\((.*?)\\\\\\)/.source,\n \"g\",\n );\n return text.replace(\n pattern,\n (\n match: string,\n codeBlock: string | undefined,\n squareBracket: string | undefined,\n roundBracket: string | undefined,\n ): string => {\n if (codeBlock != null) {\n return codeBlock;\n } else if (squareBracket != null) {\n return `$$${squareBracket}$$`;\n } else if (roundBracket != null) {\n return `$${roundBracket}$`;\n }\n return match;\n },\n );\n}\n\nexport function escapeMhchem(text: string): string {\n return text.replaceAll(\"$\\\\ce{\", \"$\\\\\\\\ce{\").replaceAll(\"$\\\\pu{\", \"$\\\\\\\\pu{\");\n}\n","import { clsx } from \"clsx\";\nimport { useMemo } from \"react\";\nimport type { HTMLAttributes } from \"react\";\nimport ReactMarkdown, { type Components } from \"react-markdown\";\nimport rehypeKatex from \"rehype-katex\";\nimport remarkGfm from \"remark-gfm\";\nimport remarkMath from \"remark-math\";\n\nimport { completePartialTokens } from \"./completePartialTokens\";\nimport { CopyButton } from \"./CopyButton\";\nimport { preprocessLaTeX } from \"./preprocess\";\nimport type {\n CodeHighlighter,\n LLMMessageClassNames,\n LLMMessageComponents,\n} from \"./types\";\n\nexport interface LLMMessageProps\n extends Omit<HTMLAttributes<HTMLDivElement>, \"children\" | \"content\"> {\n /** The LLM message content as a markdown string. */\n children?: string;\n /** Alias for `children`. */\n content?: string;\n /** Class applied to the root element (merged with the built-in class). */\n className?: string;\n /** Per-element class overrides (merged with the built-in classes). */\n classNames?: LLMMessageClassNames;\n /** Per-element component overrides for full markup control. */\n components?: LLMMessageComponents;\n /**\n * Repair partially-streamed markdown/LaTeX so unterminated tokens (e.g.\n * `**bold`, `` `code ``, `[label](http`, `$E = mc^2`) do not render as raw\n * delimiter junk while the response is still streaming. Defaults to `true`.\n */\n completePartialTokens?: boolean;\n /**\n * Progressively render unterminated *block* math (`\\[…`, `$$…`) while it\n * streams, instead of hiding it until the closing delimiter arrives. This is\n * nicer to watch (a long block reveals row by row) but costs a synchronous\n * KaTeX parse on every chunk that contains an open block. Set to `false` to\n * hide unfinished blocks and skip that work. Only relevant while\n * `completePartialTokens` is enabled. Defaults to `true`.\n */\n showUnfinishedLatexBlocks?: boolean;\n /**\n * Optional syntax highlighter for fenced code blocks. When omitted, code\n * blocks render as plain text (so no highlighter bundle is pulled in). Pass\n * `ShikiHighlighter` / `ShikiWebHighlighter`, or build your own with\n * `createShikiHighlighter`.\n */\n highlighter?: CodeHighlighter;\n}\n\nconst remarkPlugins = [remarkGfm, remarkMath];\nconst rehypePlugins = [rehypeKatex];\n\nfunction cx(...inputs: Array<string | undefined>): string | undefined {\n const result = clsx(inputs);\n return result === \"\" ? undefined : result;\n}\n\nfunction buildComponents(\n classNames: LLMMessageClassNames | undefined,\n overrides: LLMMessageComponents | undefined,\n highlighter: CodeHighlighter | undefined,\n): Components {\n const cn = classNames ?? {};\n const o = overrides ?? {};\n const Highlighter = highlighter;\n\n return {\n code({ node: _node, className, children, ...props }) {\n const match = /language-(\\w+)/.exec(className || \"\");\n const codeText = String(children).replace(/\\n$/, \"\");\n // A fenced block always spans its own lines (so its text contains a\n // newline) even when no language info string is present; inline code\n // never does. Relying on the `language-` class alone would misrender a\n // bare ``` fence as inline code.\n const isBlock = match != null || String(children).includes(\"\\n\");\n\n if (isBlock) {\n const language = match?.[1] ?? \"\";\n if (o.codeBlock) {\n const CodeBlock = o.codeBlock;\n return (\n <CodeBlock\n code={codeText}\n language={language}\n className={cn.codeBlock}\n />\n );\n }\n return (\n <div className={cx(\"llm-code-block\", cn.codeBlock)}>\n <div className={cx(\"llm-code-header\", cn.codeHeader)}>\n <span className={cx(\"llm-code-language\", cn.codeLanguage)}>\n {language}\n </span>\n {o.copyButton ? (\n <o.copyButton text={codeText} className={cn.copyButton} />\n ) : (\n <CopyButton\n text={codeText}\n className={cx(\"llm-copy-button\", cn.copyButton)}\n />\n )}\n </div>\n <div className=\"llm-code-body\">\n {Highlighter ? (\n <Highlighter code={codeText} language={language} />\n ) : (\n <code className=\"llm-code-plain\">{codeText}</code>\n )}\n </div>\n </div>\n );\n }\n\n if (o.code) {\n const InlineCode = o.code;\n return (\n <InlineCode className={cx(\"llm-code\", cn.code, className)}>\n {children}\n </InlineCode>\n );\n }\n\n return (\n <code className={cx(\"llm-code\", cn.code, className)} {...props}>\n {children}\n </code>\n );\n },\n pre({ children }) {\n if (o.pre) {\n return <o.pre>{children}</o.pre>;\n }\n // Let the code component handle fenced blocks.\n return <>{children}</>;\n },\n table({ children }) {\n if (o.table) {\n return <o.table className={cn.table}>{children}</o.table>;\n }\n return (\n <div className={cx(\"llm-table-wrapper\", cn.tableWrapper)}>\n <table className={cx(\"llm-table\", cn.table)}>{children}</table>\n </div>\n );\n },\n th({ children }) {\n if (o.th) {\n return <o.th className={cn.th}>{children}</o.th>;\n }\n return <th className={cx(\"llm-th\", cn.th)}>{children}</th>;\n },\n td({ children }) {\n if (o.td) {\n return <o.td className={cn.td}>{children}</o.td>;\n }\n return <td className={cx(\"llm-td\", cn.td)}>{children}</td>;\n },\n blockquote({ children }) {\n if (o.blockquote) {\n return <o.blockquote className={cn.blockquote}>{children}</o.blockquote>;\n }\n return (\n <blockquote className={cx(\"llm-blockquote\", cn.blockquote)}>\n {children}\n </blockquote>\n );\n },\n ul({ children }) {\n if (o.ul) {\n return <o.ul className={cn.ul}>{children}</o.ul>;\n }\n return <ul className={cx(\"llm-ul\", cn.ul)}>{children}</ul>;\n },\n ol({ children }) {\n if (o.ol) {\n return <o.ol className={cn.ol}>{children}</o.ol>;\n }\n return <ol className={cx(\"llm-ol\", cn.ol)}>{children}</ol>;\n },\n li({ children }) {\n if (o.li) {\n return <o.li className={cn.li}>{children}</o.li>;\n }\n return <li className={cx(\"llm-li\", cn.li)}>{children}</li>;\n },\n p({ children }) {\n if (o.p) {\n return <o.p className={cn.p}>{children}</o.p>;\n }\n return <p className={cx(\"llm-p\", cn.p)}>{children}</p>;\n },\n h1({ children }) {\n if (o.h1) {\n return <o.h1 className={cn.h1}>{children}</o.h1>;\n }\n return <h1 className={cx(\"llm-h1\", cn.h1)}>{children}</h1>;\n },\n h2({ children }) {\n if (o.h2) {\n return <o.h2 className={cn.h2}>{children}</o.h2>;\n }\n return <h2 className={cx(\"llm-h2\", cn.h2)}>{children}</h2>;\n },\n h3({ children }) {\n if (o.h3) {\n return <o.h3 className={cn.h3}>{children}</o.h3>;\n }\n return <h3 className={cx(\"llm-h3\", cn.h3)}>{children}</h3>;\n },\n h4({ children }) {\n if (o.h4) {\n return <o.h4 className={cn.h4}>{children}</o.h4>;\n }\n return <h4 className={cx(\"llm-h4\", cn.h4)}>{children}</h4>;\n },\n h5({ children }) {\n if (o.h5) {\n return <o.h5 className={cn.h5}>{children}</o.h5>;\n }\n return <h5 className={cx(\"llm-h5\", cn.h5)}>{children}</h5>;\n },\n h6({ children }) {\n if (o.h6) {\n return <o.h6 className={cn.h6}>{children}</o.h6>;\n }\n return <h6 className={cx(\"llm-h6\", cn.h6)}>{children}</h6>;\n },\n input({ node: _node, type, checked, disabled, ...props }) {\n if (type === \"checkbox\") {\n if (o.checkbox) {\n return (\n <o.checkbox checked={Boolean(checked)} className={cn.checkbox} />\n );\n }\n return (\n <input\n type=\"checkbox\"\n checked={Boolean(checked)}\n disabled\n aria-label={checked ? \"Completed task\" : \"Incomplete task\"}\n className={cx(\"llm-checkbox\", cn.checkbox)}\n readOnly\n />\n );\n }\n return (\n <input\n type={type}\n checked={checked}\n disabled={disabled}\n readOnly\n {...props}\n />\n );\n },\n a({ href, children }) {\n if (o.a) {\n return (\n <o.a href={href} className={cn.a}>\n {children}\n </o.a>\n );\n }\n return (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={cx(\"llm-a\", cn.a)}\n >\n {children}\n </a>\n );\n },\n img({ node: _node, src, alt, title, className: _className, ...props }) {\n if (o.img) {\n const Image = o.img;\n return (\n <Image\n src={typeof src === \"string\" ? src : undefined}\n alt={alt}\n title={title}\n className={cn.img}\n />\n );\n }\n return (\n <img\n src={typeof src === \"string\" ? src : undefined}\n alt={alt}\n title={title}\n className={cx(\"llm-img\", cn.img)}\n {...props}\n />\n );\n },\n hr() {\n if (o.hr) {\n return <o.hr className={cn.hr} />;\n }\n return <hr className={cx(\"llm-hr\", cn.hr)} />;\n },\n strong({ children }) {\n if (o.strong) {\n return <o.strong className={cn.strong}>{children}</o.strong>;\n }\n return <strong className={cx(\"llm-strong\", cn.strong)}>{children}</strong>;\n },\n em({ children }) {\n if (o.em) {\n return <o.em className={cn.em}>{children}</o.em>;\n }\n return <em className={cx(\"llm-em\", cn.em)}>{children}</em>;\n },\n del({ children }) {\n if (o.del) {\n return <o.del className={cn.del}>{children}</o.del>;\n }\n return <del className={cx(\"llm-del\", cn.del)}>{children}</del>;\n },\n };\n}\n\nexport function LLMMessage({\n children,\n content,\n className,\n classNames,\n components,\n completePartialTokens: repairPartialTokens = true,\n showUnfinishedLatexBlocks = true,\n highlighter,\n ...rest\n}: LLMMessageProps) {\n const source = content ?? children ?? \"\";\n\n const markdownComponents = useMemo(\n () => buildComponents(classNames, components, highlighter),\n [classNames, components, highlighter],\n );\n\n const processed = useMemo(() => {\n const repaired = repairPartialTokens\n ? completePartialTokens(source, { showUnfinishedLatexBlocks })\n : source;\n return preprocessLaTeX(repaired);\n }, [source, repairPartialTokens, showUnfinishedLatexBlocks]);\n\n return (\n <div className={cx(\"llm-message\", classNames?.root, className)} {...rest}>\n <ReactMarkdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n components={markdownComponents}\n >\n {processed}\n </ReactMarkdown>\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { CodeHighlighter, CodeToHtml } from \"./types\";\n\ninterface CreateShikiHighlighterOptions {\n /** Theme pair forwarded to `codeToHtml`. Defaults to GitHub light/dark. */\n themes?: { light: string; dark: string };\n}\n\nconst DEFAULT_THEMES = { light: \"github-light\", dark: \"github-dark\" };\n\n/**\n * Builds a {@link CodeHighlighter} from any `codeToHtml`-compatible function.\n *\n * This factory imports no Shiki bundle itself, so importing it never drags\n * highlighting code into your app. You decide which bundle to pay for by\n * passing the `codeToHtml` from `shiki` (full), `shiki/bundle/web` (web), or a\n * minimal `createHighlighterCore` instance.\n *\n * @example\n * import { codeToHtml } from \"shiki/bundle/web\";\n * const Highlighter = createShikiHighlighter(codeToHtml);\n * <LLMMessage highlighter={Highlighter}>{content}</LLMMessage>\n */\nexport function createShikiHighlighter(\n codeToHtml: CodeToHtml,\n options?: CreateShikiHighlighterOptions,\n): CodeHighlighter {\n const themes = options?.themes ?? DEFAULT_THEMES;\n\n return function ShikiHighlighter({ code, language, className }) {\n const [html, setHtml] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n Promise.resolve(codeToHtml(code, { lang: language, themes }))\n .then((result) => {\n if (!cancelled) setHtml(result);\n })\n .catch(() => {\n // Fallback: if the language is unsupported, just show plain code.\n if (!cancelled) setHtml(null);\n });\n return () => {\n cancelled = true;\n };\n // `codeToHtml` and `themes` are fixed for the lifetime of a highlighter\n // instance (captured from the factory closure), so they are intentionally\n // not listed: they never change between renders of this component.\n }, [code, language]);\n\n if (html) {\n return (\n <div\n className={className ?? \"llm-shiki\"}\n // The HTML is generated by Shiki, which is safe.\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n }\n\n return <code className=\"llm-code-plain\">{code}</code>;\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/CopyButton.tsx","../src/buildMarkdownComponents.tsx","../src/MarkdownBlock.tsx","../src/completePartialTokens.ts","../src/preprocess.ts","../src/splitBlocks.ts","../src/useMarkdownBlocks.ts","../src/smoothReveal.ts","../src/useSmoothReveal.ts","../src/LLMMessage.tsx","../src/createShikiHighlighter.tsx"],"names":["jsxs","jsx","useState","useRef","useEffect","clsx","Fragment","memo","MarkdownBlock","ReactMarkdown","katex","Lexer","useMemo","useDeferredValue","useLayoutEffect","remarkGfm","remarkMath","rehypeKatex"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,QAAA,GAAW;AAClB,EAAA,uBACEA,eAAA;AAAA,IAAC,KAAA;AAAA,IAAA;AAAA,MACC,OAAA,EAAQ,WAAA;AAAA,MACR,KAAA,EAAM,KAAA;AAAA,MACN,MAAA,EAAO,KAAA;AAAA,MACP,IAAA,EAAK,MAAA;AAAA,MACL,MAAA,EAAO,cAAA;AAAA,MACP,WAAA,EAAY,GAAA;AAAA,MACZ,aAAA,EAAc,OAAA;AAAA,MACd,cAAA,EAAe,OAAA;AAAA,MACf,aAAA,EAAY,MAAA;AAAA,MAEZ,QAAA,EAAA;AAAA,wBAAAC,cAAA,CAAC,MAAA,EAAA,EAAK,CAAA,EAAE,GAAA,EAAI,CAAA,EAAE,GAAA,EAAI,KAAA,EAAM,IAAA,EAAK,MAAA,EAAO,IAAA,EAAK,EAAA,EAAG,GAAA,EAAI,EAAA,EAAG,GAAA,EAAI,CAAA;AAAA,wBACvDA,cAAA,CAAC,MAAA,EAAA,EAAK,CAAA,EAAE,yDAAA,EAA0D;AAAA;AAAA;AAAA,GACpE;AAEJ;AAEA,SAAS,SAAA,GAAY;AACnB,EAAA,uBACEA,cAAA;AAAA,I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KAAA;AAAA,QAAA;AAAA,UACC,WAAW,SAAA,IAAa,WAAA;AAAA,UAExB,uBAAA,EAAyB,EAAE,MAAA,EAAQ,IAAA;AAAK;AAAA,OAC1C;AAAA,IAEJ;AAEA,IAAA,uBAAOA,cAAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAU,kBAAkB,QAAA,EAAA,IAAA,EAAK,CAAA;AAAA,EAChD,CAAA;AACF","file":"index.cjs","sourcesContent":["import { useEffect, useRef, useState } from \"react\";\n\nimport type { CopyButtonProps } from \"./types\";\n\nfunction CopyIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" />\n <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" />\n </svg>\n );\n}\n\nfunction CheckIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n );\n}\n\nexport function CopyButton({ text, className }: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (timeoutRef.current != null) clearTimeout(timeoutRef.current);\n };\n }, []);\n\n const copy = () => {\n const clipboard = navigator.clipboard;\n if (!clipboard) return;\n // Only show the \"copied\" confirmation once the write actually succeeds.\n void clipboard\n .writeText(text)\n .then(() => {\n setCopied(true);\n if (timeoutRef.current != null) clearTimeout(timeoutRef.current);\n timeoutRef.current = setTimeout(() => setCopied(false), 2000);\n })\n .catch(() => {\n // Clipboard write failed; keep the idle state.\n });\n };\n\n return (\n <button\n type=\"button\"\n onClick={copy}\n className={className}\n aria-label={copied ? \"Copied\" : \"Copy code\"}\n data-copied={copied ? \"\" : undefined}\n >\n {copied ? <CheckIcon /> : <CopyIcon />}\n </button>\n );\n}\n","import { clsx } from \"clsx\";\nimport type { Components } from \"react-markdown\";\n\nimport { CopyButton } from \"./CopyButton\";\nimport type {\n CodeHighlighter,\n LLMMessageClassNames,\n LLMMessageComponents,\n} from \"./types\";\n\nexport function cx(...inputs: Array<string | undefined>): string | undefined {\n const result = clsx(inputs);\n return result === \"\" ? undefined : result;\n}\n\nexport function buildMarkdownComponents(\n classNames: LLMMessageClassNames | undefined,\n overrides: LLMMessageComponents | undefined,\n highlighter: CodeHighlighter | undefined,\n): Components {\n const cn = classNames ?? {};\n const o = overrides ?? {};\n const Highlighter = highlighter;\n\n // Merged class strings depend only on `classNames`, which is stable for the\n // lifetime of this (memoized) component map, so we compute them once here\n // instead of running `clsx` for every element on every render. Elements that\n // also receive a per-node `className` from react-markdown (inline code,\n // blockquote, list items) cache the static part and only re-run `clsx` when a\n // dynamic class is actually present.\n const c = {\n // Code — inline and fenced blocks.\n code: cx(\"llm-code\", cn.code),\n codeBlock: cx(\"llm-code-block\", cn.codeBlock),\n codeHeader: cx(\"llm-code-header\", cn.codeHeader),\n codeLanguage: cx(\"llm-code-language\", cn.codeLanguage),\n copyButton: cx(\"llm-copy-button\", cn.copyButton),\n\n // Tables — wrapper, table shell, and cells.\n tableWrapper: cx(\"llm-table-wrapper\", cn.tableWrapper),\n table: cx(\"llm-table\", cn.table),\n th: cx(\"llm-th\", cn.th),\n td: cx(\"llm-td\", cn.td),\n\n // Blockquote.\n blockquote: cx(\"llm-blockquote\", cn.blockquote),\n\n // Lists — ordered, unordered, items, and GFM task checkboxes.\n ul: cx(\"llm-ul\", cn.ul),\n ol: cx(\"llm-ol\", cn.ol),\n li: cx(\"llm-li\", cn.li),\n checkbox: cx(\"llm-checkbox\", cn.checkbox),\n\n // Paragraph.\n p: cx(\"llm-p\", cn.p),\n\n // Headings — h1 through h6.\n h1: cx(\"llm-h1\", cn.h1),\n h2: cx(\"llm-h2\", cn.h2),\n h3: cx(\"llm-h3\", cn.h3),\n h4: cx(\"llm-h4\", cn.h4),\n h5: cx(\"llm-h5\", cn.h5),\n h6: cx(\"llm-h6\", cn.h6),\n\n // Links and media.\n a: cx(\"llm-a\", cn.a),\n img: cx(\"llm-img\", cn.img),\n\n // Horizontal rule.\n hr: cx(\"llm-hr\", cn.hr),\n\n // Inline emphasis — bold, italic, strikethrough.\n strong: cx(\"llm-strong\", cn.strong),\n em: cx(\"llm-em\", cn.em),\n del: cx(\"llm-del\", cn.del),\n };\n\n // Combine a precomputed base class with an optional per-node class, avoiding a\n // `clsx` call entirely when there is no dynamic class to merge.\n const merge = (\n base: string | undefined,\n extra: string | undefined,\n ): string | undefined => (extra ? cx(base, extra) : base);\n\n return {\n // --- Code: inline `code` and fenced ``` blocks (pre is a passthrough). ---\n code({ node: _node, className, children, ...props }) {\n const match = /language-(\\w+)/.exec(className || \"\");\n const codeText = String(children).replace(/\\n$/, \"\");\n // A fenced block always spans its own lines (so its text contains a\n // newline) even when no language info string is present; inline code\n // never does. Relying on the `language-` class alone would misrender a\n // bare ``` fence as inline code.\n const isBlock = match != null || String(children).includes(\"\\n\");\n\n if (isBlock) {\n const language = match?.[1] ?? \"\";\n if (o.codeBlock) {\n const CodeBlock = o.codeBlock;\n return (\n <CodeBlock\n code={codeText}\n language={language}\n className={cn.codeBlock}\n />\n );\n }\n return (\n <div className={c.codeBlock}>\n <div className={c.codeHeader}>\n <span className={c.codeLanguage}>{language}</span>\n {o.copyButton ? (\n <o.copyButton text={codeText} className={cn.copyButton} />\n ) : (\n <CopyButton text={codeText} className={c.copyButton} />\n )}\n </div>\n <div className=\"llm-code-body\">\n {Highlighter ? (\n <Highlighter code={codeText} language={language} />\n ) : (\n <code className=\"llm-code-plain\">{codeText}</code>\n )}\n </div>\n </div>\n );\n }\n\n if (o.code) {\n const InlineCode = o.code;\n return (\n <InlineCode className={merge(c.code, className)}>\n {children}\n </InlineCode>\n );\n }\n\n return (\n <code className={merge(c.code, className)} {...props}>\n {children}\n </code>\n );\n },\n pre({ children }) {\n if (o.pre) {\n return <o.pre>{children}</o.pre>;\n }\n // Let the code component handle fenced blocks.\n return <>{children}</>;\n },\n\n // --- Tables: scrollable wrapper, shell, header and body cells. ---\n table({ children }) {\n if (o.table) {\n return <o.table className={cn.table}>{children}</o.table>;\n }\n return (\n <div className={c.tableWrapper}>\n <table className={c.table}>{children}</table>\n </div>\n );\n },\n th({ children, style }) {\n if (o.th) {\n return <o.th className={cn.th}>{children}</o.th>;\n }\n return (\n <th className={c.th} style={style}>\n {children}\n </th>\n );\n },\n td({ children, style }) {\n if (o.td) {\n return <o.td className={cn.td}>{children}</o.td>;\n }\n return (\n <td className={c.td} style={style}>\n {children}\n </td>\n );\n },\n\n // --- Blockquote. ---\n blockquote({ children, className, style }) {\n if (o.blockquote) {\n return <o.blockquote className={cn.blockquote}>{children}</o.blockquote>;\n }\n return (\n <blockquote className={merge(c.blockquote, className)} style={style}>\n {children}\n </blockquote>\n );\n },\n\n // --- Lists: ordered, unordered, items, and GFM task checkboxes. ---\n ul({ children }) {\n if (o.ul) {\n return <o.ul className={cn.ul}>{children}</o.ul>;\n }\n return <ul className={c.ul}>{children}</ul>;\n },\n ol({ children }) {\n if (o.ol) {\n return <o.ol className={cn.ol}>{children}</o.ol>;\n }\n return <ol className={c.ol}>{children}</ol>;\n },\n li({ children, className, style }) {\n if (o.li) {\n return <o.li className={cn.li}>{children}</o.li>;\n }\n return (\n <li className={merge(c.li, className)} style={style}>\n {children}\n </li>\n );\n },\n input({ node: _node, type, checked, disabled, ...props }) {\n if (type === \"checkbox\") {\n if (o.checkbox) {\n return (\n <o.checkbox checked={Boolean(checked)} className={cn.checkbox} />\n );\n }\n return (\n <input\n type=\"checkbox\"\n checked={Boolean(checked)}\n disabled\n aria-label={checked ? \"Completed task\" : \"Incomplete task\"}\n className={c.checkbox}\n readOnly\n />\n );\n }\n return (\n <input\n type={type}\n checked={checked}\n disabled={disabled}\n readOnly\n {...props}\n />\n );\n },\n\n // --- Paragraph. ---\n p({ children }) {\n if (o.p) {\n return <o.p className={cn.p}>{children}</o.p>;\n }\n return <p className={c.p}>{children}</p>;\n },\n\n // --- Headings: h1 through h6. ---\n h1({ children }) {\n if (o.h1) {\n return <o.h1 className={cn.h1}>{children}</o.h1>;\n }\n return <h1 className={c.h1}>{children}</h1>;\n },\n h2({ children }) {\n if (o.h2) {\n return <o.h2 className={cn.h2}>{children}</o.h2>;\n }\n return <h2 className={c.h2}>{children}</h2>;\n },\n h3({ children }) {\n if (o.h3) {\n return <o.h3 className={cn.h3}>{children}</o.h3>;\n }\n return <h3 className={c.h3}>{children}</h3>;\n },\n h4({ children }) {\n if (o.h4) {\n return <o.h4 className={cn.h4}>{children}</o.h4>;\n }\n return <h4 className={c.h4}>{children}</h4>;\n },\n h5({ children }) {\n if (o.h5) {\n return <o.h5 className={cn.h5}>{children}</o.h5>;\n }\n return <h5 className={c.h5}>{children}</h5>;\n },\n h6({ children }) {\n if (o.h6) {\n return <o.h6 className={cn.h6}>{children}</o.h6>;\n }\n return <h6 className={c.h6}>{children}</h6>;\n },\n\n // --- Links and media. ---\n a({ href, title, children }) {\n if (o.a) {\n return (\n <o.a href={href} title={title} className={cn.a}>\n {children}\n </o.a>\n );\n }\n return (\n <a\n href={href}\n title={title}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={c.a}\n >\n {children}\n </a>\n );\n },\n img({ node: _node, src, alt, title, className: _className, ...props }) {\n if (o.img) {\n const Image = o.img;\n return (\n <Image\n src={typeof src === \"string\" ? src : undefined}\n alt={alt}\n title={title}\n className={cn.img}\n />\n );\n }\n return (\n <img\n src={typeof src === \"string\" ? src : undefined}\n alt={alt}\n title={title}\n className={c.img}\n {...props}\n />\n );\n },\n\n // --- Horizontal rule. ---\n hr() {\n if (o.hr) {\n return <o.hr className={cn.hr} />;\n }\n return <hr className={c.hr} />;\n },\n\n // --- Inline emphasis: bold, italic, strikethrough. ---\n strong({ children }) {\n if (o.strong) {\n return <o.strong className={cn.strong}>{children}</o.strong>;\n }\n return <strong className={c.strong}>{children}</strong>;\n },\n em({ children }) {\n if (o.em) {\n return <o.em className={cn.em}>{children}</o.em>;\n }\n return <em className={c.em}>{children}</em>;\n },\n del({ children }) {\n if (o.del) {\n return <o.del className={cn.del}>{children}</o.del>;\n }\n return <del className={c.del}>{children}</del>;\n },\n };\n}\n","import { memo } from \"react\";\nimport ReactMarkdown, { type Components, type Options } from \"react-markdown\";\n\ntype RemarkPlugins = NonNullable<Options[\"remarkPlugins\"]>;\ntype RehypePlugins = NonNullable<Options[\"rehypePlugins\"]>;\n\nexport interface MarkdownBlockProps {\n content: string;\n components: Components;\n remarkPlugins: RemarkPlugins;\n rehypePlugins: RehypePlugins;\n}\n\n/**\n * A single top-level markdown block. Memoized so that stable blocks (every\n * block except the one currently being streamed) skip re-rendering — and thus\n * skip re-parsing and re-running KaTeX / code highlighting — when a new chunk\n * only changes the last block. `components` and the plugin arrays are stable\n * references, so the comparison effectively keys on `content`.\n */\nexport const MarkdownBlock = memo(function MarkdownBlock({\n content,\n components,\n remarkPlugins: remark,\n rehypePlugins,\n}: MarkdownBlockProps) {\n return (\n <ReactMarkdown\n remarkPlugins={remark}\n rehypePlugins={rehypePlugins}\n components={components}\n >\n {content}\n </ReactMarkdown>\n );\n});\n","import katex from \"katex\";\n\n/** Options controlling how {@link completePartialTokens} repairs the stream. */\nexport interface CompletePartialTokensOptions {\n /**\n * Progressively render unterminated math by closing the open constructs and\n * keeping the largest prefix KaTeX accepts. This applies to both *block* math\n * (`\\[…`, `$$…`, revealed row by row) and *inline* math (`$…`, `\\(…`, closed\n * in place). It is convenient but costs a synchronous KaTeX parse on every\n * chunk while the math streams. Set to `false` to instead hide the\n * unterminated math entirely until its closing delimiter arrives, skipping the\n * KaTeX work. Defaults to `true`.\n */\n showUnfinishedLatexBlocks?: boolean;\n}\n\n/**\n * Repairs partially-streamed markdown / LaTeX so that incomplete syntax does\n * not leak raw delimiter characters into the rendered output.\n *\n * While an LLM streams a response, the text often ends mid-token, e.g.\n * `**bold`, `` `code ``, `[label](http`, `$E = mc^2` or `\\(a + b`. Rendered\n * as-is, those dangling delimiters show up as literal junk (`**`, `` ` ``, `[`,\n * `$`, `\\(`). This function detects the unterminated constructs at the tail of\n * the string and:\n * - closes safe inline formatting so it renders as intended (`**bold` →\n * `**bold**`, `` `code `` → `` `code` ``);\n * - hides fragments that cannot be completed yet, namely incomplete links and\n * incomplete inline math (`$…`, `\\(…`);\n * - progressively renders incomplete *block* math (`\\[…`, `$$…`): instead of\n * hiding the whole block until it finishes streaming, it closes the open\n * environments/braces and renders the largest prefix KaTeX accepts, so a\n * long aligned block reveals row by row instead of popping in at the end.\n *\n * It is a no-op for already-complete text, so it is safe to run on every chunk.\n *\n * @param text The (possibly mid-stream) markdown string.\n * @returns The string with trailing incomplete tokens repaired.\n */\nexport function completePartialTokens(\n text: string,\n options?: CompletePartialTokensOptions,\n): string {\n if (!text) return text;\n\n const showUnfinishedLatexBlocks = options?.showUnfinishedLatexBlocks ?? true;\n\n // An unterminated fenced code block is fine on its own: remark renders it to\n // the end of the document and the partial content reads correctly as code,\n // so we must not touch any of the (markdown-looking) characters inside it.\n if (hasUnclosedCodeFence(text)) {\n return text;\n }\n\n const protectedSpans: string[] = [];\n const protect = (value: string): string =>\n `\\u0000llmph${protectedSpans.push(value) - 1}\\u0000`;\n\n // Protect complete fenced code blocks first (they may span several lines), so\n // their contents are never mistaken for markdown/LaTeX markers and the inline\n // scanner below does not see their backticks.\n let working = text.replace(/```[\\s\\S]*?```/g, (match) => protect(match));\n\n // Then handle inline code spans with proper CommonMark backtick-run matching:\n // a span opened by a run of N backticks is closed by the next run of exactly N\n // backticks (runs of a different width in between are literal content). This\n // correctly handles widths > 1, e.g. `` a`b ``. A trailing, still-unterminated\n // opener is the in-progress span; it is closed (so the code renders cleanly)\n // or hidden while it is still the very last thing streamed.\n working = protectInlineCode(working, protect);\n\n working = repairIncompleteMath(working, showUnfinishedLatexBlocks);\n working = hideIncompleteLink(working);\n working = completePartialTable(working);\n working = hideDanglingListMarker(working);\n working = closeUnbalancedEmphasis(working);\n\n // Restore protected spans. Repeat until no placeholder remains so a span that\n // happens to wrap an earlier placeholder is never left half-restored (which\n // would leak raw `\\u0000llmph1\\u0000` junk). Restored source text never\n // reintroduces the null-delimited marker, so this terminates; the no-progress\n // break is a belt-and-braces guard against a malformed marker.\n while (working.includes(\"\\u0000llmph\")) {\n const restored = working.replace(\n /\\u0000llmph(\\d+)\\u0000/g,\n (_match, index: string) => protectedSpans[Number(index)] ?? \"\",\n );\n if (restored === working) break;\n working = restored;\n }\n return working;\n}\n\n/**\n * Protects inline code spans, replacing each with an opaque placeholder so its\n * contents are not treated as markdown/LaTeX. Uses CommonMark backtick-run\n * matching: a span opened by a run of N backticks closes at the next run of\n * exactly N backticks; runs of any other width in between are literal content.\n *\n * The final, still-open backtick run (if any) is the in-progress span at the\n * tail of the stream. It is bounded to its own line (so later markdown is not\n * swallowed) and then:\n * - hidden, while the opener is the very last thing on the line with nothing\n * after it yet (the run may still be growing, e.g. `` ` `` → `` `` ``), so no\n * raw backticks flash; otherwise\n * - closed with a run matching the opener width, extending any partial closing\n * run already streamed (so `` `` ` `` becomes `` `` ` `` ``).\n */\nfunction protectInlineCode(\n text: string,\n protect: (value: string) => string,\n): string {\n let result = \"\";\n let i = 0;\n const n = text.length;\n\n while (i < n) {\n if (text[i] !== \"`\") {\n result += text[i];\n i++;\n continue;\n }\n\n // Measure the opening backtick run.\n let openEnd = i;\n while (openEnd < n && text[openEnd] === \"`\") openEnd++;\n const width = openEnd - i;\n\n // Look for a closing run of exactly `width` backticks on the same line.\n const lineEnd = text.indexOf(\"\\n\", openEnd);\n const limit = lineEnd === -1 ? n : lineEnd;\n let closeStart = -1;\n let scan = openEnd;\n while (scan < limit) {\n if (text[scan] !== \"`\") {\n scan++;\n continue;\n }\n let runEnd = scan;\n while (runEnd < limit && text[runEnd] === \"`\") runEnd++;\n if (runEnd - scan === width) {\n closeStart = scan;\n scan = runEnd;\n break;\n }\n scan = runEnd;\n }\n\n if (closeStart !== -1) {\n // Complete span: protect it verbatim.\n result += protect(text.slice(i, scan));\n i = scan;\n continue;\n }\n\n // Unterminated opener: this is the in-progress span at the tail.\n const lineTail = text.slice(i, limit);\n const hasContent = lineTail.length > width;\n if (!hasContent) {\n // Bare opener with nothing after it yet — hide it so no raw backticks show\n // while the run may still be growing.\n i = limit;\n continue;\n }\n // Close it, extending any partial closing run already at the line's end.\n let trailing = lineTail.length;\n while (trailing > 0 && lineTail[trailing - 1] === \"`\") trailing--;\n const need = Math.max(0, width - (lineTail.length - trailing));\n result += protect(lineTail + \"`\".repeat(need));\n i = limit;\n }\n\n return result;\n}\n\n/**\n * Completes a partially-streamed GFM table delimiter row.\n *\n * A table needs a full delimiter row (`| --- | --- |`) to be recognised, so\n * while it streams the buffer ends with a header row followed by a fragment like\n * `| ---`. Without a valid delimiter remark-gfm collapses both lines into a\n * paragraph (\"| Feature | Works | | ---\"). Once a delimiter fragment appears we\n * already know the column count from the header, so we expand the fragment to a\n * complete delimiter, preserving any alignment colons that have streamed in.\n */\nfunction completePartialTable(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length < 2) return text;\n\n const last = lines[lines.length - 1];\n // The candidate delimiter must contain only delimiter characters and at least\n // one dash; anything else (letters, etc.) means it is a header or body row.\n if (!/-/.test(last) || !/^[\\s|:-]*$/.test(last)) return text;\n\n const header = lines[lines.length - 2];\n if (!header.includes(\"|\")) return text;\n\n // If the table already has a delimiter row at or above the candidate, then\n // the candidate is just a body row that happens to contain only dashes/pipes\n // (not a streaming delimiter), so the table is complete and must be left\n // untouched. Walk up the contiguous block of pipe rows to detect that.\n for (let i = lines.length - 2; i >= 0; i--) {\n const line = lines[i];\n if (!line.includes(\"|\")) break;\n if (/-/.test(line) && /^[\\s|:-]*$/.test(line)) return text;\n }\n\n const columns = countTableColumns(header);\n lines[lines.length - 1] = buildDelimiterRow(last, columns);\n return lines.join(\"\\n\");\n}\n\n/** Counts the cells in a GFM table row, ignoring the outer pipes. */\nfunction countTableColumns(row: string): number {\n let inner = row.trim();\n if (inner.startsWith(\"|\")) inner = inner.slice(1);\n if (inner.endsWith(\"|\")) inner = inner.slice(0, -1);\n return inner.split(\"|\").length;\n}\n\n/**\n * Builds a delimiter row with `columns` cells, reusing any alignment colons\n * already present in the streamed fragment.\n */\nfunction buildDelimiterRow(fragment: string, columns: number): string {\n let inner = fragment.trim();\n if (inner.startsWith(\"|\")) inner = inner.slice(1);\n if (inner.endsWith(\"|\")) inner = inner.slice(0, -1);\n const existing = inner.split(\"|\").map((cell) => cell.trim());\n\n const cells = Array.from({ length: columns }, (_unused, index) => {\n const spec = existing[index] ?? \"\";\n const left = spec.startsWith(\":\");\n const right = spec.endsWith(\":\");\n if (left && right) return \":---:\";\n if (right) return \"---:\";\n if (left) return \":---\";\n return \"---\";\n });\n\n return `| ${cells.join(\" | \")} |`;\n}\n\n/**\n * Hides a trailing line that would be parsed as a setext heading underline.\n *\n * Mid-stream a bullet list arrives a character at a time, so the buffer briefly\n * ends with `paragraph\\n-` before the item text follows. In CommonMark a lone\n * run of dashes directly beneath a non-blank line is a setext H2 underline, so\n * a line like \"Unordered list:\" would flash as a heading until \"- Item\" streams\n * in. We drop the dangling marker until it gains content. A blank line above the\n * dashes makes them a thematic break instead, which is left untouched.\n *\n * The dash that opens a *nested* item is indented past the parent's marker, so\n * the underline is judged relative to the previous line's list context: a top\n * level paragraph treats a dash indented 0-3 spaces as a setext underline,\n * while under a list item the same range is measured from the item's own\n * content column (e.g. a third-level dash indented four spaces). A dash beyond\n * that range is an indented code line, not a heading, and is left untouched.\n */\nfunction hideDanglingListMarker(text: string): string {\n const match = text.match(/\\n([ \\t]*)-+[ \\t]*$/);\n if (match?.index == null) return text;\n\n const before = text.slice(0, match.index);\n const prevLine = before.slice(before.lastIndexOf(\"\\n\") + 1);\n if (prevLine.trim() === \"\") return text;\n\n const dashIndent = indentWidth(match[1]);\n\n // A setext underline may be indented up to three spaces past the column where\n // the paragraph it underlines begins. For a list item that column is the\n // item's content (after its marker); for plain text it is column zero.\n const listItem = prevLine.match(/^([ \\t]*(?:[-*+]|\\d+[.)])[ \\t]+)/);\n const baseIndent = listItem ? indentWidth(listItem[1]) : 0;\n if (dashIndent <= baseIndent + 3) return before;\n\n return text;\n}\n\n/** Visual width of leading whitespace, counting a tab as up to four columns. */\nfunction indentWidth(indent: string): number {\n let width = 0;\n for (const char of indent) {\n width += char === \"\\t\" ? 4 - (width % 4) : 1;\n }\n return width;\n}\n\n/**\n * True when a code fence is left open. Backtick (```) and tilde (~~~) fences are\n * counted separately so that a complete block of one kind that happens to\n * contain a line of the other kind is not mistaken for an unbalanced fence.\n */\nfunction hasUnclosedCodeFence(text: string): boolean {\n const backticks = (text.match(/^[ \\t]{0,3}```/gm) ?? []).length;\n const tildes = (text.match(/^[ \\t]{0,3}~~~/gm) ?? []).length;\n return backticks % 2 === 1 || tildes % 2 === 1;\n}\n\n/**\n * Drops a trailing, still-incomplete link or image, e.g. `[label`, `![alt` or\n * `[label](http`. Closed bracket fragments such as `arr[i]` or `[label]` are\n * left untouched to avoid hiding legitimate text.\n */\nfunction hideIncompleteLink(text: string): string {\n // Find the last \"[\" that is not an escaped LaTeX delimiter (\"\\[\").\n let open = -1;\n for (let i = text.length - 1; i >= 0; i--) {\n if (text[i] === \"[\" && text[i - 1] !== \"\\\\\") {\n open = i;\n break;\n }\n }\n if (open === -1) return text;\n\n const start = open > 0 && text[open - 1] === \"!\" ? open - 1 : open;\n const rest = text.slice(open);\n\n // Label is still open: \"[lab\" / \"![al\".\n if (!rest.includes(\"]\")) {\n return text.slice(0, start);\n }\n // Label closed, destination opened but not yet closed: \"[lab](http\".\n if (/^\\[[^\\]]*\\]\\([^)]*$/.test(rest)) {\n return text.slice(0, start);\n }\n return text;\n}\n\n/** A math delimiter that has been opened but not yet closed in the stream. */\ninterface OpenMath {\n /** Index of the opening delimiter in the source string. */\n index: number;\n /** The opening delimiter itself, e.g. `\"\\\\[\"` or `\"$$\"`. */\n open: string;\n /** The closing delimiter to append once repaired, empty for inline math. */\n close: string;\n /** Whether the math is block (display) math we try to render progressively. */\n block: boolean;\n /** Whether to render in KaTeX display mode when validating a candidate. */\n display: boolean;\n}\n\n/**\n * Repairs an unterminated LaTeX region at the tail of the stream.\n *\n * Both inline math (`$…`, `\\(…`) and block math (`\\[…`, `$$…`) are rendered\n * progressively: we close any open environments/braces and keep the largest\n * leading slice that KaTeX can parse, so the math reveals itself as it streams\n * instead of staying blank until the closing delimiter finally arrives. Inline\n * math additionally drops an incomplete trailing brace group (e.g. `\\text{ kc`)\n * rather than auto-closing it, so a half-streamed word does not flash in the\n * middle of running text. Set `showUnfinishedLatexBlocks` to `false` to instead\n * hide the unterminated math entirely until its closing delimiter arrives.\n */\nfunction repairIncompleteMath(\n text: string,\n showUnfinishedLatexBlocks: boolean,\n): string {\n const countOf = (pattern: RegExp): number =>\n (text.match(pattern) ?? []).length;\n\n const opens: OpenMath[] = [];\n\n // Display math: \\[ ... \\]\n if (countOf(/\\\\\\[/g) > countOf(/\\\\\\]/g)) {\n opens.push({\n index: text.lastIndexOf(\"\\\\[\"),\n open: \"\\\\[\",\n close: \"\\\\]\",\n block: true,\n display: true,\n });\n }\n\n // Inline math: \\( ... \\)\n if (countOf(/\\\\\\(/g) > countOf(/\\\\\\)/g)) {\n opens.push({\n index: text.lastIndexOf(\"\\\\(\"),\n open: \"\\\\(\",\n close: \"\\\\)\",\n block: false,\n display: false,\n });\n }\n\n if (countOf(/\\$\\$/g) % 2 === 1) {\n // Display math: $$ ... $$\n opens.push({\n index: text.lastIndexOf(\"$$\"),\n open: \"$$\",\n close: \"$$\",\n block: true,\n display: true,\n });\n } else {\n // Inline math: $ ... $. Mask complete \"$$\" pairs (keeping indices stable),\n // then ignore escaped \"\\$\" and currency like \"$5\" to avoid false positives.\n let masked = text.replace(/\\$\\$/g, \" \");\n // Also mask complete single-line \"$…$\" spans that contain a LaTeX command\n // (so they are real math, not \"$5\" currency). Their opening \"$\" may be\n // followed by a digit (e.g. \"$15 \\text{ g}$\"), which the currency guard\n // below would otherwise drop from the count while still counting the\n // closing \"$\", flipping the parity and hiding trailing content by mistake.\n masked = masked.replace(\n /(?<!\\\\)\\$(?!\\$)[^$\\n]*?\\\\[a-zA-Z][^$\\n]*?\\$/g,\n (m) => \" \".repeat(m.length),\n );\n // Same parity hazard for command-free numeric spans (e.g. \"$0$\", \"$15$\"):\n // the opening \"$\" is dropped by the currency guard below while the closing\n // \"$\" is still counted. Mask these balanced numeric spans too so neither\n // delimiter is counted. Plain currency (\"$5 and $10\") has prose between the\n // dollars, so it matches neither this nor the command mask and is left for\n // the currency guard to handle.\n masked = masked.replace(\n /(?<!\\\\)\\$(?!\\$)\\d[\\d\\s.,+\\-*/=]*\\$/g,\n (m) => \" \".repeat(m.length),\n );\n const dollars = inlineMathDollarIndices(masked);\n if (dollars.length % 2 === 1) {\n opens.push({\n index: dollars[dollars.length - 1],\n open: \"$\",\n close: \"$\",\n block: false,\n display: false,\n });\n }\n }\n\n const valid = opens.filter((entry) => entry.index >= 0);\n if (valid.length === 0) return text;\n\n // The earliest opener marks where the incomplete math region begins; anything\n // after it is part of the unterminated construct.\n const open = valid.reduce((a, b) => (b.index < a.index ? b : a));\n const before = text.slice(0, open.index);\n\n // When progressive rendering is disabled, hide the unterminated math (inline\n // or block) until its closing delimiter arrives, skipping the KaTeX cost.\n if (!showUnfinishedLatexBlocks) {\n return before;\n }\n\n const inner = text.slice(open.index + open.open.length);\n const body = bestRenderableMathBody(inner, open.display, open.block);\n if (body == null) return before;\n\n // Reproduce the original fenced layout so the markdown math parser can detect\n // the closing delimiter. When the block opens on its own line (`\\[\\n…`), the\n // closing delimiter must also sit on its own line; otherwise micromark treats\n // the run as inline math, never finds the closing fence, and KaTeX renders a\n // parse error that swallows the trailing delimiter.\n const blockLayout = /^[ \\t]*\\r?\\n/.test(inner);\n if (!blockLayout) {\n return before + open.open + body + open.close;\n }\n const opener =\n before === \"\" || before.endsWith(\"\\n\") ? open.open : `\\n${open.open}`;\n return `${before}${opener}${body.replace(/\\s+$/, \"\")}\\n${open.close}`;\n}\n\n/**\n * Returns the indices of the unescaped single `$` characters that act as inline\n * math delimiters in `masked` (complete `$$`/`$…$` spans are expected to have\n * been blanked out by the caller already).\n *\n * A `$` directly followed by a digit is normally currency (`$5`) and ignored.\n * The exception is a span whose body merely *starts* with a number but contains\n * a LaTeX command, e.g. `$1288 \\text{ kcal}`: the `\\text` proves it is real\n * math, so the opening `$` must count as a delimiter instead of being mistaken\n * for `$1288` currency. The span is scanned only up to the next unescaped `$`,\n * a newline, or the end of the string, since inline math stays on one line.\n */\nfunction inlineMathDollarIndices(masked: string): number[] {\n const indices: number[] = [];\n const pattern = /(?<!\\\\)\\$/g;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(masked)) != null) {\n const index = match.index;\n if (/\\d/.test(masked[index + 1] ?? \"\")) {\n const rest = masked.slice(index + 1);\n const end = rest.search(/(?<!\\\\)\\$|\\n/);\n const span = end === -1 ? rest : rest.slice(0, end);\n if (!/\\\\[a-zA-Z]/.test(span)) continue;\n }\n indices.push(index);\n }\n return indices;\n}\n\n/**\n * Returns the largest leading slice of incomplete block-math content that KaTeX\n * can render, with its open environments and braces closed, or `null` when no\n * usable prefix exists yet (in which case the caller hides the fragment).\n *\n * When an environment is still open (e.g. `\\begin{aligned}` mid-stream) we\n * prefer revealing only the complete rows so each equation appears fully formed,\n * falling back to a token-level repair so single-line blocks still stream in.\n */\nfunction bestRenderableMathBody(\n inner: string,\n display: boolean,\n block: boolean,\n): string | null {\n const candidates = unclosedEnvironments(inner).length > 0\n ? [closeOpenMathConstructs(truncateToLastRow(inner)), closeOpenMathConstructs(trimIncompleteMathTail(inner))]\n : [closeOpenMathConstructs(trimIncompleteMathTail(inner))];\n\n // Inline math is short and sits in running text, so a half-streamed brace\n // group (e.g. `\\text{ kc`) would flash a partial word that then changes. For\n // inline math we therefore prefer dropping the incomplete trailing group and\n // keeping the largest stable prefix, only falling back to the brace-closing\n // candidates above when that prefix cannot render on its own.\n if (!block) {\n candidates.unshift(\n closeOpenMathConstructs(\n trimIncompleteMathTail(dropIncompleteBraceGroup(inner)),\n ),\n );\n }\n\n for (const candidate of candidates) {\n if (!hasRenderableMathContent(candidate)) continue;\n if (isRenderableMath(candidate, display)) return candidate;\n }\n return null;\n}\n\n/**\n * Cuts a math fragment back to just before its first still-open `{`, dropping\n * the entire incomplete brace group. Escaped braces (`\\{`, `\\}`) are ignored.\n * Returns the input unchanged when every group is already balanced.\n */\nfunction dropIncompleteBraceGroup(text: string): string {\n const stack: number[] = [];\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\\\\") {\n i++;\n continue;\n }\n if (char === \"{\") stack.push(i);\n else if (char === \"}\" && stack.length > 0) stack.pop();\n }\n if (stack.length === 0) return text;\n return text.slice(0, stack[0]);\n}\n\n/** True when a math body contains something other than empty environment scaffolding. */\nfunction hasRenderableMathContent(body: string): boolean {\n const stripped = body\n .replace(/\\\\(?:begin|end)\\s*\\{[^}]*\\}/g, \"\")\n .replace(/[\\s{}]/g, \"\");\n return stripped.length > 0;\n}\n\n/**\n * True when KaTeX can render the math body without raising a parse error.\n *\n * Uses the public, stable `renderToString` entry point (with `throwOnError`)\n * rather than any internal parse-only API, so it keeps working across KaTeX\n * upgrades. We only care whether it throws; the produced string is discarded.\n */\nfunction isRenderableMath(body: string, display: boolean): boolean {\n try {\n katex.renderToString(body, {\n displayMode: display,\n throwOnError: true,\n strict: false,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Keeps only the complete rows of a multi-line environment by cutting back to\n * the last row separator (`\\\\`), dropping the partially-streamed current row.\n * Returns an empty string when no full row has streamed yet.\n */\nfunction truncateToLastRow(inner: string): string {\n const lastRow = inner.lastIndexOf(\"\\\\\\\\\");\n if (lastRow === -1) return \"\";\n return inner.slice(0, lastRow + 2);\n}\n\n/**\n * Drops trailing tokens that cannot render on their own yet: surrounding\n * whitespace, a dangling backslash, an in-progress control word (`\\frac` may\n * still be `\\fra`), and a subscript/superscript with no argument. A complete\n * `\\\\` row separator is preserved.\n */\nfunction trimIncompleteMathTail(inner: string): string {\n let result = inner;\n let previous: string;\n do {\n previous = result;\n result = result.replace(/\\s+$/, \"\");\n // A trailing odd run of backslashes ends in a lone \"\\\" (an incomplete \"\\\\\"\n // or the start of a command); drop it. An even run is complete \"\\\\\".\n const backslashes = result.match(/\\\\+$/);\n if (backslashes != null && backslashes[0].length % 2 === 1) {\n result = result.slice(0, -1);\n }\n // A trailing control word is ambiguous mid-stream; drop it so it cannot be\n // an unknown (and therefore error-rendered) command.\n result = result.replace(/\\\\[a-zA-Z]+\\*?$/, \"\");\n // A subscript/superscript needs an argument that has not arrived yet.\n result = result.replace(/[_^]$/, \"\");\n } while (result !== previous);\n return result;\n}\n\n/**\n * Closes the constructs left open in a math fragment so KaTeX can parse it:\n * unmatched `\\left`, unbalanced `{` groups, and unclosed environments. Order is\n * a best effort; the caller validates the result with KaTeX regardless.\n */\nfunction closeOpenMathConstructs(inner: string): string {\n let result = inner;\n\n const lefts = (result.match(/\\\\left(?![a-zA-Z])/g) ?? []).length;\n const rights = (result.match(/\\\\right(?![a-zA-Z])/g) ?? []).length;\n result += \"\\\\right.\".repeat(Math.max(0, lefts - rights));\n\n result += \"}\".repeat(openBraceDepth(result));\n\n const environments = unclosedEnvironments(result);\n for (let i = environments.length - 1; i >= 0; i--) {\n result += `\\\\end{${environments[i]}}`;\n }\n return result;\n}\n\n/** Counts unclosed `{` groups, ignoring escaped braces (`\\{`, `\\}`). */\nfunction openBraceDepth(text: string): number {\n let depth = 0;\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\\\\") {\n i++;\n continue;\n }\n if (char === \"{\") depth++;\n else if (char === \"}\" && depth > 0) depth--;\n }\n return depth;\n}\n\n/**\n * Returns the names of environments opened with `\\begin{…}` but not yet closed\n * with a matching `\\end{…}`, outermost first.\n */\nfunction unclosedEnvironments(text: string): string[] {\n const stack: string[] = [];\n const pattern = /\\\\(begin|end)\\s*\\{([^}]*)\\}/g;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(text)) != null) {\n const name = match[2];\n if (match[1] === \"begin\") {\n stack.push(name);\n } else {\n const index = stack.lastIndexOf(name);\n if (index !== -1) stack.splice(index, 1);\n else stack.pop();\n }\n }\n return stack;\n}\n\n/**\n * Closes unterminated emphasis runs: ~~strike~~, **bold**, *italic*, __bold__\n * and _italic_.\n */\nfunction closeUnbalancedEmphasis(text: string): string {\n let result = text;\n result = closeRunMarker(result, \"~~\");\n // Close a single \"*\" first so a \"***\" opener becomes \"*\" + \"**\" and both\n // halves get closed, yielding a balanced \"***…***\".\n result = closeSingleAsterisk(result);\n result = closeRunMarker(result, \"**\");\n result = closeSingleUnderscore(result);\n result = closeDoubleUnderscore(result);\n return result;\n}\n\n/**\n * True when the marker at `index` begins a delimiter run that could open\n * emphasis: it sits at the start of the string or directly after a non-word\n * character (whitespace or punctuation). Underscores require this so intra-word\n * usage (`snake_case`, `__init__`) is never treated as a dangling emphasis\n * opener.\n */\nfunction opensAtWordBoundary(text: string, index: number): boolean {\n if (index <= 0) return true;\n // Whitespace or punctuation before the marker counts as a boundary; an\n // alphanumeric character (or another underscore) does not, so intra-word\n // usage (`snake_case`, `__init__`) is never treated as a dangling opener\n // while a leading-punctuation case like `(_italic` still closes.\n return !/[\\p{L}\\p{N}_]/u.test(text[index - 1]);\n}\n\n/**\n * Closes a single `_` italic marker. `__` pairs are masked out first, and the\n * marker is only closed when it both opens at a word boundary and sits directly\n * before a non-space character, so `snake_case` is left alone.\n */\nfunction closeSingleUnderscore(text: string): string {\n const masked = text.replace(/__/g, \"\");\n const count = (masked.match(/_/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"_\");\n const after = text.slice(lastIndex + 1);\n if (after.length === 0 || /^[\\s_]/.test(after)) return text;\n if (!opensAtWordBoundary(text, lastIndex)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"_\");\n}\n\n/**\n * Closes a `__` bold marker when it is unbalanced, opens at a word boundary,\n * and is directly followed by a non-space character (so `a__b` and `__init__`\n * are left untouched).\n */\nfunction closeDoubleUnderscore(text: string): string {\n const count = (text.match(/__/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"__\");\n const after = text.slice(lastIndex + 2);\n if (after.length === 0 || /^\\s/.test(after)) return text;\n if (!opensAtWordBoundary(text, lastIndex)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"__\");\n}\n\n/**\n * Blanks out asterisks that belong to *block* constructs rather than inline\n * emphasis so they never skew the emphasis parity count: thematic breaks\n * (`***`, `* * *`) and line-leading list bullets (`* item`) at any\n * indentation. Each match is replaced with spaces of equal length so string\n * indices stay stable for the callers that still use the original text.\n */\nfunction maskBlockAsterisks(text: string): string {\n return text\n .replace(/^[ \\t]*\\*(?:[ \\t]*\\*){2,}[ \\t]*$/gm, (m) => \" \".repeat(m.length))\n .replace(/^[ \\t]*\\*(?=[ \\t])/gm, (m) => \" \".repeat(m.length));\n}\n\n/**\n * Closes a two-character emphasis marker (`**` or `~~`) when it is unbalanced\n * and the final marker looks like an opener (immediately followed by a\n * non-space character), which avoids touching list markers or operators.\n */\nfunction closeRunMarker(text: string, marker: string): string {\n const escaped = marker.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Asterisk runs share their character with bullets and thematic breaks, so\n // count them on a text whose block asterisks have been masked away.\n const countSource = marker.includes(\"*\") ? maskBlockAsterisks(text) : text;\n const count = (countSource.match(new RegExp(escaped, \"g\")) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(marker);\n const after = text.slice(lastIndex + marker.length);\n if (after.length === 0 || /^\\s/.test(after)) return text;\n\n return insertBeforeTrailingWhitespace(text, marker);\n}\n\n/**\n * Closes a single `*` italic marker. `**` pairs are masked out first, and the\n * marker is only closed when it sits directly before a non-space character so\n * bullet markers (`* item`) and multiplication (`2 * 3`) are left alone.\n */\nfunction closeSingleAsterisk(text: string): string {\n // Mask block-level asterisks (bullets, thematic breaks) and \"**\" pairs so the\n // marker is not miscounted as a dangling italic opener. Masking only affects\n // the parity count; `lastIndexOf` still operates on the original text.\n const masked = maskBlockAsterisks(text).replace(/\\*\\*/g, \"\");\n const count = (masked.match(/\\*/g) ?? []).length;\n if (count % 2 === 0) return text;\n\n const lastIndex = text.lastIndexOf(\"*\");\n const after = text.slice(lastIndex + 1);\n if (after.length === 0 || /^[\\s*]/.test(after)) return text;\n\n return insertBeforeTrailingWhitespace(text, \"*\");\n}\n\n/**\n * Appends a closing emphasis marker, but places it before any trailing\n * whitespace. A closer such as `**` is only valid when it directly follows a\n * non-space character, so `**bold ` must become `**bold** ` rather than the\n * un-renderable `**bold **`.\n */\nfunction insertBeforeTrailingWhitespace(text: string, marker: string): string {\n const trailing = text.match(/\\s+$/)?.[0] ?? \"\";\n const core = text.slice(0, text.length - trailing.length);\n return core + marker + trailing;\n}\n","/**\n * Matches a fenced code block or an inline code span. Shared by\n * {@link preprocessLaTeX} and {@link escapeBrackets} so both functions treat\n * code identically; composed into the larger patterns below via `.source`.\n */\nconst CODE_SPAN = /```[\\s\\S]*?```|``[^\\n]*?``|`[^`\\n]+`/;\n\n/**\n * Preprocesses LaTeX content by replacing delimiters and escaping certain characters.\n *\n * @param content The input string containing LaTeX expressions.\n * @returns The processed string with replaced delimiters and escaped characters.\n */\nexport function preprocessLaTeX(content: string): string {\n // Step 1: Protect code blocks\n const codeBlocks: string[] = [];\n content = content.replace(\n new RegExp(`(${CODE_SPAN.source})`, \"g\"),\n (_match, code) => {\n codeBlocks.push(code);\n return `<<CODE_BLOCK_${codeBlocks.length - 1}>>`;\n },\n );\n\n // Step 2: Protect existing LaTeX expressions. This is what makes the currency\n // escaping in Step 3 safe: by pulling complete `$$…$$` / `\\[…\\]` / `\\(…\\)`\n // regions out of the string first, the `\\$(?=\\d)` pass below cannot corrupt a\n // `$` that legitimately belongs to a math expression (e.g. `$$x = $5$$`).\n //\n // Single-dollar inline math whose content begins with a digit (e.g.\n // `$15 \\text{ g}$`) is protected too: without this its opening `$` would be\n // escaped as currency in Step 3, unbalancing the delimiters so remark-math\n // swallows the rest of the paragraph as one math region. Two shapes qualify:\n // 1. spans containing a LaTeX command (`\\…`), e.g. `$15 \\text{ g}$`;\n // 2. balanced spans whose content is purely numeric/math (digits, spaces\n // and basic operators, no prose letters), e.g. `$0$` or `$1288 / 3$`.\n // Both leave plain currency prose like `$5 and $10` for Step 3, because that\n // text contains letters between the dollars and so matches neither shape.\n const latexExpressions: string[] = [];\n content = content.replace(\n /(\\$\\$[\\s\\S]*?\\$\\$|\\\\\\[[\\s\\S]*?\\\\\\]|\\\\\\(.*?\\\\\\)|\\$(?!\\$)[^$\\n]*?\\\\[a-zA-Z][^$\\n]*?\\$|\\$(?!\\$)\\d[\\d\\s.,+\\-*/=]*\\$)/g,\n (match) => {\n latexExpressions.push(match);\n return `<<LATEX_${latexExpressions.length - 1}>>`;\n },\n );\n\n // Step 3: Escape dollar signs that are likely currency indicators\n content = content.replace(/\\$(?=\\d)/g, \"\\\\$\");\n\n // Step 4: Restore LaTeX expressions\n content = content.replace(\n /<<LATEX_(\\d+)>>/g,\n (_, index) => latexExpressions[parseInt(index, 10)],\n );\n\n // Step 5: Restore code blocks\n content = content.replace(\n /<<CODE_BLOCK_(\\d+)>>/g,\n (_, index) => codeBlocks[parseInt(index, 10)],\n );\n\n // Step 6: Apply additional escaping functions\n content = escapeBrackets(content);\n content = escapeMhchem(content);\n\n return content;\n}\n\nexport function escapeBrackets(text: string): string {\n const pattern = new RegExp(\n `(${CODE_SPAN.source})|` +\n /\\\\\\[((?:[\\s\\S]*?[^\\\\])?)\\\\]|\\\\\\((.*?)\\\\\\)/.source,\n \"g\",\n );\n return text.replace(\n pattern,\n (\n match: string,\n codeBlock: string | undefined,\n squareBracket: string | undefined,\n roundBracket: string | undefined,\n ): string => {\n if (codeBlock != null) {\n return codeBlock;\n } else if (squareBracket != null) {\n return `$$${squareBracket}$$`;\n } else if (roundBracket != null) {\n return `$${roundBracket}$`;\n }\n return match;\n },\n );\n}\n\nexport function escapeMhchem(text: string): string {\n return text.replaceAll(\"$\\\\ce{\", \"$\\\\\\\\ce{\").replaceAll(\"$\\\\pu{\", \"$\\\\\\\\pu{\");\n}\n","import { Lexer, type Token } from \"marked\";\n\n/**\n * Footnote reference (`[^id]`) or definition (`[^id]:`). A footnote resolves\n * across top-level blocks — the reference points at a definition that may live\n * in another block — so a document containing either must be kept whole, since\n * independently-rendered subtrees can't see each other's definitions.\n *\n * The pattern requires at least one word/dash char inside `[^…]`, so a regex\n * character class such as `[^,]` or `[^\\d]` (common inside code) never matches\n * and so never forces a needless single-block fallback.\n */\nconst FOOTNOTE = /\\[\\^[\\w-]{1,200}\\]/;\n\n/** Counts `$$` runs in a string. */\nfunction countDollarRuns(text: string): number {\n let runs = 0;\n for (let i = 0; i < text.length - 1; i++) {\n if (text[i] === \"$\" && text[i + 1] === \"$\") {\n runs++;\n i++;\n }\n }\n return runs;\n}\n\n/** Counts occurrences of a fixed two-char escape sequence (e.g. `\\[`, `\\]`). */\nfunction countEscaped(text: string, second: string): number {\n let count = 0;\n for (let i = 0; i < text.length - 1; i++) {\n if (text[i] === \"\\\\\" && text[i + 1] === second) {\n count++;\n i++;\n }\n }\n return count;\n}\n\n/**\n * Whether a block ends inside an unterminated block-math region, which the\n * lexer would otherwise split at a blank line. Covers both `$$…$$` (odd number\n * of `$$` runs) and `\\[…\\]` display math (more openers than closers). Inline\n * `\\(…\\)` math never spans a blank line, so it needs no handling here.\n */\nfunction hasOpenBlockMath(text: string): boolean {\n if (countDollarRuns(text) % 2 === 1) {\n return true;\n }\n return countEscaped(text, \"[\") > countEscaped(text, \"]\");\n}\n\n/**\n * Splits a markdown string into its top-level blocks, preserving every\n * character so that concatenating the result reproduces the input. Each block\n * is a self-contained markdown string that renders identically whether parsed\n * alone or as part of the whole document.\n *\n * Can be called on the *raw* source: math grouping handles both `$$…$$` and\n * `\\[…\\]` directly, so callers may repair/preprocess each returned block\n * independently rather than processing the whole document on every chunk.\n *\n * Uses `marked`'s block lexer rather than a full remark/mdast parse: the lexer\n * is roughly an order of magnitude faster, which matters because this runs on\n * every streamed chunk. A few constructs need explicit handling on top of the\n * raw token stream:\n *\n * - **Block math** (`$$…$$` or `\\[…\\]` spanning a blank line): the lexer\n * doesn't know math and would split it at the blank line, so a token\n * following a block that ends inside an open math region is merged back in.\n * - **Whitespace** between blocks is attached to the preceding block so trailing\n * blank lines stay with the earlier block (and blocks remain append-only as\n * the last one streams).\n * - **Footnotes** and **link/image reference definitions** resolve across blocks\n * and would break if split, so such documents are returned as a single block.\n *\n * As a final safety net, if the reconstructed blocks don't concatenate back to\n * the source exactly, the whole source is returned as one block rather than\n * risking corrupted or dropped content.\n */\nexport function splitMarkdownBlocks(source: string): string[] {\n if (source === \"\" || /^\\s*$/.test(source)) {\n return [];\n }\n\n // Fast path: with no blank-line separator the document is, in practice, a\n // single top-level block, so skip the lexer entirely. Rendering it as one\n // block is always correct and avoids re-tokenising the whole string on every\n // streamed chunk of a single growing block (a long code fence or paragraph).\n if (!/\\n[ \\t]*\\n/.test(source)) {\n return [source];\n }\n\n // Footnotes resolve across blocks; keep the document whole.\n if (FOOTNOTE.test(source)) {\n return [source];\n }\n\n let tokens: Token[];\n try {\n tokens = Lexer.lex(source, { gfm: true });\n } catch {\n return [source];\n }\n\n const blocks: string[] = [];\n // Cursor into the original source. Each token's text is taken as a *verbatim*\n // slice of the source rather than `token.raw`: `marked` normalises the raw of\n // an incomplete trailing construct mid-stream (e.g. a half-typed list item\n // `- First ` becomes `- First\\n` — the dangling marker is trimmed and a\n // newline appended). The lengths match but the characters differ, so using\n // `raw` would corrupt the streaming block and trip the reconstruction guard,\n // collapsing the whole document into a single block on alternating chunks\n // (which resets the reveal wave and re-fades the entire message). Slicing the\n // source keeps every block byte-exact and append-only.\n let cursor = 0;\n for (const token of tokens) {\n // Link/image reference definitions resolve across blocks; keep whole.\n if (token.type === \"def\") {\n return [source];\n }\n\n const raw = token.raw;\n if (raw === \"\") {\n continue;\n }\n\n const end = Math.min(cursor + raw.length, source.length);\n const text = source.slice(cursor, end);\n cursor = end;\n\n const last = blocks.length - 1;\n const previous = last >= 0 ? blocks[last] : undefined;\n const mergeIntoPrevious =\n previous != null &&\n (token.type === \"space\" || hasOpenBlockMath(previous));\n\n if (mergeIntoPrevious) {\n blocks[last] += text;\n } else {\n blocks.push(text);\n }\n }\n\n if (blocks.length === 0) {\n return [source];\n }\n\n // Absorb any trailing source the tokens didn't account for onto the last\n // block so concatenation always reproduces the input exactly.\n if (cursor < source.length) {\n blocks[blocks.length - 1] += source.slice(cursor);\n }\n\n // Safety net: if anything was dropped or reordered, fall back to one block so\n // no characters are lost and cross-block constructs keep working.\n if (blocks.join(\"\") !== source) {\n return [source];\n }\n\n return blocks;\n}\n","import { useDeferredValue, useMemo, useRef } from \"react\";\n\nimport { completePartialTokens } from \"./completePartialTokens\";\nimport { preprocessLaTeX } from \"./preprocess\";\nimport { splitMarkdownBlocks } from \"./splitBlocks\";\n\nexport interface UseMarkdownBlocksOptions {\n /** Raw markdown source. */\n source: string;\n /**\n * Split into top-level blocks and cache stable (sealed) ones, or process the\n * whole message as a single block.\n */\n blockMemoization: boolean;\n /** Repair partially-streamed markdown/LaTeX before preprocessing. */\n repairPartialTokens: boolean;\n /** Show unfinished block math while streaming (only when repairing). */\n showUnfinishedLatexBlocks: boolean;\n /**\n * When enabled, render blocks synchronously so smooth reveal can animate the\n * active block every chunk; otherwise defer reconciliation for throughput.\n */\n smoothReveal: boolean;\n}\n\nexport interface UseMarkdownBlocksResult {\n /** Processed blocks ready for rendering (possibly deferred). */\n renderedBlocks: string[];\n /** Index of the active (currently streaming) block. */\n activeIndex: number;\n /** Processed source of the active block. */\n activeSource: string;\n}\n\n/**\n * Splits the raw source into top-level markdown blocks, repairs partial tokens\n * and preprocesses LaTeX per block, and caches stable blocks so streaming only\n * re-processes the last (growing) block.\n */\nexport function useMarkdownBlocks({\n source,\n blockMemoization,\n repairPartialTokens,\n showUnfinishedLatexBlocks,\n smoothReveal,\n}: UseMarkdownBlocksOptions): UseMarkdownBlocksResult {\n const prevSourceRef = useRef(\"\");\n\n // A block processor: repairs (closes partial tokens) then preprocesses LaTeX\n // for a single block, plus a cache of already-processed *stable* (sealed)\n // blocks keyed by their raw string. Both are rebuilt together whenever the\n // processing options change so stale results never leak. The order inside\n // `process` matters: `completePartialTokens` closes an unfinished `\\[…` so\n // that `preprocessLaTeX` can then convert the now-complete `\\[…\\]` to `$$…$$`.\n const processor = useMemo(() => {\n const cache = new Map<string, string>();\n const process = (block: string): string => {\n const repaired = repairPartialTokens\n ? completePartialTokens(block, { showUnfinishedLatexBlocks })\n : block;\n return preprocessLaTeX(repaired);\n };\n return { cache, process };\n }, [repairPartialTokens, showUnfinishedLatexBlocks]);\n\n // With memoization, split the raw source into top-level blocks so only the\n // last (streaming) block is re-processed and re-rendered; stable blocks are\n // pulled from the cache. Streaming is append-only, so every block except the\n // last is sealed and never changes — caching them means a growing message\n // only repairs/preprocesses the last block each chunk instead of the whole\n // document. Without memoization the whole message is processed as one block,\n // which preserves cross-block constructs (footnotes, reference definitions).\n const blocks = useMemo(() => {\n if (source === \"\") {\n prevSourceRef.current = source;\n return [];\n }\n if (!source.startsWith(prevSourceRef.current)) {\n processor.cache.clear();\n }\n prevSourceRef.current = source;\n if (!blockMemoization) {\n return [processor.process(source)];\n }\n const rawBlocks = splitMarkdownBlocks(source);\n const lastIndex = rawBlocks.length - 1;\n return rawBlocks.map((raw, index) => {\n if (index === lastIndex) {\n // The streaming block changes every chunk; always process it fresh.\n return processor.process(raw);\n }\n let done = processor.cache.get(raw);\n if (done === undefined) {\n done = processor.process(raw);\n processor.cache.set(raw, done);\n }\n return done;\n });\n }, [source, blockMemoization, processor]);\n\n // Render the block list from a deferred copy of `blocks`. On a fast stream the\n // synchronous render keeps showing the previously-rendered blocks while React\n // reconciles the new (and heavier) block subtree at low priority, so a burst\n // of chunks coalesces instead of forcing a full synchronous re-parse/re-render\n // on every chunk. `useDeferredValue` does this without an effect or extra\n // state (so it can't loop), and the first render is immediate.\n //\n // Smooth reveal is the exception: it animates the active block per chunk and\n // needs the freshly-rendered blocks every frame. Deferring would let the\n // reveal wave reset (and `--llm-reveal` drop to 0) while a just-finished\n // block's fade spans are still mounted, making committed code blocks / lists /\n // blockquotes flicker. So when the reveal is on, render the current blocks\n // synchronously; the deferral is purely a throughput win for the common\n // non-animated case.\n const deferredBlocks = useDeferredValue(blocks);\n const renderedBlocks = smoothReveal ? blocks : deferredBlocks;\n\n const activeIndex = renderedBlocks.length - 1;\n const activeSource = renderedBlocks[activeIndex] ?? \"\";\n\n return { renderedBlocks, activeIndex, activeSource };\n}\n","import type { Element, ElementContent, Root, Text } from \"hast\";\n\n/**\n * Shared, mutable state for the smooth-reveal rehype plugin. Lives in a ref on\n * the component so it survives re-renders. `committedUnits` is the number of\n * leading reveal units that are already fully shown; they render as plain\n * markup (no span) so the per-character DOM stays bounded to the active wave.\n */\nexport interface SmoothRevealState {\n committedUnits: number;\n}\n\nexport interface FadeRehypePluginOptions {\n state: SmoothRevealState;\n /** Called once per transform with the total reveal-unit count. */\n onTotal: (total: number) => void;\n}\n\nconst CHAR_CLASS = \"llm-char\";\nconst FADE_CLASS = \"llm-fade\";\nconst BLOCK_CLASS = \"llm-fade-block\";\nconst BLOCK_INLINE_CLASS = \"llm-fade-block-inline\";\n/**\n * Block math renders all-or-nothing (KaTeX only produces output once the whole\n * formula has streamed in), so a soft opacity fade just looks like a flash.\n * These blocks are tagged to appear instantly the moment the wave reaches them\n * instead of fading.\n */\nconst BLOCK_SNAP_CLASS = \"llm-fade-block-snap\";\n\n/** Tags whose entire subtree fades in as a single unit (wrapped in a div). */\nconst BLOCK_TAGS = new Set([\"pre\", \"table\", \"hr\"]);\n\n/**\n * Tags that carry their own box decoration (a border, marker, or background)\n * but still contain flowing text we want to reveal per-character. We tag the\n * element itself with the reveal index of its first child so the decoration\n * fades in with the wave, then descend so the text inside still streams in\n * letter by letter. `code` here is always inline code (block code lives inside\n * a `pre`, which is a complex unit we never descend into).\n */\nconst DECORATED_TAGS = new Set([\"blockquote\", \"li\", \"code\"]);\n\nfunction hasClass(node: Element, name: string): boolean {\n const className = node.properties?.className;\n if (Array.isArray(className)) {\n return className.includes(name);\n }\n return typeof className === \"string\" && className.split(/\\s+/).includes(name);\n}\n\nfunction isComplexElement(node: Element): boolean {\n return (\n BLOCK_TAGS.has(node.tagName) ||\n node.tagName === \"img\" ||\n // KaTeX output (rehype-katex). `katex-display` is the block wrapper; a bare\n // `katex` is inline math. Either way we fade the whole formula as one unit.\n hasClass(node, \"katex-display\") ||\n hasClass(node, \"katex\")\n );\n}\n\n/**\n * A rehype plugin factory that wraps newly-streamed rendered text in\n * per-character `<span>`s (and complex blocks in a single wrapper) and tags\n * each with its document-order index via a `--i` custom property. The actual\n * fade is computed in CSS from `--i` and a single `--llm-reveal` position that\n * the component advances over time, so the opacity of every unit is a pure\n * function of state: re-parses of the streaming source never cause a flicker.\n */\nexport function createFadeRehypePlugin(options: FadeRehypePluginOptions) {\n const { state, onTotal } = options;\n\n return function fadeRehypePlugin() {\n return (tree: Root): void => {\n const counter = { unit: 0 };\n\n const makeFadeBlock = (\n node: Element,\n inline: boolean,\n index: number,\n snap = false,\n ): Element => {\n const className = inline\n ? [BLOCK_CLASS, BLOCK_INLINE_CLASS]\n : snap\n ? [BLOCK_CLASS, BLOCK_SNAP_CLASS]\n : [BLOCK_CLASS];\n return {\n type: \"element\",\n tagName: inline ? \"span\" : \"div\",\n properties: {\n className,\n style: `--i:${index}`,\n },\n children: [node],\n };\n };\n\n const processText = (node: Text): ElementContent[] => {\n // Leave structural whitespace untouched. Markdown places whitespace-only\n // text nodes (e.g. newlines) between block siblings such as the `<li>`s\n // of a list. A flex/grid container ignores such a text node, but wrapping\n // it in a `<span>` turns it into a real (element) flex item that adds a\n // phantom `gap`, so the container is one gap taller while animating and\n // snaps back once the spans are committed to plain text. These nodes\n // carry no visible glyph, so there is nothing to fade anyway.\n if (/^\\s*$/.test(node.value)) {\n return [node];\n }\n const chars = Array.from(node.value);\n const out: ElementContent[] = [];\n let plain = \"\";\n\n const flushPlain = () => {\n if (plain) {\n out.push({ type: \"text\", value: plain });\n plain = \"\";\n }\n };\n\n for (const ch of chars) {\n const index = counter.unit++;\n if (index < state.committedUnits) {\n plain += ch;\n continue;\n }\n flushPlain();\n out.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [CHAR_CLASS], style: `--i:${index}` },\n children: [{ type: \"text\", value: ch }],\n });\n }\n\n flushPlain();\n return out;\n };\n\n const processComplex = (node: Element): ElementContent => {\n const index = counter.unit++;\n if (index < state.committedUnits) {\n // Already revealed: render verbatim so the DOM stays minimal.\n return node;\n }\n const inline = node.tagName === \"img\" || hasClass(node, \"katex\");\n // Block math (`katex-display`) appears instantly rather than fading.\n const snap = hasClass(node, \"katex-display\");\n return makeFadeBlock(node, inline, index, snap);\n };\n\n const stampDecoration = (node: Element, index: number): void => {\n const className = node.properties?.className;\n const classes = Array.isArray(className)\n ? className.map(String)\n : typeof className === \"string\"\n ? className.split(/\\s+/).filter(Boolean)\n : [];\n classes.push(FADE_CLASS);\n node.properties = {\n ...node.properties,\n className: classes,\n style: `--i:${index}`,\n };\n };\n\n const processChildren = (parent: Root | Element): void => {\n const next: ElementContent[] = [];\n for (const child of parent.children) {\n if (child.type === \"text\") {\n next.push(...processText(child));\n } else if (child.type === \"element\") {\n if (isComplexElement(child)) {\n next.push(processComplex(child));\n } else {\n if (DECORATED_TAGS.has(child.tagName)) {\n // Tag with the index of the first unit inside so the box\n // decoration fades in with the content; do not consume a unit.\n stampDecoration(child, counter.unit);\n }\n processChildren(child);\n next.push(child);\n }\n } else {\n // Comments / doctype / raw: keep as-is, no reveal unit.\n next.push(child as ElementContent);\n }\n }\n parent.children = next;\n };\n\n processChildren(tree);\n onTotal(counter.unit);\n };\n };\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { CSSProperties, RefObject } from \"react\";\n\nimport { createFadeRehypePlugin, type SmoothRevealState } from \"./smoothReveal\";\n\n/** The rehype plugin produced by {@link createFadeRehypePlugin}. */\ntype FadePlugin = ReturnType<typeof createFadeRehypePlugin>;\n\n// Run the wave synchronously after commit but before paint, so the\n// `--llm-reveal` variable is only ever written to a freshly-committed tree\n// (never to the previous, still-mounted tree during render). On the server\n// there is no layout to flush, so fall back to a passive effect to avoid the\n// React \"useLayoutEffect does nothing on the server\" warning.\nconst useIsomorphicLayoutEffect =\n typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n// Width of the smooth-reveal fade gradient, in reveal units (characters). A\n// larger value spreads each fade over more neighbouring characters for a softer\n// trailing edge. Shared with the CSS `--llm-ramp` fallback.\nconst SMOOTH_RAMP = 6;\n\nexport interface UseSmoothRevealOptions {\n /**\n * The markdown source of the *active* (currently streaming) block; its growth\n * is what drives the reveal wave. With block memoization this is the last\n * block; without it, the whole message.\n */\n activeSource: string;\n /**\n * Identity of the active block (its index). When it changes a new block has\n * started streaming, so the wave resets and animates the new block from its\n * own start.\n */\n activeKey: number;\n /** Whether smooth rendering is enabled. */\n enabled: boolean;\n /** Reveal window for a freshly-arrived chunk, in milliseconds. */\n duration: number;\n}\n\nexport interface UseSmoothRevealResult {\n /** Attach to the rendered root element; the wave position is set on it. */\n rootRef: RefObject<HTMLDivElement | null>;\n /**\n * The smooth-reveal rehype plugin to attach to the active block, or `null`\n * when smooth reveal is disabled. KaTeX is composed separately by the caller\n * so it runs only on blocks that actually contain math.\n */\n fadePlugin: FadePlugin | null;\n /** Extra CSS custom properties to spread onto the root, or `undefined`. */\n revealStyle: CSSProperties | undefined;\n}\n\n/**\n * Drives the smooth character-by-character reveal of the active block.\n *\n * The opacity of every reveal unit is computed in CSS from its `--i` index and\n * a single `--llm-reveal` position on the root. That position is a float in unit\n * space that only ever moves forward, so the reveal is monotonic and never\n * flickers even as `react-markdown` re-parses the growing source. A new chunk\n * re-targets the position and recomputes the speed from the *current* position,\n * which merges any unfinished leftover into the new chunk's wave over one fresh\n * `duration` window. Units the wave has already passed are committed to plain\n * markup so the live per-character DOM stays bounded to the active wave.\n *\n * Only the active block carries the fade plugin, so its reveal indices are\n * local to that block (they restart at 0). When the active block changes the\n * wave resets so the new block animates from its own start, while the\n * just-finished block flips to plain markup.\n */\nexport function useSmoothReveal({\n activeSource,\n activeKey,\n enabled,\n duration,\n}: UseSmoothRevealOptions): UseSmoothRevealResult {\n const rootRef = useRef<HTMLDivElement>(null);\n const revealStateRef = useRef<SmoothRevealState>({ committedUnits: 0 });\n const positionRef = useRef(0);\n const targetRef = useRef(0);\n const velocityRef = useRef(0);\n const totalRef = useRef(0);\n const rafRef = useRef<number | null>(null);\n const lastTsRef = useRef(0);\n const prevSourceRef = useRef(\"\");\n const activeKeyRef = useRef(activeKey);\n const snapRef = useRef(false);\n const [, forceCommit] = useState(0);\n\n const setRevealVar = (value: number) => {\n rootRef.current?.style.setProperty(\"--llm-reveal\", String(value));\n };\n\n // A new active block began streaming: reset the wave so the new block reveals\n // from its own start (its reveal indices restart at 0) instead of being\n // treated as a wholesale content replacement (which would snap it visible).\n // Only refs are touched here; `--llm-reveal` is written from the layout effect\n // after commit so a reset can never blank out the just-finished block's fade\n // spans (which are still mounted until React commits the new tree).\n if (enabled && activeKey !== activeKeyRef.current) {\n activeKeyRef.current = activeKey;\n positionRef.current = 0;\n targetRef.current = 0;\n velocityRef.current = 0;\n revealStateRef.current.committedUnits = 0;\n prevSourceRef.current = \"\";\n snapRef.current = false;\n }\n\n // Only genuine appends animate. When the content shrinks (e.g. scrubbing\n // backwards) or is replaced wholesale, there is no newly-streamed text, so we\n // reveal everything instantly with no animation: render every unit as plain\n // markup this pass and snap the wave to the end in the effect below. For an\n // append we just advance the committed boundary so units the wave has already\n // passed render as plain markup. Done during render so the plugin sees the\n // correct state on this same pass; it is idempotent for a given source.\n if (enabled) {\n const isAppend = activeSource.startsWith(prevSourceRef.current);\n if (isAppend) {\n const safe = Math.floor(positionRef.current) - SMOOTH_RAMP;\n if (safe > revealStateRef.current.committedUnits) {\n revealStateRef.current.committedUnits = safe;\n }\n } else {\n // Content shrank or was replaced: render every unit as plain markup this\n // pass (committed boundary past the end) so there are no fade spans, and\n // let the layout effect snap `--llm-reveal` to the end after commit.\n snapRef.current = true;\n revealStateRef.current.committedUnits = Number.MAX_SAFE_INTEGER;\n }\n prevSourceRef.current = activeSource;\n }\n\n const fadePlugin = useMemo<FadePlugin | null>(() => {\n if (!enabled) {\n return null;\n }\n return createFadeRehypePlugin({\n state: revealStateRef.current,\n onTotal: (total) => {\n totalRef.current = total;\n },\n });\n }, [enabled]);\n\n // Drive `--llm-reveal` toward the end of the active block. Runs after commit\n // but before paint (layout effect) so the variable is written to the just\n // committed tree, never to the previous one during render. Re-runs on every\n // chunk (and when the active block changes) so the target/speed are\n // recomputed from the *current* position, which is what merges any unfinished\n // leftover into the new chunk's reveal wave.\n useIsomorphicLayoutEffect(() => {\n if (!enabled) {\n if (rafRef.current != null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n return;\n }\n\n const total = totalRef.current;\n\n // Content shrank or was replaced: there is nothing new to animate, so snap\n // the wave to the end and normalise the committed boundary back to the real\n // unit count so subsequent appends animate from there.\n if (snapRef.current) {\n snapRef.current = false;\n const end = total + SMOOTH_RAMP;\n positionRef.current = end;\n targetRef.current = end;\n velocityRef.current = 0;\n revealStateRef.current.committedUnits = total;\n setRevealVar(end);\n if (rafRef.current != null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n return;\n }\n\n // Reflect the current wave position on the freshly-committed tree before the\n // browser paints. After an active-block change the position was reset to 0,\n // so this keeps the new block hidden (rather than flashing fully visible for\n // one frame before the animation's first rAF tick lowers it).\n setRevealVar(positionRef.current);\n\n // Reveal one ramp past the last unit so the final character reaches full\n // opacity rather than stopping mid-fade.\n targetRef.current = total + SMOOTH_RAMP;\n\n const reduceMotion =\n typeof window !== \"undefined\" &&\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n const finishImmediately =\n reduceMotion ||\n duration <= 0 ||\n typeof requestAnimationFrame !== \"function\";\n\n if (finishImmediately) {\n positionRef.current = targetRef.current;\n setRevealVar(positionRef.current);\n if (revealStateRef.current.committedUnits !== total) {\n revealStateRef.current.committedUnits = total;\n forceCommit((n) => n + 1);\n }\n return;\n }\n\n velocityRef.current = (targetRef.current - positionRef.current) / duration;\n lastTsRef.current = performance.now();\n\n const tick = (ts: number) => {\n const dt = Math.max(0, ts - lastTsRef.current);\n lastTsRef.current = ts;\n let next = positionRef.current + velocityRef.current * dt;\n if (next >= targetRef.current) {\n next = targetRef.current;\n positionRef.current = next;\n setRevealVar(next);\n rafRef.current = null;\n // The wave has caught up: collapse the spans back to plain markup.\n if (revealStateRef.current.committedUnits !== totalRef.current) {\n revealStateRef.current.committedUnits = totalRef.current;\n forceCommit((n) => n + 1);\n }\n return;\n }\n positionRef.current = next;\n setRevealVar(next);\n rafRef.current = requestAnimationFrame(tick);\n };\n\n if (rafRef.current == null) {\n rafRef.current = requestAnimationFrame(tick);\n }\n\n return () => {\n if (rafRef.current != null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n };\n }, [activeSource, activeKey, enabled, duration]);\n\n const revealStyle: CSSProperties | undefined = enabled\n ? ({ \"--llm-ramp\": String(SMOOTH_RAMP) } as CSSProperties)\n : undefined;\n\n return { rootRef, fadePlugin, revealStyle };\n}\n","import { useMemo } from \"react\";\nimport type { CSSProperties, HTMLAttributes } from \"react\";\nimport { type Options } from \"react-markdown\";\nimport rehypeKatex from \"rehype-katex\";\nimport remarkGfm from \"remark-gfm\";\nimport remarkMath from \"remark-math\";\n\nimport {\n buildMarkdownComponents,\n cx,\n} from \"./buildMarkdownComponents\";\nimport { MarkdownBlock } from \"./MarkdownBlock\";\nimport type {\n CodeHighlighter,\n LLMMessageClassNames,\n LLMMessageComponents,\n} from \"./types\";\nimport { useMarkdownBlocks } from \"./useMarkdownBlocks\";\nimport { useSmoothReveal } from \"./useSmoothReveal\";\n\nexport interface LLMMessageProps\n extends Omit<HTMLAttributes<HTMLDivElement>, \"children\" | \"content\"> {\n /** The LLM message content as a markdown string. */\n children?: string;\n /** Alias for `children`. */\n content?: string;\n /** Class applied to the root element (merged with the built-in class). */\n className?: string;\n /** Per-element class overrides (merged with the built-in classes). */\n classNames?: LLMMessageClassNames;\n /** Per-element component overrides for full markup control. */\n components?: LLMMessageComponents;\n /**\n * Repair partially-streamed markdown/LaTeX so unterminated tokens (e.g.\n * `**bold`, `` `code ``, `[label](http`, `$E = mc^2`) do not render as raw\n * delimiter junk while the response is still streaming. Defaults to `true`.\n */\n completePartialTokens?: boolean;\n /**\n * Progressively render unterminated *block* math (`\\[…`, `$$…`) while it\n * streams, instead of hiding it until the closing delimiter arrives. This is\n * nicer to watch (a long block reveals row by row) but costs a synchronous\n * KaTeX parse on every chunk that contains an open block. Set to `false` to\n * hide unfinished blocks and skip that work. Only relevant while\n * `completePartialTokens` is enabled. Defaults to `true`.\n */\n showUnfinishedLatexBlocks?: boolean;\n /**\n * Fade newly-streamed text in character-by-character (and complex blocks as a\n * whole) instead of popping it in. Purely visual: text is always in the DOM\n * immediately, it just eases from transparent. Respects\n * `prefers-reduced-motion`. Defaults to `false`.\n */\n smoothReveal?: boolean;\n /**\n * The reveal window for a freshly-arrived chunk, in milliseconds. Each batch\n * of new characters is staggered so it finishes within roughly this window;\n * when a new chunk arrives mid-animation the leftover plus the new text reveal\n * over a fresh window. Only relevant while `smoothReveal` is enabled.\n * Defaults to `300`.\n */\n smoothRevealDuration?: number;\n /**\n * Split the message into top-level markdown blocks and render each as its own\n * memoized subtree, so a streaming update only re-parses/re-renders the last\n * (currently growing) block instead of the whole message. This keeps KaTeX\n * and code highlighting in earlier blocks from re-running on every chunk.\n *\n * Set to `false` to render the whole message as a single tree (needed for\n * documents that rely on constructs spanning blocks, e.g. footnote or link\n * reference definitions). Defaults to `true`.\n */\n blockMemoization?: boolean;\n /**\n * Optional syntax highlighter for fenced code blocks. When omitted, code\n * blocks render as plain text (so no highlighter bundle is pulled in). Pass\n * `ShikiHighlighter` / `ShikiWebHighlighter`, or build your own with\n * `createShikiHighlighter`.\n */\n highlighter?: CodeHighlighter;\n}\n\nconst remarkPlugins = [remarkGfm, remarkMath];\n\ntype RehypePlugins = NonNullable<Options[\"rehypePlugins\"]>;\n\nexport function LLMMessage({\n children,\n content,\n className,\n classNames,\n components,\n completePartialTokens: repairPartialTokens = true,\n showUnfinishedLatexBlocks = true,\n smoothReveal = false,\n smoothRevealDuration = 300,\n blockMemoization = true,\n highlighter,\n style,\n ...rest\n}: LLMMessageProps) {\n const source = content ?? children ?? \"\";\n\n const markdownComponents = useMemo(\n () => buildMarkdownComponents(classNames, components, highlighter),\n [classNames, components, highlighter],\n );\n\n const { renderedBlocks, activeIndex, activeSource } = useMarkdownBlocks({\n source,\n blockMemoization,\n repairPartialTokens,\n showUnfinishedLatexBlocks,\n smoothReveal,\n });\n\n const { rootRef, fadePlugin, revealStyle } = useSmoothReveal({\n activeSource,\n activeKey: activeIndex,\n enabled: smoothReveal,\n duration: smoothRevealDuration,\n });\n\n // Stable rehype-plugin arrays, selected per block so KaTeX runs only on blocks\n // that actually contain math (`$`). The fade plugin is attached to the active\n // block only. All four references are stable across renders, so a block whose\n // content and math-ness are unchanged keeps the same array reference and stays\n // memoized.\n const pluginSets = useMemo(() => {\n const math: RehypePlugins = [rehypeKatex];\n const none: RehypePlugins = [];\n return {\n math,\n none,\n activeMath: fadePlugin ? [rehypeKatex, fadePlugin] : math,\n activeNone: fadePlugin ? [fadePlugin] : none,\n };\n }, [fadePlugin]);\n\n const rootStyle: CSSProperties | undefined = revealStyle\n ? { ...style, ...revealStyle }\n : style;\n\n return (\n <div\n ref={rootRef}\n className={cx(\"llm-message\", classNames?.root, className)}\n style={rootStyle}\n {...rest}\n >\n {renderedBlocks.map((block, index) => {\n const isActive = index === activeIndex;\n // After preprocessing all math uses `$`; a block without one cannot\n // contain math, so KaTeX can be skipped for it entirely.\n const hasMath = block.includes(\"$\");\n const rehypePlugins = isActive\n ? hasMath\n ? pluginSets.activeMath\n : pluginSets.activeNone\n : hasMath\n ? pluginSets.math\n : pluginSets.none;\n return (\n <MarkdownBlock\n // Index keys keep stable blocks mounted across chunks; blocks are\n // append-only, so content changes flow through props and the memo\n // comparison rather than remounting.\n key={index}\n content={block}\n components={markdownComponents}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n />\n );\n })}\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { CodeHighlighter, CodeToHtml } from \"./types\";\n\ninterface CreateShikiHighlighterOptions {\n /** Theme pair forwarded to `codeToHtml`. Defaults to GitHub light/dark. */\n themes?: { light: string; dark: string };\n}\n\nconst DEFAULT_THEMES = { light: \"github-light\", dark: \"github-dark\" };\n\n/**\n * Builds a {@link CodeHighlighter} from any `codeToHtml`-compatible function.\n *\n * This factory imports no Shiki bundle itself, so importing it never drags\n * highlighting code into your app. You decide which bundle to pay for by\n * passing the `codeToHtml` from `shiki` (full), `shiki/bundle/web` (web), or a\n * minimal `createHighlighterCore` instance.\n *\n * @example\n * import { codeToHtml } from \"shiki/bundle/web\";\n * const Highlighter = createShikiHighlighter(codeToHtml);\n * <LLMMessage highlighter={Highlighter}>{content}</LLMMessage>\n */\nexport function createShikiHighlighter(\n codeToHtml: CodeToHtml,\n options?: CreateShikiHighlighterOptions,\n): CodeHighlighter {\n const themes = options?.themes ?? DEFAULT_THEMES;\n\n return function ShikiHighlighter({ code, language, className }) {\n const [html, setHtml] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n Promise.resolve(codeToHtml(code, { lang: language, themes }))\n .then((result) => {\n if (!cancelled) setHtml(result);\n })\n .catch(() => {\n // Fallback: if the language is unsupported, just show plain code.\n if (!cancelled) setHtml(null);\n });\n return () => {\n cancelled = true;\n };\n // `codeToHtml` and `themes` are fixed for the lifetime of a highlighter\n // instance (captured from the factory closure), so they are intentionally\n // not listed: they never change between renders of this component.\n }, [code, language]);\n\n if (html) {\n return (\n <div\n className={className ?? \"llm-shiki\"}\n // The HTML is generated by Shiki, which is safe.\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n }\n\n return <code className=\"llm-code-plain\">{code}</code>;\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { HTMLAttributes } from 'react';
3
- import { L as LLMMessageClassNames, a as LLMMessageComponents, C as CodeHighlighter, b as CodeToHtml } from './types-Dz7GupgB.cjs';
4
- export { A as AnchorProps, c as CheckboxProps, d as CodeBlockProps, e as CodeHighlighterProps, f as CopyButtonProps, E as ElementProps, I as ImageProps, g as InlineCodeProps } from './types-Dz7GupgB.cjs';
3
+ import { L as LLMMessageClassNames, a as LLMMessageComponents, C as CodeHighlighter, b as CodeToHtml } from './types-DETvxTAd.cjs';
4
+ export { A as AnchorProps, c as CheckboxProps, d as CodeBlockProps, e as CodeHighlighterProps, f as CopyButtonProps, E as ElementProps, I as ImageProps, g as InlineCodeProps } from './types-DETvxTAd.cjs';
5
5
 
6
6
  interface LLMMessageProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "content"> {
7
7
  /** The LLM message content as a markdown string. */
@@ -29,6 +29,32 @@ interface LLMMessageProps extends Omit<HTMLAttributes<HTMLDivElement>, "children
29
29
  * `completePartialTokens` is enabled. Defaults to `true`.
30
30
  */
31
31
  showUnfinishedLatexBlocks?: boolean;
32
+ /**
33
+ * Fade newly-streamed text in character-by-character (and complex blocks as a
34
+ * whole) instead of popping it in. Purely visual: text is always in the DOM
35
+ * immediately, it just eases from transparent. Respects
36
+ * `prefers-reduced-motion`. Defaults to `false`.
37
+ */
38
+ smoothReveal?: boolean;
39
+ /**
40
+ * The reveal window for a freshly-arrived chunk, in milliseconds. Each batch
41
+ * of new characters is staggered so it finishes within roughly this window;
42
+ * when a new chunk arrives mid-animation the leftover plus the new text reveal
43
+ * over a fresh window. Only relevant while `smoothReveal` is enabled.
44
+ * Defaults to `300`.
45
+ */
46
+ smoothRevealDuration?: number;
47
+ /**
48
+ * Split the message into top-level markdown blocks and render each as its own
49
+ * memoized subtree, so a streaming update only re-parses/re-renders the last
50
+ * (currently growing) block instead of the whole message. This keeps KaTeX
51
+ * and code highlighting in earlier blocks from re-running on every chunk.
52
+ *
53
+ * Set to `false` to render the whole message as a single tree (needed for
54
+ * documents that rely on constructs spanning blocks, e.g. footnote or link
55
+ * reference definitions). Defaults to `true`.
56
+ */
57
+ blockMemoization?: boolean;
32
58
  /**
33
59
  * Optional syntax highlighter for fenced code blocks. When omitted, code
34
60
  * blocks render as plain text (so no highlighter bundle is pulled in). Pass
@@ -37,7 +63,7 @@ interface LLMMessageProps extends Omit<HTMLAttributes<HTMLDivElement>, "children
37
63
  */
38
64
  highlighter?: CodeHighlighter;
39
65
  }
40
- declare function LLMMessage({ children, content, className, classNames, components, completePartialTokens: repairPartialTokens, showUnfinishedLatexBlocks, highlighter, ...rest }: LLMMessageProps): react.JSX.Element;
66
+ declare function LLMMessage({ children, content, className, classNames, components, completePartialTokens: repairPartialTokens, showUnfinishedLatexBlocks, smoothReveal, smoothRevealDuration, blockMemoization, highlighter, style, ...rest }: LLMMessageProps): react.JSX.Element;
41
67
 
42
68
  /**
43
69
  * Preprocesses LaTeX content by replacing delimiters and escaping certain characters.