@carbon/ai-chat-components 1.10.0-rc.0 → 1.10.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.
Files changed (56) hide show
  1. package/custom-elements.json +3186 -3074
  2. package/es/components/markdown/index.d.ts +1 -0
  3. package/es/components/markdown/src/markdown-renderer.js +27 -1
  4. package/es/components/markdown/src/markdown-renderer.js.map +1 -1
  5. package/es/components/markdown/src/markdown-token-tree.js +6 -1
  6. package/es/components/markdown/src/markdown-token-tree.js.map +1 -1
  7. package/es/components/markdown/src/markdown.d.ts +5 -2
  8. package/es/components/markdown/src/markdown.js +66 -23
  9. package/es/components/markdown/src/markdown.js.map +1 -1
  10. package/es/components/markdown/src/utils/html-helpers.js +9 -2
  11. package/es/components/markdown/src/utils/html-helpers.js.map +1 -1
  12. package/es/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
  13. package/es/components/markdown/src/utils/plugin-fallback.js +14 -5
  14. package/es/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  15. package/es/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
  16. package/es/components/markdown/src/utils/plugin-host-container.js +165 -0
  17. package/es/components/markdown/src/utils/plugin-host-container.js.map +1 -0
  18. package/es/components/markdown/src/utils/table-helpers.d.ts +10 -0
  19. package/es/components/markdown/src/utils/table-helpers.js.map +1 -1
  20. package/es/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
  21. package/es/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  22. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
  23. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  24. package/es/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
  25. package/es/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  26. package/es/components/prompt-line/src/tiptap/types.d.ts +2 -1
  27. package/es/react/markdown.js +2 -44
  28. package/es/react/markdown.js.map +1 -1
  29. package/es-custom/components/markdown/index.d.ts +1 -0
  30. package/es-custom/components/markdown/src/markdown-renderer.js +27 -1
  31. package/es-custom/components/markdown/src/markdown-renderer.js.map +1 -1
  32. package/es-custom/components/markdown/src/markdown-token-tree.js +6 -1
  33. package/es-custom/components/markdown/src/markdown-token-tree.js.map +1 -1
  34. package/es-custom/components/markdown/src/markdown.d.ts +5 -2
  35. package/es-custom/components/markdown/src/markdown.js +66 -23
  36. package/es-custom/components/markdown/src/markdown.js.map +1 -1
  37. package/es-custom/components/markdown/src/utils/html-helpers.js +9 -2
  38. package/es-custom/components/markdown/src/utils/html-helpers.js.map +1 -1
  39. package/es-custom/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
  40. package/es-custom/components/markdown/src/utils/plugin-fallback.js +14 -5
  41. package/es-custom/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  42. package/es-custom/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
  43. package/es-custom/components/markdown/src/utils/plugin-host-container.js +165 -0
  44. package/es-custom/components/markdown/src/utils/plugin-host-container.js.map +1 -0
  45. package/es-custom/components/markdown/src/utils/table-helpers.d.ts +10 -0
  46. package/es-custom/components/markdown/src/utils/table-helpers.js.map +1 -1
  47. package/es-custom/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
  48. package/es-custom/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  49. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
  50. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  51. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
  52. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  53. package/es-custom/components/prompt-line/src/tiptap/types.d.ts +2 -1
  54. package/es-custom/react/markdown.js +2 -44
  55. package/es-custom/react/markdown.js.map +1 -1
  56. package/package.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import './src/markdown.js';
2
2
  export { default, CDSAIChatMarkdown } from './src/markdown.js';
3
3
  export type { MarkdownCustomRenderers, MarkdownRendererChecklist, MarkdownRendererChecklistItemArgs, MarkdownRendererChecklistToggleArgs, MarkdownRendererCodeBlockArgs, MarkdownRendererCodeBlockData, MarkdownRendererImageArgs, MarkdownRendererImageResult, MarkdownRendererLinkArgs, MarkdownRendererLinkResult, MarkdownRendererTableArgs, MarkdownRendererTableData, } from './src/markdown-renderer-types.js';
4
+ export type { MarkdownCustomRendererMountDetail, MarkdownPluginFallbackMountDetail, MarkdownPluginHostMountDetail, MarkdownPluginHostMountDetailInput, } from './src/utils/plugin-host-container.js';
4
5
  export type { MarkdownItPlugin, TokenTree } from './src/markdown-token-tree.js';
5
6
  export { markdownToMarkdownItTokens } from './src/markdown-token-tree.js';
@@ -131,10 +131,28 @@ function renderChildTokenTrees(children, options, childContext) {
131
131
  function renderMarkdownTree(node, options) {
132
132
  const batch = [];
133
133
  let pluginSlotIndex = 0;
134
+ // Memoized per node, not just counted. `renderFallback` runs inside a
135
+ // lit-html `repeat()` callback, so it evaluates when lit-html commits the
136
+ // template — and one render result gets committed again on any later Lit
137
+ // update that leaves `renderedContent` alone. A bare counter would hand the
138
+ // same token a fresh index on each commit, minting a second slot the very
139
+ // next reconcile retires. First evaluation still assigns 0, 1, 2 in walk
140
+ // order, so a single-commit render is unchanged.
141
+ const pluginSlotIndexes = new WeakMap();
134
142
  const template = renderTokenTree(node, {
135
143
  ...options,
136
144
  recordCustomRender: (descriptor) => batch.push(descriptor),
137
- pluginSlotCounter: { next: () => pluginSlotIndex++ },
145
+ pluginSlotCounter: {
146
+ next: (forNode) => {
147
+ const existing = pluginSlotIndexes.get(forNode);
148
+ if (existing !== undefined) {
149
+ return existing;
150
+ }
151
+ const index = pluginSlotIndex++;
152
+ pluginSlotIndexes.set(forNode, index);
153
+ return index;
154
+ },
155
+ },
138
156
  });
139
157
  return { template, batch };
140
158
  }
@@ -175,6 +193,14 @@ function renderTokenTree(node, options) {
175
193
  if (token.type === 'text') {
176
194
  return html `${token.content}`;
177
195
  }
196
+ // Hard and soft line breaks. Handled before the tag-based dispatch because
197
+ // hardbreak has tag="br", which `renderWithStaticTag` does not know and would
198
+ // route through the plugin-fallback slot machinery.
199
+ if (token.type === 'hardbreak' || token.type === 'softbreak') {
200
+ return token.type === 'softbreak' && options.md?.options.breaks === false
201
+ ? html `${'\n'}`
202
+ : html `<br />`;
203
+ }
178
204
  // Handle inline code spans
179
205
  if (token.type === 'code_inline') {
180
206
  if (shouldDelegateToPluginRule(token, options.md) && options.md) {
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-renderer.js","sources":["../../../../src/components/markdown/src/markdown-renderer.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * Walks a `TokenTree` and emits a Lit `TemplateResult` plus a batch of {@link MarkdownRendererSlotDescriptor} records the markdown element consumes during its `updated()` reconcile. External callers should go through {@link renderMarkdownTree} so the batch isn't accidentally dropped.\n *\n * ### Dispatch precedence\n *\n * Per token, in order:\n *\n * 1. **Consumer override** — `options.customRenderers`. For `table`/`codeBlock` the renderer emits a named `<slot>` placeholder and records a descriptor; the markdown element's `updated()` invokes the consumer callback later. For `link`/`image` the callback runs synchronously here as an attribute transform (no slot, no descriptor); `checklist` adjusts the rendered `cds-checkbox` (its toggles are delivered by a listener on the markdown element).\n * 2. **Plugin-overridden rule** — `shouldDelegateToPluginRule(token, md)` is true when a user-supplied markdown-it plugin overrode the renderer rule for one of the curated leaf tokens in `PLUGIN_DELEGABLE_TOKEN_TYPES` (`fence`, `image`, `code_inline`, `html_block`). The token routes through `renderFallback` and surfaces as a `pluginFallback` descriptor.\n * 3. **Native Lit dispatch** — the hand-written `renderWithStaticTag` switch. Kept flat (rather than a tag-to-renderer map) so the per-tag exceptions — task-list passthrough, Carbon `cds-unordered-list` / `cds-ordered-list` wrappers, automatic `target=\"_blank\"` on `<a>`, image plugin delegation — stay easy to grep.\n * 4. **Unknown plugin-introduced token** — anything not natively handled falls through to `renderFallback`, so plugins that register `md.renderer.rules[type]` (footnote, deflist, custom containers, emoji) just work.\n *\n * ### Slot contract\n *\n * {@link MarkdownRendererSlotDescriptor} (defined in `./markdown-renderer-types.ts`) is the bridge between this module and `./markdown.ts`. This module appends descriptors via `recordCustomRender`; the markdown element's `reconcileCustomRendererHosts` consumes them, invokes consumer callbacks (or adopts plugin-fallback HTML) and attaches the result as a light-DOM `<div slot=\"…\">` host (or `<span>` for inline plugin output).\n */\n\nimport DOMPurify from 'dompurify';\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js';\nimport { Token } from 'markdown-it';\nimport '@carbon/web-components/es/components/list/index.js';\nimport '@carbon/web-components/es/components/checkbox/index.js';\nimport '../../code-snippet/index.js';\nimport '../../card/index.js';\nimport '../../table/index.js';\nimport { defaultLineCountText } from '../../code-snippet/src/formatters.js';\n\nimport { renderTable } from './utils/table-helpers.js';\nimport {\n combineConsecutiveHtmlInline,\n combineSplitHtmlBlocks,\n} from './utils/html-helpers.js';\nimport {\n htmlContainer,\n sanitizeHtmlContent,\n spread,\n} from './utils/lit-directives.js';\nimport {\n isNativelyHandled,\n renderFallback,\n shouldDelegateToPluginRule,\n} from './utils/plugin-fallback.js';\nimport {\n MARKDOWN_SLOT_PREFIX,\n withInstanceNamespace,\n} from './utils/slot-names.js';\nimport { type TokenTree } from './markdown-token-tree.js';\nimport type {\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n// Re-export types so existing imports of these from this module keep working.\nexport type {\n MarkdownCustomRenderers,\n MarkdownRendererChecklist,\n MarkdownRendererChecklistItemArgs,\n MarkdownRendererChecklistToggleArgs,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererCodeBlockData,\n MarkdownRendererImageArgs,\n MarkdownRendererImageResult,\n MarkdownRendererLinkArgs,\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n MarkdownRendererTableArgs,\n MarkdownRendererTableData,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n/**\n * Slot name for an overridable token — unique across the page, stable across\n * streaming ticks. Three parts:\n *\n * - `startLine` (not the full `token.map`) so the name doesn't change when the\n * token's `endLine` advances during streaming;\n * - `currentIndex` from the parent context, disambiguating siblings that share\n * a start line (rare but possible);\n * - the owning element's namespace, because slot hosts from every markdown\n * element on the page are hoisted into one shared light-DOM container and\n * projected back by name (see `./utils/slot-names.js`).\n */\nfunction slotNameFor(\n kind: 'table' | 'codeBlock',\n token: Token,\n options: RenderTokenTreeOptions\n): string {\n const startLine = token.map?.[0] ?? 0;\n const index = options.context?.currentIndex ?? 0;\n return withInstanceNamespace(\n `${MARKDOWN_SLOT_PREFIX}-${kind}-${startLine}-${index}`,\n options\n );\n}\n\n/**\n * Drops attributes DOMPurify considers unsafe (event handlers, `javascript:`\n * URLs, etc.) from a plain attr object. Used both for the parsed token attrs\n * and for attributes a consumer `link`/`image` renderer merges in — the latter\n * bypass the token-attr pass, so they must be re-checked here.\n */\nfunction sanitizeAttrs(attrs: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(attrs).filter(([key, value]) => {\n // Use DOMPurify to check if attribute is safe\n const fragment = DOMPurify.sanitize(`<a ${key}=\"${value}\">`, {\n RETURN_DOM: true,\n });\n const element = fragment.firstChild as Element | null;\n return element?.getAttribute(key) !== null;\n })\n );\n}\n\n/**\n * Concatenates the plain-text content of a node's descendants. A lossy\n * convenience for consumer `link`/`checklist` callbacks that want the visible\n * text; the rich children still render through the normal dispatch.\n */\nfunction extractText(node: TokenTree): string {\n const { token, children } = node;\n if (children && children.length > 0) {\n return children.map(extractText).join('');\n }\n return token.content ?? '';\n}\n\nfunction renderChildTokenTrees(\n children: TokenTree[],\n options: RenderTokenTreeOptions,\n childContext?: RenderTokenTreeOptions['context']\n): TemplateResult {\n const normalizedChildren = combineConsecutiveHtmlInline(\n combineSplitHtmlBlocks(children)\n );\n\n // Multiple or complex children: use repeat for stable keying\n return html`${repeat(\n normalizedChildren,\n (child, index) => {\n // Key by start line + type + tag rather than array index so blocks keep\n // a stable identity when earlier siblings transiently merge/split during\n // streaming re-parses (which would otherwise re-key and remount later\n // blocks — e.g. remounting a code snippet and reloading its editor). We\n // use `token.map?.[0]` (start line, like `slotNameFor`) rather than the\n // node's `key`/`generateKey`, whose embedded end line advances every tick.\n const startLine = child.token.map?.[0] ?? index;\n const stableKey = `${startLine}:${child.token.type}:${child.token.tag}`;\n\n if (child.token.type?.includes('table')) {\n return `table-${stableKey}`;\n }\n\n return `stable-${stableKey}`;\n },\n (child, index) => {\n const result = renderTokenTree(child, {\n ...options,\n context: {\n ...childContext,\n parentChildren: normalizedChildren,\n currentIndex: index,\n },\n });\n // Ensure we never return undefined, which Lit would render as the string \"undefined\"\n return result ?? html``;\n }\n )}`;\n}\n\n/**\n * Top-level entry: renders a markdown token tree to a Lit `TemplateResult`\n * and returns the batch of custom-renderer slot descriptors collected along\n * the way. Callers receive both pieces in one call so the batch can't be\n * accidentally dropped.\n */\nexport function renderMarkdownTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): {\n template: TemplateResult;\n batch: MarkdownRendererSlotDescriptor[];\n} {\n const batch: MarkdownRendererSlotDescriptor[] = [];\n let pluginSlotIndex = 0;\n const template = renderTokenTree(node, {\n ...options,\n recordCustomRender: (descriptor) => batch.push(descriptor),\n pluginSlotCounter: { next: () => pluginSlotIndex++ },\n });\n return { template, batch };\n}\n\n/**\n * Converts TokenTree to Lit TemplateResult.\n *\n * Recursive renderer; external callers should use {@link renderMarkdownTree}\n * which collects the slot-descriptor batch.\n */\nexport function renderTokenTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): TemplateResult {\n const { token, children } = node;\n const { context, sanitize } = options;\n\n // Handle raw HTML blocks and inline HTML\n if (token.type === 'html_block' || token.type === 'html_inline') {\n // Plugin-overridden html_block rules (rare but supported) — route through\n // the plugin's renderer before our default unsafeHTML pass-through.\n if (\n token.type === 'html_block' &&\n shouldDelegateToPluginRule(token, options.md) &&\n options.md\n ) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n let content = token.content || '';\n\n // Apply HTML sanitization if requested\n if (sanitize && content) {\n content = sanitizeHtmlContent(content);\n }\n\n return html`${unsafeHTML(content)}`;\n }\n\n // Handle split HTML blocks that wrap markdown siblings (e.g. <details>…</details>).\n if (token.type === 'html_container') {\n const openingHtml = token.content ?? '';\n const innerContent = renderChildTokenTrees(children, options, context);\n\n return html`<div\n class=\"cds-aichat-markdown-html-container\"\n ${htmlContainer(openingHtml, innerContent, sanitize)}></div>`;\n }\n\n // Handle plain text content\n if (token.type === 'text') {\n return html`${token.content}`;\n }\n\n // Handle inline code spans\n if (token.type === 'code_inline') {\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n return html`<code>${token.content}</code>`;\n }\n\n // Handle fenced code blocks\n if (token.type === 'fence') {\n const language = token.info?.trim() ?? '';\n const {\n codeSnippetHighlight = true,\n codeSnippetShowLessText,\n codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText = defaultLineCountText,\n codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable,\n } = options;\n\n const defaultTemplate = html`<cds-aichat-card is-flush>\n <div slot=\"body\">\n <cds-aichat-code-snippet\n data-rounded\n .language=${language}\n .highlight=${codeSnippetHighlight}\n .detectLanguage=${true}\n .showLessText=${codeSnippetShowLessText}\n .showMoreText=${codeSnippetShowMoreText}\n .copyButtonTooltipContent=${codeSnippetCopyButtonTooltipContent}\n .getLineCountText=${codeSnippetGetLineCountText}\n .ariaLabelReadOnly=${codeSnippetAriaLabelReadOnly}\n .ariaLabelEditable=${codeSnippetAriaLabelEditable}\n .code=${token.content}></cds-aichat-code-snippet>\n </div>\n </cds-aichat-card>`;\n\n if (options.customRenderers?.codeBlock) {\n const slotName = slotNameFor('codeBlock', token as Token, options);\n options.recordCustomRender?.({\n slotName,\n kind: 'codeBlock',\n token: token as Token,\n data: {\n language,\n code: token.content ?? '',\n isStreaming: !!options.streaming,\n },\n });\n return html`<slot name=${slotName}>${defaultTemplate}</slot>`;\n }\n\n // Honor user-plugin `fence` overrides (markdown-it-mermaid, syntax\n // highlighters, etc.). customRenderer slot above wins when set.\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n return defaultTemplate;\n }\n\n // Handle structural elements (paragraphs, headings, lists, etc.)\n const tag = token.tag;\n\n // Convert markdown-it attributes (array of [key, value]) into an object.\n const rawAttrs = (token.attrs || []).reduce(\n (acc, [key, value]) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>\n );\n\n // Apply attribute sanitization if requested\n let attrs = rawAttrs;\n const isCustomElement = !!token.tag && token.tag.includes('-');\n if (sanitize && !isCustomElement) {\n attrs = sanitizeAttrs(rawAttrs);\n }\n\n // Set up context for child rendering\n let childContext = context;\n if (tag === 'thead') {\n childContext = { ...context, isInThead: true };\n }\n\n // Render child content\n let content: TemplateResult;\n\n if (children.length === 1 && children[0].token.type === 'text') {\n // Optimization: single text child doesn't need repeat wrapper\n content = html`${children[0].token.content}`;\n } else {\n content = renderChildTokenTrees(children, options, childContext);\n }\n\n // Unknown plugin-introduced tokens (no tag we recognize) — defer to\n // markdown-it's renderer so plugins that register md.renderer.rules[type]\n // (footnote, emoji, deflist, container, etc.) just work.\n if (!tag && options.md && !isNativelyHandled(token)) {\n return renderFallback(token as Token, node, options.md, sanitize, options);\n }\n\n // Handle tokens without HTML tags (just return content)\n if (!tag) {\n return content;\n }\n\n // Render the final HTML element with appropriate tag\n return renderWithStaticTag(\n tag,\n token as Token,\n content,\n attrs,\n options,\n childContext,\n node\n );\n}\n\n/**\n * Renders HTML elements with static tag names.\n */\nfunction renderWithStaticTag(\n tag: string,\n token: Token,\n content: TemplateResult,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n _context?: { isInThead?: boolean },\n node?: TokenTree\n): TemplateResult {\n // Handle root token specially\n if (token.type === 'root') {\n return content;\n }\n\n const hasTaskListItems = (listNode?: TokenTree) =>\n !!listNode?.children?.some((child) => {\n if (child.token.type !== 'list_item_open') {\n return false;\n }\n\n const classAttr = child.token.attrs?.find(([key]) => key === 'class');\n return classAttr?.[1]?.split(/\\s+/).includes('task-list-item');\n });\n\n switch (tag) {\n // Basic block elements\n case 'p':\n return html`<p ${spread(attrs)}>${content}</p>`;\n\n case 'blockquote':\n return html`<blockquote ${spread(attrs)}>${content}</blockquote>`;\n\n case 'pre':\n return html`<pre ${spread(attrs)}>${content}</pre>`;\n\n case 'hr':\n return html`<hr ${spread(attrs)} />`;\n\n // Headings\n case 'h1':\n return html`<h1 ${spread(attrs)}>${content}</h1>`;\n case 'h2':\n return html`<h2 ${spread(attrs)}>${content}</h2>`;\n case 'h3':\n return html`<h3 ${spread(attrs)}>${content}</h3>`;\n case 'h4':\n return html`<h4 ${spread(attrs)}>${content}</h4>`;\n case 'h5':\n return html`<h5 ${spread(attrs)}>${content}</h5>`;\n case 'h6':\n return html`<h6 ${spread(attrs)}>${content}</h6>`;\n\n // Lists with Carbon components\n case 'ul': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ul ${spread(attrs)}>\n ${content}\n </ul>`;\n }\n return html`<p>\n <cds-unordered-list ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-unordered-list>\n </p>`;\n }\n\n case 'ol': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ol ${spread(attrs)}>\n ${content}\n </ol>`;\n }\n return html`<p>\n <cds-ordered-list native ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-ordered-list>\n </p>`;\n }\n\n case 'li': {\n const classList = attrs.class?.split(/\\s+/) ?? [];\n if (classList.includes('task-list-item')) {\n return html`<li ${spread(attrs)}>${content}</li>`;\n }\n return html`<cds-list-item ${spread(attrs)}>${content}</cds-list-item>`;\n }\n\n case 'cds-checkbox': {\n const { checked, disabled, ...otherAttrs } = attrs;\n let isChecked = checked === 'true';\n\n // A configured `checklist` renderer can supply the checked state\n // (so a persisted toggle survives streaming re-renders) and makes the\n // boxes interactive.\n const checklist = options.customRenderers?.checklist;\n if (checklist?.getChecked && node) {\n const override = checklist.getChecked({\n id: otherAttrs['data-cds-aichat-checklist-id'] ?? '',\n label: extractText(node),\n checked: isChecked,\n token,\n });\n if (typeof override === 'boolean') {\n isChecked = override;\n }\n }\n\n const isDisabled = checklist\n ? false\n : disabled === undefined\n ? false\n : disabled === '' || disabled === 'true';\n\n return html`<cds-checkbox\n ?checked=${isChecked}\n ?disabled=${isDisabled}\n ${spread(otherAttrs)}\n >${content}</cds-checkbox\n >`;\n }\n\n // Inline formatting\n case 'strong':\n return html`<strong ${spread(attrs)}>${content}</strong>`;\n case 'em':\n return html`<em ${spread(attrs)}>${content}</em>`;\n case 'code':\n return html`<code ${spread(attrs)}>${content}</code>`;\n case 'del':\n return html`<del ${spread(attrs)}>${content}</del>`;\n case 'sub':\n return html`<sub ${spread(attrs)}>${content}</sub>`;\n case 'sup':\n return html`<sup ${spread(attrs)}>${content}</sup>`;\n case 'span':\n return html`<span ${spread(attrs)}>${content}</span>`;\n case 'i':\n return html`<i ${spread(attrs)}>${content}</i>`;\n case 'b':\n return html`<b ${spread(attrs)}>${content}</b>`;\n case 'small':\n return html`<small ${spread(attrs)}>${content}</small>`;\n case 'mark':\n return html`<mark ${spread(attrs)}>${content}</mark>`;\n case 'ins':\n return html`<ins ${spread(attrs)}>${content}</ins>`;\n case 's':\n return html`<s ${spread(attrs)}>${content}</s>`;\n case 'kbd':\n return html`<kbd ${spread(attrs)}>${content}</kbd>`;\n case 'var':\n return html`<var ${spread(attrs)}>${content}</var>`;\n case 'samp':\n return html`<samp ${spread(attrs)}>${content}</samp>`;\n case 'cite':\n return html`<cite ${spread(attrs)}>${content}</cite>`;\n case 'abbr':\n return html`<abbr ${spread(attrs)}>${content}</abbr>`;\n case 'dfn':\n return html`<dfn ${spread(attrs)}>${content}</dfn>`;\n case 'time':\n return html`<time ${spread(attrs)}>${content}</time>`;\n case 'q':\n return html`<q ${spread(attrs)}>${content}</q>`;\n\n // Links: optional consumer attribute transform, then automatic\n // target=\"_blank\" safety default.\n case 'a': {\n let linkAttrs: Record<string, string> = {\n ...attrs,\n target: attrs.target ?? '_blank',\n };\n\n let onClickHandler: MarkdownRendererLinkResult['onClick'];\n\n const linkRenderer = options.customRenderers?.link;\n\n if (linkRenderer && node) {\n const result = linkRenderer({\n href: attrs.href ?? '',\n title: attrs.title,\n text: extractText(node),\n attributes: { ...attrs },\n token,\n });\n\n if (result) {\n linkAttrs = {\n ...linkAttrs,\n ...(result.attributes ?? {}),\n };\n\n if (result.href !== undefined) {\n linkAttrs.href = result.href;\n }\n if (result.target !== undefined) {\n linkAttrs.target = result.target;\n }\n if (result.rel !== undefined) {\n linkAttrs.rel = result.rel;\n }\n\n // Consumer-supplied attributes are merged after the initial token\n // sanitization pass, so sanitize the final attribute set again.\n if (options.sanitize) {\n linkAttrs = sanitizeAttrs(linkAttrs);\n }\n\n onClickHandler = result.onClick;\n }\n }\n\n return html`<a ${spread(linkAttrs)} @click=${onClickHandler}\n >${content}</a\n >`;\n }\n\n // Self-closing image. A consumer `image` transform wins first (mirroring\n // how `codeBlock` wins over plugin `fence` rules); otherwise\n // plugin-introduced wrappers (e.g. image-figures) route through\n // `shouldDelegateToPluginRule` before falling back to a plain `<img>`.\n case 'img': {\n const imageRenderer = options.customRenderers?.image;\n if (imageRenderer && node) {\n let imgAttrs: Record<string, string> = attrs;\n const result = imageRenderer({\n src: attrs.src ?? '',\n alt: attrs.alt,\n title: attrs.title,\n attributes: { ...attrs },\n token,\n });\n if (result) {\n imgAttrs = { ...attrs, ...(result.attributes ?? {}) };\n if (result.src !== undefined) {\n imgAttrs.src = result.src;\n }\n if (options.sanitize) {\n imgAttrs = sanitizeAttrs(imgAttrs);\n }\n }\n return html`<img ${spread(imgAttrs)} />`;\n }\n if (node && options.md && shouldDelegateToPluginRule(token, options.md)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<img ${spread(attrs)} />`;\n }\n\n // Tables with Carbon component and streaming support\n case 'table': {\n if (!node) {\n return html`<div>Error: Missing table data</div>`;\n }\n const slotName = options.customRenderers?.table\n ? slotNameFor('table', token, options)\n : undefined;\n return renderTable(\n token,\n node,\n attrs,\n options,\n renderTokenTree,\n slotName\n );\n }\n\n // Fallback for unknown tags. If we have the markdown-it instance available,\n // defer to its renderer for plugin-introduced container tags (footnote_block,\n // dl/dt/dd from deflist, custom containers, etc.). Otherwise fall back to\n // a generic <div>.\n default:\n if (options.md && node && !isNativelyHandled(token)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<div ${spread(attrs)}>${content}</div>`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;AAeG;AA0DH;;;;;;;;;;;AAWG;AACH,SAAS,WAAW,CAClB,IAA2B,EAC3B,KAAY,EACZ,OAA+B,EAAA;IAE/B,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC;IACrC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,YAAY,IAAI,CAAC;AAChD,IAAA,OAAO,qBAAqB,CAC1B,CAAA,EAAG,oBAAoB,IAAI,IAAI,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA,EAAI,KAAK,CAAA,CAAE,EACvD,OAAO,CACR;AACH;AAEA;;;;;AAKG;AACH,SAAS,aAAa,CAAC,KAA6B,EAAA;IAClD,OAAO,MAA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gBAAA,OAAO,cAAc,CACnB,KAAK,EACL,IAAI,EACJ,OAAO,CAAC,EAAE,EACV,OAAO,CAAC,QAAQ,EAChB,OAAO,CACR;YACH;YACA,OAAO,IAAI,CAAA,CAAA,KAAA,EAAQ,MAAM,CAAC,KAAK,CAAC,CAAA,CAAA,EAAI,OAAO,CAAA,MAAA,CAAQ;;AAEzD;;"}
1
+ {"version":3,"file":"markdown-renderer.js","sources":["../../../../src/components/markdown/src/markdown-renderer.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * Walks a `TokenTree` and emits a Lit `TemplateResult` plus a batch of {@link MarkdownRendererSlotDescriptor} records the markdown element consumes during its `updated()` reconcile. External callers should go through {@link renderMarkdownTree} so the batch isn't accidentally dropped.\n *\n * ### Dispatch precedence\n *\n * Per token, in order:\n *\n * 1. **Consumer override** — `options.customRenderers`. For `table`/`codeBlock` the renderer emits a named `<slot>` placeholder and records a descriptor; the markdown element's `updated()` invokes the consumer callback later. For `link`/`image` the callback runs synchronously here as an attribute transform (no slot, no descriptor); `checklist` adjusts the rendered `cds-checkbox` (its toggles are delivered by a listener on the markdown element).\n * 2. **Plugin-overridden rule** — `shouldDelegateToPluginRule(token, md)` is true when a user-supplied markdown-it plugin overrode the renderer rule for one of the curated leaf tokens in `PLUGIN_DELEGABLE_TOKEN_TYPES` (`fence`, `image`, `code_inline`, `html_block`). The token routes through `renderFallback` and surfaces as a `pluginFallback` descriptor.\n * 3. **Native Lit dispatch** — the hand-written `renderWithStaticTag` switch. Kept flat (rather than a tag-to-renderer map) so the per-tag exceptions — task-list passthrough, Carbon `cds-unordered-list` / `cds-ordered-list` wrappers, automatic `target=\"_blank\"` on `<a>`, image plugin delegation — stay easy to grep.\n * 4. **Unknown plugin-introduced token** — anything not natively handled falls through to `renderFallback`, so plugins that register `md.renderer.rules[type]` (footnote, deflist, custom containers, emoji) just work.\n *\n * ### Slot contract\n *\n * {@link MarkdownRendererSlotDescriptor} (defined in `./markdown-renderer-types.ts`) is the bridge between this module and `./markdown.ts`. This module appends descriptors via `recordCustomRender`; the markdown element's `reconcileCustomRendererHosts` consumes them, invokes consumer callbacks (or adopts plugin-fallback HTML) and attaches the result as a light-DOM `<div slot=\"…\">` host (or `<span>` for inline plugin output).\n */\n\nimport DOMPurify from 'dompurify';\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js';\nimport { Token } from 'markdown-it';\nimport '@carbon/web-components/es/components/list/index.js';\nimport '@carbon/web-components/es/components/checkbox/index.js';\nimport '../../code-snippet/index.js';\nimport '../../card/index.js';\nimport '../../table/index.js';\nimport { defaultLineCountText } from '../../code-snippet/src/formatters.js';\n\nimport { renderTable } from './utils/table-helpers.js';\nimport {\n combineConsecutiveHtmlInline,\n combineSplitHtmlBlocks,\n} from './utils/html-helpers.js';\nimport {\n htmlContainer,\n sanitizeHtmlContent,\n spread,\n} from './utils/lit-directives.js';\nimport {\n isNativelyHandled,\n renderFallback,\n shouldDelegateToPluginRule,\n} from './utils/plugin-fallback.js';\nimport {\n MARKDOWN_SLOT_PREFIX,\n withInstanceNamespace,\n} from './utils/slot-names.js';\nimport { type TokenTree } from './markdown-token-tree.js';\nimport type {\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n// Re-export types so existing imports of these from this module keep working.\nexport type {\n MarkdownCustomRenderers,\n MarkdownRendererChecklist,\n MarkdownRendererChecklistItemArgs,\n MarkdownRendererChecklistToggleArgs,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererCodeBlockData,\n MarkdownRendererImageArgs,\n MarkdownRendererImageResult,\n MarkdownRendererLinkArgs,\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n MarkdownRendererTableArgs,\n MarkdownRendererTableData,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n/**\n * Slot name for an overridable token — unique across the page, stable across\n * streaming ticks. Three parts:\n *\n * - `startLine` (not the full `token.map`) so the name doesn't change when the\n * token's `endLine` advances during streaming;\n * - `currentIndex` from the parent context, disambiguating siblings that share\n * a start line (rare but possible);\n * - the owning element's namespace, because slot hosts from every markdown\n * element on the page are hoisted into one shared light-DOM container and\n * projected back by name (see `./utils/slot-names.js`).\n */\nfunction slotNameFor(\n kind: 'table' | 'codeBlock',\n token: Token,\n options: RenderTokenTreeOptions\n): string {\n const startLine = token.map?.[0] ?? 0;\n const index = options.context?.currentIndex ?? 0;\n return withInstanceNamespace(\n `${MARKDOWN_SLOT_PREFIX}-${kind}-${startLine}-${index}`,\n options\n );\n}\n\n/**\n * Drops attributes DOMPurify considers unsafe (event handlers, `javascript:`\n * URLs, etc.) from a plain attr object. Used both for the parsed token attrs\n * and for attributes a consumer `link`/`image` renderer merges in — the latter\n * bypass the token-attr pass, so they must be re-checked here.\n */\nfunction sanitizeAttrs(attrs: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(attrs).filter(([key, value]) => {\n // Use DOMPurify to check if attribute is safe\n const fragment = DOMPurify.sanitize(`<a ${key}=\"${value}\">`, {\n RETURN_DOM: true,\n });\n const element = fragment.firstChild as Element | null;\n return element?.getAttribute(key) !== null;\n })\n );\n}\n\n/**\n * Concatenates the plain-text content of a node's descendants. A lossy\n * convenience for consumer `link`/`checklist` callbacks that want the visible\n * text; the rich children still render through the normal dispatch.\n */\nfunction extractText(node: TokenTree): string {\n const { token, children } = node;\n if (children && children.length > 0) {\n return children.map(extractText).join('');\n }\n return token.content ?? '';\n}\n\nfunction renderChildTokenTrees(\n children: TokenTree[],\n options: RenderTokenTreeOptions,\n childContext?: RenderTokenTreeOptions['context']\n): TemplateResult {\n const normalizedChildren = combineConsecutiveHtmlInline(\n combineSplitHtmlBlocks(children)\n );\n\n // Multiple or complex children: use repeat for stable keying\n return html`${repeat(\n normalizedChildren,\n (child, index) => {\n // Key by start line + type + tag rather than array index so blocks keep\n // a stable identity when earlier siblings transiently merge/split during\n // streaming re-parses (which would otherwise re-key and remount later\n // blocks — e.g. remounting a code snippet and reloading its editor). We\n // use `token.map?.[0]` (start line, like `slotNameFor`) rather than the\n // node's `key`/`generateKey`, whose embedded end line advances every tick.\n const startLine = child.token.map?.[0] ?? index;\n const stableKey = `${startLine}:${child.token.type}:${child.token.tag}`;\n\n if (child.token.type?.includes('table')) {\n return `table-${stableKey}`;\n }\n\n return `stable-${stableKey}`;\n },\n (child, index) => {\n const result = renderTokenTree(child, {\n ...options,\n context: {\n ...childContext,\n parentChildren: normalizedChildren,\n currentIndex: index,\n },\n });\n // Ensure we never return undefined, which Lit would render as the string \"undefined\"\n return result ?? html``;\n }\n )}`;\n}\n\n/**\n * Top-level entry: renders a markdown token tree to a Lit `TemplateResult`\n * and returns the batch of custom-renderer slot descriptors collected along\n * the way. Callers receive both pieces in one call so the batch can't be\n * accidentally dropped.\n */\nexport function renderMarkdownTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): {\n template: TemplateResult;\n batch: MarkdownRendererSlotDescriptor[];\n} {\n const batch: MarkdownRendererSlotDescriptor[] = [];\n let pluginSlotIndex = 0;\n // Memoized per node, not just counted. `renderFallback` runs inside a\n // lit-html `repeat()` callback, so it evaluates when lit-html commits the\n // template — and one render result gets committed again on any later Lit\n // update that leaves `renderedContent` alone. A bare counter would hand the\n // same token a fresh index on each commit, minting a second slot the very\n // next reconcile retires. First evaluation still assigns 0, 1, 2 in walk\n // order, so a single-commit render is unchanged.\n const pluginSlotIndexes = new WeakMap<TokenTree, number>();\n const template = renderTokenTree(node, {\n ...options,\n recordCustomRender: (descriptor) => batch.push(descriptor),\n pluginSlotCounter: {\n next: (forNode: TokenTree) => {\n const existing = pluginSlotIndexes.get(forNode);\n if (existing !== undefined) {\n return existing;\n }\n const index = pluginSlotIndex++;\n pluginSlotIndexes.set(forNode, index);\n return index;\n },\n },\n });\n return { template, batch };\n}\n\n/**\n * Converts TokenTree to Lit TemplateResult.\n *\n * Recursive renderer; external callers should use {@link renderMarkdownTree}\n * which collects the slot-descriptor batch.\n */\nexport function renderTokenTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): TemplateResult {\n const { token, children } = node;\n const { context, sanitize } = options;\n\n // Handle raw HTML blocks and inline HTML\n if (token.type === 'html_block' || token.type === 'html_inline') {\n // Plugin-overridden html_block rules (rare but supported) — route through\n // the plugin's renderer before our default unsafeHTML pass-through.\n if (\n token.type === 'html_block' &&\n shouldDelegateToPluginRule(token, options.md) &&\n options.md\n ) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n let content = token.content || '';\n\n // Apply HTML sanitization if requested\n if (sanitize && content) {\n content = sanitizeHtmlContent(content);\n }\n\n return html`${unsafeHTML(content)}`;\n }\n\n // Handle split HTML blocks that wrap markdown siblings (e.g. <details>…</details>).\n if (token.type === 'html_container') {\n const openingHtml = token.content ?? '';\n const innerContent = renderChildTokenTrees(children, options, context);\n\n return html`<div\n class=\"cds-aichat-markdown-html-container\"\n ${htmlContainer(openingHtml, innerContent, sanitize)}></div>`;\n }\n\n // Handle plain text content\n if (token.type === 'text') {\n return html`${token.content}`;\n }\n\n // Hard and soft line breaks. Handled before the tag-based dispatch because\n // hardbreak has tag=\"br\", which `renderWithStaticTag` does not know and would\n // route through the plugin-fallback slot machinery.\n if (token.type === 'hardbreak' || token.type === 'softbreak') {\n return token.type === 'softbreak' && options.md?.options.breaks === false\n ? html`${'\\n'}`\n : html`<br />`;\n }\n\n // Handle inline code spans\n if (token.type === 'code_inline') {\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n return html`<code>${token.content}</code>`;\n }\n\n // Handle fenced code blocks\n if (token.type === 'fence') {\n const language = token.info?.trim() ?? '';\n const {\n codeSnippetHighlight = true,\n codeSnippetShowLessText,\n codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText = defaultLineCountText,\n codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable,\n } = options;\n\n const defaultTemplate = html`<cds-aichat-card is-flush>\n <div slot=\"body\">\n <cds-aichat-code-snippet\n data-rounded\n .language=${language}\n .highlight=${codeSnippetHighlight}\n .detectLanguage=${true}\n .showLessText=${codeSnippetShowLessText}\n .showMoreText=${codeSnippetShowMoreText}\n .copyButtonTooltipContent=${codeSnippetCopyButtonTooltipContent}\n .getLineCountText=${codeSnippetGetLineCountText}\n .ariaLabelReadOnly=${codeSnippetAriaLabelReadOnly}\n .ariaLabelEditable=${codeSnippetAriaLabelEditable}\n .code=${token.content}></cds-aichat-code-snippet>\n </div>\n </cds-aichat-card>`;\n\n if (options.customRenderers?.codeBlock) {\n const slotName = slotNameFor('codeBlock', token as Token, options);\n options.recordCustomRender?.({\n slotName,\n kind: 'codeBlock',\n token: token as Token,\n data: {\n language,\n code: token.content ?? '',\n isStreaming: !!options.streaming,\n },\n });\n return html`<slot name=${slotName}>${defaultTemplate}</slot>`;\n }\n\n // Honor user-plugin `fence` overrides (markdown-it-mermaid, syntax\n // highlighters, etc.). customRenderer slot above wins when set.\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n return defaultTemplate;\n }\n\n // Handle structural elements (paragraphs, headings, lists, etc.)\n const tag = token.tag;\n\n // Convert markdown-it attributes (array of [key, value]) into an object.\n const rawAttrs = (token.attrs || []).reduce(\n (acc, [key, value]) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>\n );\n\n // Apply attribute sanitization if requested\n let attrs = rawAttrs;\n const isCustomElement = !!token.tag && token.tag.includes('-');\n if (sanitize && !isCustomElement) {\n attrs = sanitizeAttrs(rawAttrs);\n }\n\n // Set up context for child rendering\n let childContext = context;\n if (tag === 'thead') {\n childContext = { ...context, isInThead: true };\n }\n\n // Render child content\n let content: TemplateResult;\n\n if (children.length === 1 && children[0].token.type === 'text') {\n // Optimization: single text child doesn't need repeat wrapper\n content = html`${children[0].token.content}`;\n } else {\n content = renderChildTokenTrees(children, options, childContext);\n }\n\n // Unknown plugin-introduced tokens (no tag we recognize) — defer to\n // markdown-it's renderer so plugins that register md.renderer.rules[type]\n // (footnote, emoji, deflist, container, etc.) just work.\n if (!tag && options.md && !isNativelyHandled(token)) {\n return renderFallback(token as Token, node, options.md, sanitize, options);\n }\n\n // Handle tokens without HTML tags (just return content)\n if (!tag) {\n return content;\n }\n\n // Render the final HTML element with appropriate tag\n return renderWithStaticTag(\n tag,\n token as Token,\n content,\n attrs,\n options,\n childContext,\n node\n );\n}\n\n/**\n * Renders HTML elements with static tag names.\n */\nfunction renderWithStaticTag(\n tag: string,\n token: Token,\n content: TemplateResult,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n _context?: { isInThead?: boolean },\n node?: TokenTree\n): TemplateResult {\n // Handle root token specially\n if (token.type === 'root') {\n return content;\n }\n\n const hasTaskListItems = (listNode?: TokenTree) =>\n !!listNode?.children?.some((child) => {\n if (child.token.type !== 'list_item_open') {\n return false;\n }\n\n const classAttr = child.token.attrs?.find(([key]) => key === 'class');\n return classAttr?.[1]?.split(/\\s+/).includes('task-list-item');\n });\n\n switch (tag) {\n // Basic block elements\n case 'p':\n return html`<p ${spread(attrs)}>${content}</p>`;\n\n case 'blockquote':\n return html`<blockquote ${spread(attrs)}>${content}</blockquote>`;\n\n case 'pre':\n return html`<pre ${spread(attrs)}>${content}</pre>`;\n\n case 'hr':\n return html`<hr ${spread(attrs)} />`;\n\n // Headings\n case 'h1':\n return html`<h1 ${spread(attrs)}>${content}</h1>`;\n case 'h2':\n return html`<h2 ${spread(attrs)}>${content}</h2>`;\n case 'h3':\n return html`<h3 ${spread(attrs)}>${content}</h3>`;\n case 'h4':\n return html`<h4 ${spread(attrs)}>${content}</h4>`;\n case 'h5':\n return html`<h5 ${spread(attrs)}>${content}</h5>`;\n case 'h6':\n return html`<h6 ${spread(attrs)}>${content}</h6>`;\n\n // Lists with Carbon components\n case 'ul': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ul ${spread(attrs)}>\n ${content}\n </ul>`;\n }\n return html`<p>\n <cds-unordered-list ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-unordered-list>\n </p>`;\n }\n\n case 'ol': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ol ${spread(attrs)}>\n ${content}\n </ol>`;\n }\n return html`<p>\n <cds-ordered-list native ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-ordered-list>\n </p>`;\n }\n\n case 'li': {\n const classList = attrs.class?.split(/\\s+/) ?? [];\n if (classList.includes('task-list-item')) {\n return html`<li ${spread(attrs)}>${content}</li>`;\n }\n return html`<cds-list-item ${spread(attrs)}>${content}</cds-list-item>`;\n }\n\n case 'cds-checkbox': {\n const { checked, disabled, ...otherAttrs } = attrs;\n let isChecked = checked === 'true';\n\n // A configured `checklist` renderer can supply the checked state\n // (so a persisted toggle survives streaming re-renders) and makes the\n // boxes interactive.\n const checklist = options.customRenderers?.checklist;\n if (checklist?.getChecked && node) {\n const override = checklist.getChecked({\n id: otherAttrs['data-cds-aichat-checklist-id'] ?? '',\n label: extractText(node),\n checked: isChecked,\n token,\n });\n if (typeof override === 'boolean') {\n isChecked = override;\n }\n }\n\n const isDisabled = checklist\n ? false\n : disabled === undefined\n ? false\n : disabled === '' || disabled === 'true';\n\n return html`<cds-checkbox\n ?checked=${isChecked}\n ?disabled=${isDisabled}\n ${spread(otherAttrs)}\n >${content}</cds-checkbox\n >`;\n }\n\n // Inline formatting\n case 'strong':\n return html`<strong ${spread(attrs)}>${content}</strong>`;\n case 'em':\n return html`<em ${spread(attrs)}>${content}</em>`;\n case 'code':\n return html`<code ${spread(attrs)}>${content}</code>`;\n case 'del':\n return html`<del ${spread(attrs)}>${content}</del>`;\n case 'sub':\n return html`<sub ${spread(attrs)}>${content}</sub>`;\n case 'sup':\n return html`<sup ${spread(attrs)}>${content}</sup>`;\n case 'span':\n return html`<span ${spread(attrs)}>${content}</span>`;\n case 'i':\n return html`<i ${spread(attrs)}>${content}</i>`;\n case 'b':\n return html`<b ${spread(attrs)}>${content}</b>`;\n case 'small':\n return html`<small ${spread(attrs)}>${content}</small>`;\n case 'mark':\n return html`<mark ${spread(attrs)}>${content}</mark>`;\n case 'ins':\n return html`<ins ${spread(attrs)}>${content}</ins>`;\n case 's':\n return html`<s ${spread(attrs)}>${content}</s>`;\n case 'kbd':\n return html`<kbd ${spread(attrs)}>${content}</kbd>`;\n case 'var':\n return html`<var ${spread(attrs)}>${content}</var>`;\n case 'samp':\n return html`<samp ${spread(attrs)}>${content}</samp>`;\n case 'cite':\n return html`<cite ${spread(attrs)}>${content}</cite>`;\n case 'abbr':\n return html`<abbr ${spread(attrs)}>${content}</abbr>`;\n case 'dfn':\n return html`<dfn ${spread(attrs)}>${content}</dfn>`;\n case 'time':\n return html`<time ${spread(attrs)}>${content}</time>`;\n case 'q':\n return html`<q ${spread(attrs)}>${content}</q>`;\n\n // Links: optional consumer attribute transform, then automatic\n // target=\"_blank\" safety default.\n case 'a': {\n let linkAttrs: Record<string, string> = {\n ...attrs,\n target: attrs.target ?? '_blank',\n };\n\n let onClickHandler: MarkdownRendererLinkResult['onClick'];\n\n const linkRenderer = options.customRenderers?.link;\n\n if (linkRenderer && node) {\n const result = linkRenderer({\n href: attrs.href ?? '',\n title: attrs.title,\n text: extractText(node),\n attributes: { ...attrs },\n token,\n });\n\n if (result) {\n linkAttrs = {\n ...linkAttrs,\n ...(result.attributes ?? {}),\n };\n\n if (result.href !== undefined) {\n linkAttrs.href = result.href;\n }\n if (result.target !== undefined) {\n linkAttrs.target = result.target;\n }\n if (result.rel !== undefined) {\n linkAttrs.rel = result.rel;\n }\n\n // Consumer-supplied attributes are merged after the initial token\n // sanitization pass, so sanitize the final attribute set again.\n if (options.sanitize) {\n linkAttrs = sanitizeAttrs(linkAttrs);\n }\n\n onClickHandler = result.onClick;\n }\n }\n\n return html`<a ${spread(linkAttrs)} @click=${onClickHandler}\n >${content}</a\n >`;\n }\n\n // Self-closing image. A consumer `image` transform wins first (mirroring\n // how `codeBlock` wins over plugin `fence` rules); otherwise\n // plugin-introduced wrappers (e.g. image-figures) route through\n // `shouldDelegateToPluginRule` before falling back to a plain `<img>`.\n case 'img': {\n const imageRenderer = options.customRenderers?.image;\n if (imageRenderer && node) {\n let imgAttrs: Record<string, string> = attrs;\n const result = imageRenderer({\n src: attrs.src ?? '',\n alt: attrs.alt,\n title: attrs.title,\n attributes: { ...attrs },\n token,\n });\n if (result) {\n imgAttrs = { ...attrs, ...(result.attributes ?? {}) };\n if (result.src !== undefined) {\n imgAttrs.src = result.src;\n }\n if (options.sanitize) {\n imgAttrs = sanitizeAttrs(imgAttrs);\n }\n }\n return html`<img ${spread(imgAttrs)} />`;\n }\n if (node && options.md && shouldDelegateToPluginRule(token, options.md)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<img ${spread(attrs)} />`;\n }\n\n // Tables with Carbon component and streaming support\n case 'table': {\n if (!node) {\n return html`<div>Error: Missing table data</div>`;\n }\n const slotName = options.customRenderers?.table\n ? slotNameFor('table', token, options)\n : undefined;\n return renderTable(\n token,\n node,\n attrs,\n options,\n renderTokenTree,\n slotName\n );\n }\n\n // Fallback for unknown tags. If we have the markdown-it instance available,\n // defer to its renderer for plugin-introduced container tags (footnote_block,\n // dl/dt/dd from deflist, custom containers, etc.). Otherwise fall back to\n // a generic <div>.\n default:\n if (options.md && node && !isNativelyHandled(token)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<div ${spread(attrs)}>${content}</div>`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;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A,OAAO,IAAI,CAAA,CAAA,KAAA,EAAQ,MAAM,CAAC,KAAK,CAAC,CAAA,CAAA,EAAI,OAAO,CAAA,MAAA,CAAQ;;AAEzD;;"}
@@ -48,7 +48,12 @@ import { markdownItTaskLists } from './plugins/markdown-it-task-lists.js';
48
48
  * elements (cds-unordered-list, cds-list-item, cds-aichat-table) and break
49
49
  * streaming-friendly per-child diffing for the subtree. Link tokens are
50
50
  * excluded because the native `<a>` dispatch injects `target="_blank"` for
51
- * chat-link safety.
51
+ * chat-link safety. Break tokens (softbreak, hardbreak) are excluded because
52
+ * delegation is priced per token — a slot host and a mount/unmount event pair
53
+ * for every line break — and because `./utils/html-helpers.ts` folds breaks
54
+ * into merged inline-HTML runs and `./utils/table-helpers.ts` flattens them to
55
+ * text, so the override would be honored in some positions and silently
56
+ * dropped in others.
52
57
  *
53
58
  * @internal
54
59
  */
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-token-tree.js","sources":["../../../../src/components/markdown/src/markdown-token-tree.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * The parse/diff layer between raw markdown source and the renderer. Parses with markdown-it (built-in plugins plus any caller-supplied `markdownItPlugins`), builds a nested {@link TokenTree}, and diffs it against the previous tree so streaming updates can reuse stable subtrees.\n *\n * ### Why diff\n *\n * `diffTokenTree` reuses old nodes by `key` whenever the key matches. This is what lets `./markdown-renderer.ts`'s use of Lit's `repeat` directive keep DOM stable during streaming: each incoming chunk re-parses the full source, but matched keys reuse the prior subtree, so only the genuinely new tail differs.\n *\n * ### Why `cachedHtml`\n *\n * For the leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}, when a user plugin's renderer rule produces the HTML (via `./utils/plugin-fallback.ts`), the result is cached on the `TokenTree` node and carried forward by `diffTokenTree` whenever the underlying token's `content` / `attrs` / `info` are unchanged. A stable earlier-in-document fence/image/etc. therefore isn't re-rendered through the plugin's rule on every streaming chunk. The cache is tagged with the `MarkdownIt` instance that produced it; a plugin swap (which builds a fresh instance) invalidates the cache on read.\n *\n * The block comment on {@link PLUGIN_DELEGABLE_TOKEN_TYPES} explains why only those four token types are eligible for delegation.\n *\n * ### Related files\n *\n * - `./markdown-renderer.ts` — consumes the `TokenTree` and produces a Lit `TemplateResult`.\n * - `./utils/plugin-fallback.ts` — reads `cachedHtml` and {@link getPluginOverriddenRules} to drive the delegated-render flow.\n */\n\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport { markdownItAttrs } from './plugins/markdown-it-attrs';\nimport { markdownItHighlight } from './plugins/markdown-it-highlight';\nimport { markdownItTaskLists } from './plugins/markdown-it-task-lists';\n\n/**\n * Represents a node in the token tree structure.\n */\nexport interface TokenTree {\n /** Unique identifier for this node, used for efficient diffing */\n key: string;\n /** The original markdown-it token data */\n token: Partial<Token>;\n /** Child nodes for nested content */\n children: TokenTree[];\n /**\n * Cached HTML produced by `md.renderer.render()` for leaf tokens whose\n * renderer rule was overridden by a user plugin. Tagged with the\n * `MarkdownIt` instance that produced it so a plugin swap (which builds a\n * fresh instance) invalidates the cache on read. Inherited across\n * {@link diffTokenTree} when the token's content and attrs are unchanged so\n * the plugin's rule isn't re-invoked on every streaming chunk. Only\n * populated for token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}.\n * @internal\n */\n cachedHtml?: { md: MarkdownIt; html: string };\n}\n\n/**\n * Token types whose renderer rule, when overridden by a user-supplied\n * markdown-it plugin, will be honored — instead of the native Lit dispatch.\n * All four are leaf tokens (`nesting === 0`) so the slice handed to\n * `md.renderer.render()` is a single token and the rendered HTML can be\n * safely cached on the {@link TokenTree} node.\n *\n * Container tokens (paragraph_open, heading_open, list_*_open, table_open)\n * are intentionally excluded: delegating them would erase Carbon custom\n * elements (cds-unordered-list, cds-list-item, cds-aichat-table) and break\n * streaming-friendly per-child diffing for the subtree. Link tokens are\n * excluded because the native `<a>` dispatch injects `target=\"_blank\"` for\n * chat-link safety.\n *\n * @internal\n */\nexport const PLUGIN_DELEGABLE_TOKEN_TYPES: ReadonlySet<string> = new Set([\n 'fence',\n 'image',\n 'code_inline',\n 'html_block',\n]);\n\n/**\n * A markdown-it plugin reference. Either a bare plugin function or a\n * `[plugin, options]` / `[plugin, ...params]` tuple matching\n * `MarkdownIt.use(...)`.\n */\nexport type MarkdownItPlugin =\n | MarkdownIt.PluginSimple\n | [MarkdownIt.PluginWithOptions<unknown>, unknown]\n | [MarkdownIt.PluginWithParams, ...unknown[]];\n\n// Per-instance set of renderer-rule keys that user plugins overrode (or\n// added) relative to the snapshot taken after our built-in plugins ran.\n// WeakMap so cleanup follows the MarkdownIt instance's lifetime.\nconst pluginOverriddenRulesByMd = new WeakMap<\n MarkdownIt,\n ReadonlySet<string>\n>();\n\nconst EMPTY_RULE_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * Returns the set of renderer-rule keys that user-supplied plugins overrode\n * (or freshly added) on the given markdown-it instance, relative to the\n * baseline established after our built-in plugins (markdownItAttrs,\n * markdownItHighlight, markdownItTaskLists) ran. The renderer uses this to\n * decide which token types to route through `md.renderer.render()` instead\n * of native Lit dispatch. Returns an empty set for instances we didn't build.\n *\n * @internal\n */\nexport function getPluginOverriddenRules(md: MarkdownIt): ReadonlySet<string> {\n return pluginOverriddenRulesByMd.get(md) ?? EMPTY_RULE_SET;\n}\n\n/**\n * Builds a new markdown-it instance with the built-in plugins and any user-supplied\n * plugins applied on top. `options.html` selects whether raw HTML is parsed as HTML\n * (`true`, the default) or neutralized to inert escaped text (`false`, used when\n * {@link CDSAIChatMarkdown.removeHTML} is set). Both variants are built through this\n * same path so plugin application and overridden-rule snapshotting stay identical.\n *\n * Snapshots `md.renderer.rules` after the built-in plugins but before the user\n * plugins, then records the keys whose function reference changed (or whose\n * key was added) into {@link pluginOverriddenRulesByMd}.\n */\nfunction createMarkdownIt(\n plugins?: MarkdownItPlugin[],\n options: { html?: boolean } = {}\n): MarkdownIt {\n const md = new MarkdownIt('commonmark', {\n html: options.html ?? true,\n breaks: true,\n linkify: true,\n })\n .enable('table')\n .enable('strikethrough')\n .enable('linkify')\n .use(markdownItAttrs)\n .use(markdownItHighlight)\n .use(markdownItTaskLists);\n\n const baselineRules: Record<string, unknown> = {\n ...(md.renderer.rules as Record<string, unknown>),\n };\n\n for (const plugin of plugins ?? []) {\n if (Array.isArray(plugin)) {\n const [fn, ...args] = plugin;\n (md as MarkdownIt).use(fn as MarkdownIt.PluginWithParams, ...args);\n } else {\n md.use(plugin);\n }\n }\n\n const currentRules = md.renderer.rules as Record<string, unknown>;\n const overridden = new Set<string>();\n const allKeys = new Set<string>([\n ...Object.keys(baselineRules),\n ...Object.keys(currentRules),\n ]);\n for (const key of allKeys) {\n if (currentRules[key] !== baselineRules[key]) {\n overridden.add(key);\n }\n }\n pluginOverriddenRulesByMd.set(md, overridden);\n\n return md;\n}\n\n// Each plugin identity caches both an html-enabled and an html-disabled instance,\n// built lazily on first use. `removeHTML` selects the no-html variant.\ninterface MarkdownItVariants {\n html?: MarkdownIt;\n noHtml?: MarkdownIt;\n}\n\n// Cache for the no-plugins default instances.\nconst defaultMarkdownIt: MarkdownItVariants = {};\n\n// Cache keyed by plugin-array identity. WeakMap so plugin arrays that go out of\n// scope can be collected.\nconst markdownItCache = new WeakMap<MarkdownItPlugin[], MarkdownItVariants>();\n\n/**\n * Returns a (cached) markdown-it instance for the given plugin set, choosing the\n * html-enabled variant or the html-disabled (HTML-neutralizing) variant based on\n * `removeHtml`. Calling with the same `plugins` reference and `removeHtml` returns\n * the same instance.\n */\nexport function getMarkdownIt(\n plugins?: MarkdownItPlugin[],\n removeHtml = false\n): MarkdownIt {\n const variants =\n !plugins || plugins.length === 0\n ? defaultMarkdownIt\n : (markdownItCache.get(plugins) ??\n (() => {\n const created: MarkdownItVariants = {};\n markdownItCache.set(plugins, created);\n return created;\n })());\n\n const slot = removeHtml ? 'noHtml' : 'html';\n if (!variants[slot]) {\n variants[slot] = createMarkdownIt(plugins, { html: !removeHtml });\n }\n return variants[slot] as MarkdownIt;\n}\n\n// markdown-it treats a closing HTML tag and the next markdown line (ie. </div>\\n##Heading) as one HTML\n// block when there is no blank line between them. Insert an extra newline so the\n// following markdown is parsed as markdown, not swallowed into the HTML token.\nfunction normalizeHtmlBlockBoundaries(markdown: string): string {\n return markdown.replace(\n /(^|\\n)(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\r?\\n)(?=\\S)/g,\n '$1$2$3$3'\n );\n}\n\n// Fallback for html_block tokens that still bundle a closing tag with trailing\n// markdown on the next line. Split them so the closer stays HTML and the rest\n// is re-parsed as markdown.\nfunction splitHtmlBlockTrailingMarkdown(\n tokens: Token[],\n md: MarkdownIt\n): Token[] {\n return tokens.flatMap((token) => {\n if (token.type !== 'html_block') {\n return [token];\n }\n\n const trailingMarkdownMatch = token.content.match(\n /^(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\s*\\n)([\\s\\S]*\\S[\\s\\S]*)$/\n );\n\n if (!trailingMarkdownMatch) {\n return [token];\n }\n\n const [, closingHtml, leadingWhitespace, trailingMarkdown] =\n trailingMarkdownMatch;\n const htmlToken = {\n ...token,\n content: closingHtml,\n map: token.map ? [token.map[0], token.map[0] + 1] : token.map,\n } as Token;\n\n return [\n htmlToken,\n ...md.parse(`${leadingWhitespace}${trailingMarkdown}`, {}),\n ];\n });\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the given instance.\n *\n * When `removeHtml` is set, `md` is the html-disabled instance: raw HTML is\n * neutralized to inert escaped text (content preserved) and there are no HTML\n * blocks to normalize or split, so the boundary fixups are skipped.\n */\nfunction parseMarkdown(\n fullText: string,\n md: MarkdownIt,\n removeHtml: boolean\n): Token[] {\n if (removeHtml) {\n return md.parse(fullText, {});\n }\n const normalizedText = normalizeHtmlBlockBoundaries(fullText);\n return splitHtmlBlockTrailingMarkdown(md.parse(normalizedText, {}), md);\n}\n\n/**\n * Generates a unique string key for a markdown-it token.\n *\n * The key combines the token type, HTML tag, and source position to create\n * a stable identifier that can be used by Lit's repeat() directive for\n * efficient DOM updates.\n */\nfunction generateKey(token: Token): string {\n const map = token.map ? token.map.join('-') : '';\n return `${token.type}:${token.tag}:${map}`;\n}\n\n/**\n * Converts a flat list of markdown-it tokens into a tree.\n */\nexport function buildTokenTree(tokens: Token[]): TokenTree {\n // Create the root node that will contain all top-level content\n const root: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n // Stack tracks the current nesting context while building the tree\n const stack: TokenTree[] = [root];\n\n tokens.forEach((token) => {\n // Create a new node for this token\n const node: TokenTree = {\n key: generateKey(token),\n token,\n children: [],\n };\n\n // Handle inline tokens that contain their own child tokens\n // (e.g., a paragraph containing bold, italic, and text tokens)\n if (token.type === 'inline' && token.children?.length) {\n node.children = buildTokenTree(token.children).children;\n }\n\n const current = stack[stack.length - 1];\n\n if (token.nesting === 1) {\n // Opening tag: add node to current container and descend into it\n current.children.push(node);\n stack.push(node);\n } else if (token.nesting === -1) {\n // Closing tag: exit current container\n stack.pop();\n } else {\n // Self-contained token: add to current container\n current.children.push(node);\n }\n });\n\n return root;\n}\n\nfunction attrsEqual(\n a: Token['attrs'] | undefined,\n b: Token['attrs'] | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two TokenTree structures and creates a new tree that reuses\n * unchanged nodes from the old tree.\n *\n * This optimization is crucial for performance when content is being streamed\n * or updated incrementally.\n */\nexport function diffTokenTree(\n oldTree: TokenTree | undefined,\n newTree: TokenTree\n): TokenTree {\n // If keys don't match, the entire subtree changed - use new tree\n if (!oldTree || oldTree.key !== newTree.key) {\n return newTree;\n }\n\n // Keys match so create merged tree reusing unchanged children\n const merged: TokenTree = {\n key: newTree.key,\n token: newTree.token,\n children: [],\n };\n\n // Carry forward the rendered-HTML cache for leaf tokens delegated to the\n // markdown-it renderer. Skip when the underlying token content, attrs, or\n // info changed (info is the fence's language string and drives the rendered\n // output for plugins like markdown-it-mermaid / syntax highlighters).\n if (\n oldTree.cachedHtml !== undefined &&\n typeof newTree.token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(newTree.token.type) &&\n oldTree.token.content === newTree.token.content &&\n oldTree.token.info === newTree.token.info &&\n attrsEqual(\n oldTree.token.attrs ?? undefined,\n newTree.token.attrs ?? undefined\n )\n ) {\n merged.cachedHtml = oldTree.cachedHtml;\n }\n\n // Create lookup map of old children by key for efficient comparison\n const oldChildrenByKey = new Map(\n oldTree.children.map((child) => [child.key, child])\n );\n\n // Process each new child, reusing old ones where possible\n newTree.children.forEach((newChild) => {\n const oldChild = oldChildrenByKey.get(newChild.key);\n\n if (oldChild) {\n // Recursively diff matching children\n merged.children.push(diffTokenTree(oldChild, newChild));\n } else {\n // Use new child as-is\n merged.children.push(newChild);\n }\n });\n\n return merged;\n}\n\n/**\n * Result of {@link markdownToTokenTree}. Returns the parsed tree plus the\n * markdown-it instance used to produce it so the renderer can fall back to\n * `md.renderer.render()` for plugin-introduced tokens. The set of\n * plugin-overridden rules is read from the per-instance WeakMap via\n * {@link getPluginOverriddenRules} as needed.\n */\nexport interface MarkdownToTokenTreeResult {\n tree: TokenTree;\n md: MarkdownIt;\n}\n\n/**\n * Converts markdown into a tree with keys on it for Lit. The returned `md` is the\n * (cached) markdown-it instance keyed by `markdownItPlugins` identity and the\n * `removeHtml` flag (html-enabled vs html-neutralizing variant).\n */\nexport function markdownToTokenTree(\n markdown: string,\n lastTree: TokenTree | undefined,\n opts: { removeHtml?: boolean; markdownItPlugins?: MarkdownItPlugin[] } = {}\n): MarkdownToTokenTreeResult {\n const removeHtml = opts.removeHtml ?? false;\n const md = getMarkdownIt(opts.markdownItPlugins, removeHtml);\n const tokens = parseMarkdown(markdown, md, removeHtml);\n const tree = diffTokenTree(lastTree, buildTokenTree(tokens));\n return { tree, md };\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the default\n * plugin set. `allowHtml` is the inverse of the renderer's `removeHtml` flag.\n *\n * Used by the chat-side rich user message bubble (inline markdown rendering),\n * which needs the raw markdown-it tokens rather than a {@link TokenTree}.\n */\nexport function markdownToMarkdownItTokens(\n fullText: string,\n allowHtml = true\n): Token[] {\n const removeHtml = !allowHtml;\n return parseMarkdown(\n fullText,\n getMarkdownIt(undefined, removeHtml),\n removeHtml\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;AAiBG;AA+BH;;;;;;;;;;;;;;;AAeG;AACI,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAAC;IACvE,OAAO;IACP,OAAO;IACP,aAAa;IACb,YAAY;AACb,CAAA;AAYD;AACA;AACA;AACA,MAAM,yBAAyB,GAAG,IAAI,OAAO,EAG1C;AAEH,MAAM,cAAc,GAAwB,IAAI,GAAG,EAAU;AAE7D;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,EAAc,EAAA;IACrD,OAAO,yBAAyB,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,cAAc;AAC5D;AAEA;;;;;;;;;;AAUG;AACH,SAAS,gBAAgB,CACvB,OAA4B,EAC5B,UAA8B,EAAE,EAAA;AAEhC,IAAA,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,YAAY,EAAE;AACtC,QAAA,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,IAAI;AAC1B,QAAA,MAAM,EAAE,IAAI;AACZ,QAAA,OAAO,EAAE,IAAI;KACd;SACE,MAAM,CAAC,OAAO;SACd,MAAM,CAAC,eAAe;SACtB,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G,IAAI,EAAA;AAEhB,IAAA,MAAM,UAAU,GAAG,CAAC,SAAS;AAC7B,IAAA,OAAO,aAAa,CAClB,QAAQ,EACR,aAAa,CAAC,SAAS,EAAE,UAAU,CAAC,EACpC,UAAU,CACX;AACH;;"}
1
+ {"version":3,"file":"markdown-token-tree.js","sources":["../../../../src/components/markdown/src/markdown-token-tree.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * The parse/diff layer between raw markdown source and the renderer. Parses with markdown-it (built-in plugins plus any caller-supplied `markdownItPlugins`), builds a nested {@link TokenTree}, and diffs it against the previous tree so streaming updates can reuse stable subtrees.\n *\n * ### Why diff\n *\n * `diffTokenTree` reuses old nodes by `key` whenever the key matches. This is what lets `./markdown-renderer.ts`'s use of Lit's `repeat` directive keep DOM stable during streaming: each incoming chunk re-parses the full source, but matched keys reuse the prior subtree, so only the genuinely new tail differs.\n *\n * ### Why `cachedHtml`\n *\n * For the leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}, when a user plugin's renderer rule produces the HTML (via `./utils/plugin-fallback.ts`), the result is cached on the `TokenTree` node and carried forward by `diffTokenTree` whenever the underlying token's `content` / `attrs` / `info` are unchanged. A stable earlier-in-document fence/image/etc. therefore isn't re-rendered through the plugin's rule on every streaming chunk. The cache is tagged with the `MarkdownIt` instance that produced it; a plugin swap (which builds a fresh instance) invalidates the cache on read.\n *\n * The block comment on {@link PLUGIN_DELEGABLE_TOKEN_TYPES} explains why only those four token types are eligible for delegation.\n *\n * ### Related files\n *\n * - `./markdown-renderer.ts` — consumes the `TokenTree` and produces a Lit `TemplateResult`.\n * - `./utils/plugin-fallback.ts` — reads `cachedHtml` and {@link getPluginOverriddenRules} to drive the delegated-render flow.\n */\n\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport { markdownItAttrs } from './plugins/markdown-it-attrs';\nimport { markdownItHighlight } from './plugins/markdown-it-highlight';\nimport { markdownItTaskLists } from './plugins/markdown-it-task-lists';\n\n/**\n * Represents a node in the token tree structure.\n */\nexport interface TokenTree {\n /** Unique identifier for this node, used for efficient diffing */\n key: string;\n /** The original markdown-it token data */\n token: Partial<Token>;\n /** Child nodes for nested content */\n children: TokenTree[];\n /**\n * Cached HTML produced by `md.renderer.render()` for leaf tokens whose\n * renderer rule was overridden by a user plugin. Tagged with the\n * `MarkdownIt` instance that produced it so a plugin swap (which builds a\n * fresh instance) invalidates the cache on read. Inherited across\n * {@link diffTokenTree} when the token's content and attrs are unchanged so\n * the plugin's rule isn't re-invoked on every streaming chunk. Only\n * populated for token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}.\n * @internal\n */\n cachedHtml?: { md: MarkdownIt; html: string };\n}\n\n/**\n * Token types whose renderer rule, when overridden by a user-supplied\n * markdown-it plugin, will be honored — instead of the native Lit dispatch.\n * All four are leaf tokens (`nesting === 0`) so the slice handed to\n * `md.renderer.render()` is a single token and the rendered HTML can be\n * safely cached on the {@link TokenTree} node.\n *\n * Container tokens (paragraph_open, heading_open, list_*_open, table_open)\n * are intentionally excluded: delegating them would erase Carbon custom\n * elements (cds-unordered-list, cds-list-item, cds-aichat-table) and break\n * streaming-friendly per-child diffing for the subtree. Link tokens are\n * excluded because the native `<a>` dispatch injects `target=\"_blank\"` for\n * chat-link safety. Break tokens (softbreak, hardbreak) are excluded because\n * delegation is priced per token — a slot host and a mount/unmount event pair\n * for every line break — and because `./utils/html-helpers.ts` folds breaks\n * into merged inline-HTML runs and `./utils/table-helpers.ts` flattens them to\n * text, so the override would be honored in some positions and silently\n * dropped in others.\n *\n * @internal\n */\nexport const PLUGIN_DELEGABLE_TOKEN_TYPES: ReadonlySet<string> = new Set([\n 'fence',\n 'image',\n 'code_inline',\n 'html_block',\n]);\n\n/**\n * A markdown-it plugin reference. Either a bare plugin function or a\n * `[plugin, options]` / `[plugin, ...params]` tuple matching\n * `MarkdownIt.use(...)`.\n */\nexport type MarkdownItPlugin =\n | MarkdownIt.PluginSimple\n | [MarkdownIt.PluginWithOptions<unknown>, unknown]\n | [MarkdownIt.PluginWithParams, ...unknown[]];\n\n// Per-instance set of renderer-rule keys that user plugins overrode (or\n// added) relative to the snapshot taken after our built-in plugins ran.\n// WeakMap so cleanup follows the MarkdownIt instance's lifetime.\nconst pluginOverriddenRulesByMd = new WeakMap<\n MarkdownIt,\n ReadonlySet<string>\n>();\n\nconst EMPTY_RULE_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * Returns the set of renderer-rule keys that user-supplied plugins overrode\n * (or freshly added) on the given markdown-it instance, relative to the\n * baseline established after our built-in plugins (markdownItAttrs,\n * markdownItHighlight, markdownItTaskLists) ran. The renderer uses this to\n * decide which token types to route through `md.renderer.render()` instead\n * of native Lit dispatch. Returns an empty set for instances we didn't build.\n *\n * @internal\n */\nexport function getPluginOverriddenRules(md: MarkdownIt): ReadonlySet<string> {\n return pluginOverriddenRulesByMd.get(md) ?? EMPTY_RULE_SET;\n}\n\n/**\n * Builds a new markdown-it instance with the built-in plugins and any user-supplied\n * plugins applied on top. `options.html` selects whether raw HTML is parsed as HTML\n * (`true`, the default) or neutralized to inert escaped text (`false`, used when\n * {@link CDSAIChatMarkdown.removeHTML} is set). Both variants are built through this\n * same path so plugin application and overridden-rule snapshotting stay identical.\n *\n * Snapshots `md.renderer.rules` after the built-in plugins but before the user\n * plugins, then records the keys whose function reference changed (or whose\n * key was added) into {@link pluginOverriddenRulesByMd}.\n */\nfunction createMarkdownIt(\n plugins?: MarkdownItPlugin[],\n options: { html?: boolean } = {}\n): MarkdownIt {\n const md = new MarkdownIt('commonmark', {\n html: options.html ?? true,\n breaks: true,\n linkify: true,\n })\n .enable('table')\n .enable('strikethrough')\n .enable('linkify')\n .use(markdownItAttrs)\n .use(markdownItHighlight)\n .use(markdownItTaskLists);\n\n const baselineRules: Record<string, unknown> = {\n ...(md.renderer.rules as Record<string, unknown>),\n };\n\n for (const plugin of plugins ?? []) {\n if (Array.isArray(plugin)) {\n const [fn, ...args] = plugin;\n (md as MarkdownIt).use(fn as MarkdownIt.PluginWithParams, ...args);\n } else {\n md.use(plugin);\n }\n }\n\n const currentRules = md.renderer.rules as Record<string, unknown>;\n const overridden = new Set<string>();\n const allKeys = new Set<string>([\n ...Object.keys(baselineRules),\n ...Object.keys(currentRules),\n ]);\n for (const key of allKeys) {\n if (currentRules[key] !== baselineRules[key]) {\n overridden.add(key);\n }\n }\n pluginOverriddenRulesByMd.set(md, overridden);\n\n return md;\n}\n\n// Each plugin identity caches both an html-enabled and an html-disabled instance,\n// built lazily on first use. `removeHTML` selects the no-html variant.\ninterface MarkdownItVariants {\n html?: MarkdownIt;\n noHtml?: MarkdownIt;\n}\n\n// Cache for the no-plugins default instances.\nconst defaultMarkdownIt: MarkdownItVariants = {};\n\n// Cache keyed by plugin-array identity. WeakMap so plugin arrays that go out of\n// scope can be collected.\nconst markdownItCache = new WeakMap<MarkdownItPlugin[], MarkdownItVariants>();\n\n/**\n * Returns a (cached) markdown-it instance for the given plugin set, choosing the\n * html-enabled variant or the html-disabled (HTML-neutralizing) variant based on\n * `removeHtml`. Calling with the same `plugins` reference and `removeHtml` returns\n * the same instance.\n */\nexport function getMarkdownIt(\n plugins?: MarkdownItPlugin[],\n removeHtml = false\n): MarkdownIt {\n const variants =\n !plugins || plugins.length === 0\n ? defaultMarkdownIt\n : (markdownItCache.get(plugins) ??\n (() => {\n const created: MarkdownItVariants = {};\n markdownItCache.set(plugins, created);\n return created;\n })());\n\n const slot = removeHtml ? 'noHtml' : 'html';\n if (!variants[slot]) {\n variants[slot] = createMarkdownIt(plugins, { html: !removeHtml });\n }\n return variants[slot] as MarkdownIt;\n}\n\n// markdown-it treats a closing HTML tag and the next markdown line (ie. </div>\\n##Heading) as one HTML\n// block when there is no blank line between them. Insert an extra newline so the\n// following markdown is parsed as markdown, not swallowed into the HTML token.\nfunction normalizeHtmlBlockBoundaries(markdown: string): string {\n return markdown.replace(\n /(^|\\n)(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\r?\\n)(?=\\S)/g,\n '$1$2$3$3'\n );\n}\n\n// Fallback for html_block tokens that still bundle a closing tag with trailing\n// markdown on the next line. Split them so the closer stays HTML and the rest\n// is re-parsed as markdown.\nfunction splitHtmlBlockTrailingMarkdown(\n tokens: Token[],\n md: MarkdownIt\n): Token[] {\n return tokens.flatMap((token) => {\n if (token.type !== 'html_block') {\n return [token];\n }\n\n const trailingMarkdownMatch = token.content.match(\n /^(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\s*\\n)([\\s\\S]*\\S[\\s\\S]*)$/\n );\n\n if (!trailingMarkdownMatch) {\n return [token];\n }\n\n const [, closingHtml, leadingWhitespace, trailingMarkdown] =\n trailingMarkdownMatch;\n const htmlToken = {\n ...token,\n content: closingHtml,\n map: token.map ? [token.map[0], token.map[0] + 1] : token.map,\n } as Token;\n\n return [\n htmlToken,\n ...md.parse(`${leadingWhitespace}${trailingMarkdown}`, {}),\n ];\n });\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the given instance.\n *\n * When `removeHtml` is set, `md` is the html-disabled instance: raw HTML is\n * neutralized to inert escaped text (content preserved) and there are no HTML\n * blocks to normalize or split, so the boundary fixups are skipped.\n */\nfunction parseMarkdown(\n fullText: string,\n md: MarkdownIt,\n removeHtml: boolean\n): Token[] {\n if (removeHtml) {\n return md.parse(fullText, {});\n }\n const normalizedText = normalizeHtmlBlockBoundaries(fullText);\n return splitHtmlBlockTrailingMarkdown(md.parse(normalizedText, {}), md);\n}\n\n/**\n * Generates a unique string key for a markdown-it token.\n *\n * The key combines the token type, HTML tag, and source position to create\n * a stable identifier that can be used by Lit's repeat() directive for\n * efficient DOM updates.\n */\nfunction generateKey(token: Token): string {\n const map = token.map ? token.map.join('-') : '';\n return `${token.type}:${token.tag}:${map}`;\n}\n\n/**\n * Converts a flat list of markdown-it tokens into a tree.\n */\nexport function buildTokenTree(tokens: Token[]): TokenTree {\n // Create the root node that will contain all top-level content\n const root: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n // Stack tracks the current nesting context while building the tree\n const stack: TokenTree[] = [root];\n\n tokens.forEach((token) => {\n // Create a new node for this token\n const node: TokenTree = {\n key: generateKey(token),\n token,\n children: [],\n };\n\n // Handle inline tokens that contain their own child tokens\n // (e.g., a paragraph containing bold, italic, and text tokens)\n if (token.type === 'inline' && token.children?.length) {\n node.children = buildTokenTree(token.children).children;\n }\n\n const current = stack[stack.length - 1];\n\n if (token.nesting === 1) {\n // Opening tag: add node to current container and descend into it\n current.children.push(node);\n stack.push(node);\n } else if (token.nesting === -1) {\n // Closing tag: exit current container\n stack.pop();\n } else {\n // Self-contained token: add to current container\n current.children.push(node);\n }\n });\n\n return root;\n}\n\nfunction attrsEqual(\n a: Token['attrs'] | undefined,\n b: Token['attrs'] | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two TokenTree structures and creates a new tree that reuses\n * unchanged nodes from the old tree.\n *\n * This optimization is crucial for performance when content is being streamed\n * or updated incrementally.\n */\nexport function diffTokenTree(\n oldTree: TokenTree | undefined,\n newTree: TokenTree\n): TokenTree {\n // If keys don't match, the entire subtree changed - use new tree\n if (!oldTree || oldTree.key !== newTree.key) {\n return newTree;\n }\n\n // Keys match so create merged tree reusing unchanged children\n const merged: TokenTree = {\n key: newTree.key,\n token: newTree.token,\n children: [],\n };\n\n // Carry forward the rendered-HTML cache for leaf tokens delegated to the\n // markdown-it renderer. Skip when the underlying token content, attrs, or\n // info changed (info is the fence's language string and drives the rendered\n // output for plugins like markdown-it-mermaid / syntax highlighters).\n if (\n oldTree.cachedHtml !== undefined &&\n typeof newTree.token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(newTree.token.type) &&\n oldTree.token.content === newTree.token.content &&\n oldTree.token.info === newTree.token.info &&\n attrsEqual(\n oldTree.token.attrs ?? undefined,\n newTree.token.attrs ?? undefined\n )\n ) {\n merged.cachedHtml = oldTree.cachedHtml;\n }\n\n // Create lookup map of old children by key for efficient comparison\n const oldChildrenByKey = new Map(\n oldTree.children.map((child) => [child.key, child])\n );\n\n // Process each new child, reusing old ones where possible\n newTree.children.forEach((newChild) => {\n const oldChild = oldChildrenByKey.get(newChild.key);\n\n if (oldChild) {\n // Recursively diff matching children\n merged.children.push(diffTokenTree(oldChild, newChild));\n } else {\n // Use new child as-is\n merged.children.push(newChild);\n }\n });\n\n return merged;\n}\n\n/**\n * Result of {@link markdownToTokenTree}. Returns the parsed tree plus the\n * markdown-it instance used to produce it so the renderer can fall back to\n * `md.renderer.render()` for plugin-introduced tokens. The set of\n * plugin-overridden rules is read from the per-instance WeakMap via\n * {@link getPluginOverriddenRules} as needed.\n */\nexport interface MarkdownToTokenTreeResult {\n tree: TokenTree;\n md: MarkdownIt;\n}\n\n/**\n * Converts markdown into a tree with keys on it for Lit. The returned `md` is the\n * (cached) markdown-it instance keyed by `markdownItPlugins` identity and the\n * `removeHtml` flag (html-enabled vs html-neutralizing variant).\n */\nexport function markdownToTokenTree(\n markdown: string,\n lastTree: TokenTree | undefined,\n opts: { removeHtml?: boolean; markdownItPlugins?: MarkdownItPlugin[] } = {}\n): MarkdownToTokenTreeResult {\n const removeHtml = opts.removeHtml ?? false;\n const md = getMarkdownIt(opts.markdownItPlugins, removeHtml);\n const tokens = parseMarkdown(markdown, md, removeHtml);\n const tree = diffTokenTree(lastTree, buildTokenTree(tokens));\n return { tree, md };\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the default\n * plugin set. `allowHtml` is the inverse of the renderer's `removeHtml` flag.\n *\n * Used by the chat-side rich user message bubble (inline markdown rendering),\n * which needs the raw markdown-it tokens rather than a {@link TokenTree}.\n */\nexport function markdownToMarkdownItTokens(\n fullText: string,\n allowHtml = true\n): Token[] {\n const removeHtml = !allowHtml;\n return parseMarkdown(\n fullText,\n getMarkdownIt(undefined, removeHtml),\n removeHtml\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;AAiBG;AA+BH;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAAC;IACvE,OAAO;IACP,OAAO;IACP,aAAa;IACb,YAAY;AACb,CAAA;AAYD;AACA;AACA;AACA,MAAM,yBAAyB,GAAG,IAAI,OAAO,EAG1C;AAEH,MAAM,cAAc,GAAwB,IAAI,GAAG,EAAU;AAE7D;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,EAAc,EAAA;IACrD,OAAO,yBAAyB,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,cAAc;AAC5D;AAEA;;;;;;;;;;AAUG;AACH,SAAS,gBAAgB,CACvB,OAA4B,EAC5B,UAA8B,EAAE,EAAA;AAEhC,IAAA,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,YAAY,EAAE;AACtC,QAAA,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,IAAI;AAC1B,QAAA,MAAM,EAAE,IAAI;AACZ,QAAA,OAAO,EAAE,IAAI;KACd;SACE,MAAM,CAAC,OAAO;SACd,MAAM,CAAC,eAAe;SACtB,MAAM,CAAC,SAAS;SAChB,GAAG,CAAC,eAAe;SACnB,GAAG,CAAC,mBAAmB;SACvB,GAAG,CAAC,mBAAmB,CAAC;AAE3B,IAAA,MAAM,aAAa,GAA4B;AAC7C,QAAA,GAAI,EAAE,CAAC,QAAQ,CAAC,KAAiC;KAClD;AAED,IAAA,KAAK,MAAM,MAAM,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carbon rendering. Returning the same element reference across
105
105
  * renders avoids DOM churn.
106
106
  *
107
- * The consumer's returned element lives in this element's light DOM, not
108
- * in its shadow root, so external CSS applies normally.
107
+ * Inside a chat, a container relocates the returned element into its own
108
+ * light DOM — page DOM at the top of the chain — and this element forwards
109
+ * it back into the named slot, so consumer-loaded page CSS reaches it.
110
+ * Standalone (no chat ancestor), it stays a light-DOM child of this element.
109
111
  */
110
112
  customRenderers?: MarkdownCustomRenderers;
111
113
  private hasRenderedStreamingTableLoadingFrame;
@@ -125,6 +127,7 @@ declare class CDSAIChatMarkdown extends LitElement {
125
127
  protected willUpdate(changed: PropertyValues<this>): void;
126
128
  protected getUpdateComplete(): Promise<boolean>;
127
129
  protected updated(changed: PropertyValues<this>): void;
130
+ private retireDelegatedSlot;
128
131
  protected render(): TemplateResult<1>;
129
132
  }
130
133
  declare global {
@@ -157,6 +157,19 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
157
157
  * @internal
158
158
  */
159
159
  this.slotHosts = new Map();
160
+ /**
161
+ * `<slot name=X slot=X>` forwarders minted for {@link customRenderers} hosts
162
+ * an outer listener relocated into its own light DOM, keyed by slot name.
163
+ *
164
+ * Appended imperatively rather than rendered: Lit commits into the shadow
165
+ * root, and this hop has to be a light-DOM child of this element to gather
166
+ * the relocated host out of the chat element's light DOM and hand it to the
167
+ * shadow `<slot>` the renderer emitted. Minted where the claim is read
168
+ * rather than by a subscriber, because the mount event fires once per host
169
+ * and is never replayed — a listener that subscribes later cannot mint it.
170
+ * @internal
171
+ */
172
+ this.rendererForwarders = new Map();
160
173
  /**
161
174
  * Namespace appended to every slot name this element mints, so two markdown
162
175
  * elements rendering identical markdown never collide in the shared
@@ -171,8 +184,8 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
171
184
  this.slotNamespace = nextMarkdownInstanceId();
172
185
  /**
173
186
  * Slot names whose host was created by an outer listener (a chat container
174
- * that called `preventDefault()` on the host-mount event). We track these
175
- * so we can fire matching unmount events without trying to remove a host we
187
+ * that called `preventDefault()` on the host-mount event). We track these so
188
+ * we can fire matching unmount events without trying to remove a host we
176
189
  * never appended.
177
190
  * @internal
178
191
  */
@@ -433,15 +446,12 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
433
446
  host.remove();
434
447
  }
435
448
  this.slotHosts.clear();
436
- // Ask any delegating chat container to drop its hosts too.
437
- for (const slotName of this.delegatedPluginSlots) {
438
- this.dispatchEvent(new CustomEvent('cds-aichat-markdown-plugin-host-unmount', {
439
- bubbles: true,
440
- composed: true,
441
- detail: { slotName },
442
- }));
449
+ // Ask any delegating chat container to drop its hosts too. The loop above
450
+ // already detached every relocated node — `slotHosts` holds the reference
451
+ // wherever the node ended up — so this retires forwarders and announces.
452
+ for (const slotName of this.delegatedPluginSlots.keys()) {
453
+ this.retireDelegatedSlot(slotName);
443
454
  }
444
- this.delegatedPluginSlots.clear();
445
455
  this.latestRendererDescriptors = [];
446
456
  }
447
457
  adoptLightDomMarkdown() {
@@ -586,6 +596,40 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
586
596
  super.updated(changed);
587
597
  this.reconcileCustomRendererHosts();
588
598
  }
599
+ /**
600
+ * Drops a claim: retires the forwarder minted for it, if any, then tells the
601
+ * container to let go.
602
+ *
603
+ * The forwarder goes first. An assigned node suppresses the shadow slot's
604
+ * fallback content for as long as it exists, so a surviving forwarder turns
605
+ * a removed host into a blank region instead of the default rendering.
606
+ * @internal
607
+ */
608
+ /**
609
+ * Records a claim and mints the innermost hop back to the host the listener
610
+ * just relocated. Called in the same pass that read the claim because the
611
+ * mount event fires once per host and is never replayed — minting here is
612
+ * what makes a claim without its forwarder unrepresentable.
613
+ * @internal
614
+ */
615
+ adoptDelegatedSlot(slotName) {
616
+ this.delegatedPluginSlots.add(slotName);
617
+ const forwarder = document.createElement('slot');
618
+ forwarder.setAttribute('name', slotName);
619
+ forwarder.setAttribute('slot', slotName);
620
+ this.rendererForwarders.set(slotName, forwarder);
621
+ this.appendChild(forwarder);
622
+ }
623
+ retireDelegatedSlot(slotName) {
624
+ this.rendererForwarders.get(slotName)?.remove();
625
+ this.rendererForwarders.delete(slotName);
626
+ this.delegatedPluginSlots.delete(slotName);
627
+ this.dispatchEvent(new CustomEvent('cds-aichat-markdown-plugin-host-unmount', {
628
+ bubbles: true,
629
+ composed: true,
630
+ detail: { slotName },
631
+ }));
632
+ }
589
633
  /**
590
634
  * Invoke the consumer's `customRenderers` callbacks once per descriptor and
591
635
  * adopt their returned `HTMLElement` as a `<span slot="…">` (for inline
@@ -615,6 +659,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
615
659
  composed: true,
616
660
  cancelable: true,
617
661
  detail: {
662
+ kind: 'pluginFallback',
618
663
  slotName: descriptor.slotName,
619
664
  html: descriptor.html,
620
665
  isInline: descriptor.isInline,
@@ -622,7 +667,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
622
667
  });
623
668
  this.dispatchEvent(mountEvent);
624
669
  if (mountEvent.defaultPrevented) {
625
- this.delegatedPluginSlots.add(descriptor.slotName);
670
+ this.adoptDelegatedSlot(descriptor.slotName);
626
671
  }
627
672
  }
628
673
  else if (alreadyDelegated) {
@@ -694,13 +739,15 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
694
739
  // element's own light DOM sits inside the chat's shadow root, where it
695
740
  // cannot. Mirrors the plugin-fallback path above, but forwards the live
696
741
  // host element instead of an HTML string; the markdown element keeps
697
- // ownership of the host's content across renders. If no ancestor takes
698
- // over (standalone usage, e.g. storybook), host it locally.
742
+ // ownership of the host's content across renders, and mints the slot
743
+ // hop back to it below. If no ancestor takes over (standalone usage,
744
+ // e.g. storybook), host it locally.
699
745
  const mountEvent = new CustomEvent('cds-aichat-markdown-plugin-host-mount', {
700
746
  bubbles: true,
701
747
  composed: true,
702
748
  cancelable: true,
703
749
  detail: {
750
+ kind: 'customRenderer',
704
751
  slotName: descriptor.slotName,
705
752
  element: host,
706
753
  isInline: false,
@@ -708,7 +755,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
708
755
  });
709
756
  this.dispatchEvent(mountEvent);
710
757
  if (mountEvent.defaultPrevented) {
711
- this.delegatedPluginSlots.add(descriptor.slotName);
758
+ this.adoptDelegatedSlot(descriptor.slotName);
712
759
  }
713
760
  else {
714
761
  this.appendChild(host);
@@ -724,16 +771,12 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
724
771
  this.slotHosts.delete(slotName);
725
772
  }
726
773
  }
727
- // Tell any delegating chat container to drop hosts whose descriptor
728
- // disappeared (e.g. a streaming chunk removed a math node).
729
- for (const slotName of this.delegatedPluginSlots) {
774
+ // Drop claims whose descriptor disappeared (a streaming chunk removed a
775
+ // math node, a `customRenderers` callback returned null): the host was
776
+ // already detached above, so this retires the hop and announces.
777
+ for (const slotName of this.delegatedPluginSlots.keys()) {
730
778
  if (!wanted.has(slotName)) {
731
- this.dispatchEvent(new CustomEvent('cds-aichat-markdown-plugin-host-unmount', {
732
- bubbles: true,
733
- composed: true,
734
- detail: { slotName },
735
- }));
736
- this.delegatedPluginSlots.delete(slotName);
779
+ this.retireDelegatedSlot(slotName);
737
780
  }
738
781
  }
739
782
  }