@ai-react-markdown/core 1.4.2 → 1.4.3
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.
- package/README.md +110 -0
- package/dist/index.cjs +438 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +201 -2
- package/dist/index.d.ts +201 -2
- package/dist/index.js +426 -93
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx","../src/context.tsx","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/eq.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assocIndexOf.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_ListCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_freeGlobal.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_root.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Symbol.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getRawTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_objectToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseGetTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isFunction.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_coreJsData.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isMasked.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_toSource.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsNative.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getNative.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Map.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeCreate.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Hash.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isKeyable.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getMapData.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_MapCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Stack.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_defineProperty.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseAssignValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assignMergeValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_createBaseFor.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseFor.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Uint8Array.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneArrayBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copyArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseCreate.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_overArg.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getPrototype.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isPrototype.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_initCloneObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isObjectLike.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsArguments.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArguments.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isLength.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArrayLike.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArrayLikeObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/stubFalse.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isPlainObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseUnary.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nodeUtil.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_safeGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assignValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copyObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseTimes.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isIndex.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayLikeKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeKeysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseKeysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/keysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/toPlainObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseMergeDeep.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseMerge.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/identity.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_apply.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_overRest.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/constant.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseSetToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_shortOut.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseRest.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isIterateeCall.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_createAssigner.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/mergeWith.js","../src/defs.ts","../src/components/shortenDocumentId.ts","../src/preprocessors/latex.ts","../src/preprocessors/index.ts","../src/components/MarkdownContent.tsx","../src/components/markdown/Markdown.tsx","../src/components/markdown/processor.ts","../src/components/markdown/transform.ts","../src/components/markdown/urlTransform.ts","../src/components/sanitizeSchema.ts","../src/components/rehypeRebaseHashLinks.ts","../src/components/rehypeFooterAdorn.ts","../src/components/blockMemo.ts","../src/components/normalizeId.ts","../src/components/collectDefLabels.ts","../src/components/AIMarkdownDocuments.tsx","../src/components/documentRegistry.ts","../src/components/remarkInjectPhantomDefs.ts","../src/components/customMdastHandlers.ts","../src/components/crossChunkPlaceholders.tsx","../src/components/chunkSymbolContext.ts","../src/components/extractContributions.ts","../src/components/extractDefBodiesFromHast.ts","../src/components/aggregateFootnotesIfLast.tsx","../src/hooks/useStableValue.ts","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setCacheAdd.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_SetCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arraySome.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalArrays.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapToArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setToArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalByTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayPush.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseGetAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayFilter.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/stubArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getSymbols.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/keys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalObjects.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_DataView.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Promise.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Set.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_WeakMap.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsEqualDeep.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsEqual.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isEqual.js","../src/components/typography/Default.tsx"],"sourcesContent":["/**\n * @ai-react-markdown/core\n *\n * A batteries-included React component for rendering AI-generated markdown\n * with first-class support for LaTeX math, GFM, CJK text, syntax highlighting,\n * and streaming content.\n *\n * ## Quick Start\n *\n * ```tsx\n * import AIMarkdown from '@ai-react-markdown/core';\n * import '@ai-react-markdown/core/typography/default.css';\n *\n * function App() {\n * return <AIMarkdown content=\"Hello **world**!\" />;\n * }\n * ```\n *\n * @module @ai-react-markdown/core\n */\n\n'use client';\n\nimport { useMemo, memo, useId, type CSSProperties } from 'react';\nimport AIMarkdownRenderStateProvider, {\n AIMarkdownMetadataProvider,\n AIMarkdownRenderStateProviderProps,\n AIMarkdownMetadataProviderProps,\n} from './context';\nimport { AIMDContentPreprocessor } from './preprocessors/defs';\nimport preprocessAIMDContent from './preprocessors';\nimport AIMarkdownContent from './components/MarkdownContent';\nimport {\n AIMarkdownCustomComponents,\n AIMarkdownRenderConfig,\n AIMarkdownMetadata,\n AIMarkdownTypographyComponent,\n AIMarkdownExtraStylesComponent,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n} from './defs';\nimport useStableValue from './hooks/useStableValue';\nimport DefaultTypography from './components/typography/Default';\n\n/**\n * Props for the `<AIMarkdown>` component.\n *\n * @typeParam TConfig - Custom render configuration type (extends {@link AIMarkdownRenderConfig}).\n * @typeParam TRenderData - Custom metadata type (extends {@link AIMarkdownMetadata}).\n */\nexport interface AIMarkdownProps<\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n TRenderData extends AIMarkdownMetadata = AIMarkdownMetadata,\n>\n extends\n Omit<AIMarkdownRenderStateProviderProps<TConfig>, 'streaming' | 'fontSize' | 'variant' | 'colorScheme'>,\n AIMarkdownMetadataProviderProps<TRenderData> {\n /**\n * Whether content is actively being streamed (e.g. token-by-token from an LLM).\n * When `true`, the flag is propagated via context so custom components can adapt\n * their behavior (show cursors, disable copy buttons, skip animations, etc.).\n * Defaults to `false`.\n */\n streaming?: boolean;\n /**\n * Base font size for the rendered output.\n * Accepts a CSS length string (e.g. `'14px'`, `'0.875rem'`) or a number\n * which is treated as pixels. Defaults to `'0.9375rem'`.\n */\n fontSize?: number | string;\n /** Raw markdown content to render. */\n content: string;\n /**\n * Additional preprocessors to run on the raw markdown before rendering.\n * These run *after* the built-in LaTeX preprocessor.\n */\n contentPreprocessors?: AIMDContentPreprocessor[];\n /**\n * Custom `react-markdown` component overrides.\n * Use this to replace the default renderers for specific HTML elements\n * (e.g. code blocks, links, images).\n */\n customComponents?: AIMarkdownCustomComponents;\n /**\n * Typography wrapper component. Receives `fontSize`, `variant`, and `colorScheme`.\n * Defaults to the built-in {@link DefaultTypography}.\n */\n Typography?: AIMarkdownTypographyComponent;\n /**\n * Optional extra style wrapper component rendered between the typography\n * wrapper and the markdown content. Useful for injecting additional\n * CSS scope or theme providers.\n */\n ExtraStyles?: AIMarkdownExtraStylesComponent;\n /** Typography variant name. Defaults to `'default'`. */\n variant?: AIMarkdownVariant;\n /** Color scheme name. Defaults to `'light'`. */\n colorScheme?: AIMarkdownColorScheme;\n /**\n * Stable identifier for the *logical markdown document* this `<AIMarkdown>`\n * is rendering. Used as the id namespace for all clobberable attributes\n * (`id`, hash hrefs) so two documents on the same page do not cross-link —\n * e.g. clicking a footnote `[^1]` in message A will not scroll to the\n * `[^1]` definition in message B.\n *\n * Why `documentId` and not `instanceId`: when one logical document is\n * split across multiple `<AIMarkdown>` instances (chunked / streamed\n * rendering), every chunk should share the SAME `documentId` so their\n * id-prefixes line up. The id is per-document, not per-React-instance.\n *\n * When omitted, an id is auto-generated via React's `useId()` (SSR-safe\n * and stable across re-renders). Pass an explicit value when you need\n * deterministic ids (snapshot tests, cross-component deep links) or when\n * multiple instances render the same logical document.\n *\n * Consumer-supplied values pass through `encodeURIComponent` at the prefix\n * construction site, so any string is safe — including ids with reserved\n * characters like `:`, `/`, or spaces.\n */\n documentId?: string;\n}\n\n/**\n * Root component that preprocesses markdown content and renders it through\n * a configurable remark/rehype pipeline wrapped in typography and style layers.\n */\nconst AIMarkdownComponent = <\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n TRenderData extends AIMarkdownMetadata = AIMarkdownMetadata,\n>({\n streaming = false,\n content,\n fontSize,\n contentPreprocessors,\n customComponents,\n defaultConfig,\n config,\n metadata,\n Typography = DefaultTypography,\n ExtraStyles,\n variant = 'default',\n colorScheme = 'light',\n documentId,\n}: AIMarkdownProps<TConfig, TRenderData>) => {\n // Normalize fontSize: number -> px string, undefined -> default rem value.\n // Branch on `undefined` (not truthiness) so `fontSize={0}` resolves to `'0px'`.\n const usedFontSize = fontSize === undefined ? '0.9375rem' : typeof fontSize === 'number' ? `${fontSize}px` : fontSize;\n\n // Auto-generate a stable id when the consumer didn't supply one. We hand\n // back React's native `useId()` value verbatim — any URI/HTML-attribute\n // safety transformation happens downstream at the prefix construction site\n // (see `MarkdownContent.tsx`), so the value exposed via context retains its\n // React identity (useful for debugging and DevTools association).\n const generatedId = useId();\n const usedDocumentId = documentId && documentId.length > 0 ? documentId : generatedId;\n\n // Stabilize object/array props to prevent unnecessary re-renders\n // when the consumer creates new references on each render.\n //\n // `metadata` is INTENTIONALLY excluded — its shape is opaque to the library\n // and may be arbitrarily large (e.g. full chat session, document tree). A\n // blanket lodash isEqual deep-compare here would penalize every render with\n // an unbounded scan. Stabilizing metadata is the consumer's responsibility:\n // if their custom renderers do reference-equal work on it, they should\n // useMemo their metadata at the call site.\n const stableDefaultConfig = useStableValue(defaultConfig);\n const stableConfig = useStableValue(config);\n const stablePreprocessors = useStableValue(contentPreprocessors);\n const stableCustomComponents = useStableValue(customComponents);\n\n // Run the preprocessing pipeline (LaTeX normalization + user preprocessors).\n const usedContent = useMemo(\n () => (content ? preprocessAIMDContent(content, stablePreprocessors) : content),\n [content, stablePreprocessors]\n );\n\n // Stabilize the inline style passed to Typography; otherwise its memo wrapper\n // breaks on every parent render even when the font-size hasn't changed.\n const typographyStyle = useMemo(() => ({ '--aim-font-size-root': usedFontSize }) as CSSProperties, [usedFontSize]);\n\n return (\n <AIMarkdownMetadataProvider<TRenderData> metadata={metadata}>\n <AIMarkdownRenderStateProvider<TConfig>\n streaming={streaming}\n fontSize={usedFontSize}\n variant={variant}\n colorScheme={colorScheme}\n documentId={usedDocumentId}\n defaultConfig={stableDefaultConfig}\n config={stableConfig}\n >\n <Typography\n fontSize={usedFontSize}\n variant={variant}\n colorScheme={colorScheme}\n // Inject CSS custom properties onto the Typography root element.\n // --aim-font-size-root: absolute font-size anchor so inner CSS can\n // bypass em-compounding in deeply nested markdown structures.\n // See AIMarkdownTypographyProps.style JSDoc for the full variable list.\n style={typographyStyle}\n >\n {ExtraStyles ? (\n <ExtraStyles>\n <AIMarkdownContent content={usedContent} customComponents={stableCustomComponents} />\n </ExtraStyles>\n ) : (\n <AIMarkdownContent content={usedContent} customComponents={stableCustomComponents} />\n )}\n </Typography>\n </AIMarkdownRenderStateProvider>\n </AIMarkdownMetadataProvider>\n );\n};\n\n/**\n * A React component for rendering AI-generated markdown with rich formatting support.\n *\n * Features:\n * - GFM (tables, strikethrough, task lists, autolinks)\n * - LaTeX math rendering via KaTeX\n * - Emoji shortcodes\n * - CJK-friendly line breaking and spacing\n * - Configurable syntax extensions (highlight, definition lists, super/subscript)\n * - Configurable display optimizations (SmartyPants, pangu, comment removal)\n * - Streaming-aware rendering\n * - Customizable typography, color scheme, and component overrides\n *\n * @example\n * ```tsx\n * <AIMarkdown\n * content={markdownString}\n * streaming={isStreaming}\n * colorScheme=\"dark\"\n * config={{ extraSyntaxSupported: [AIMarkdownRenderExtraSyntax.HIGHLIGHT] }}\n * />\n * ```\n */\nconst AIMarkdown = memo(AIMarkdownComponent);\nAIMarkdown.displayName = 'AIMarkdown';\n\nexport default AIMarkdown as typeof AIMarkdownComponent;\n\n// ── Public API re-exports ───────────────────────────────────────────────────\n\n// Types\nexport type { AIMDContentPreprocessor };\nexport type {\n AIMarkdownCustomComponents,\n AIMarkdownRenderConfig,\n AIMarkdownRenderState,\n AIMarkdownMetadata,\n AIMarkdownTypographyProps,\n AIMarkdownTypographyComponent,\n AIMarkdownExtraStylesProps,\n AIMarkdownExtraStylesComponent,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n} from './defs';\n\n// Enums & Constants\nexport {\n AIMarkdownRenderExtraSyntax,\n AIMarkdownRenderDisplayOptimizeAbility,\n defaultAIMarkdownRenderConfig,\n} from './defs';\n\n// Hooks -- for custom components to access render state & metadata\nexport { useAIMarkdownRenderState, useAIMarkdownMetadata } from './context';\nexport { useStableValue };\n\n// Cross-chunk coordination wrapper + hook\nexport { AIMarkdownDocuments, useDocumentRegistry } from './components/AIMarkdownDocuments';\nexport type { AIMarkdownDocumentsProps } from './components/AIMarkdownDocuments';\n// Registry types — consumers writing typed helpers around useDocumentRegistry\n// (`function helper(r: Registry)`) need these. The Registry shape itself is a\n// public contract: we maintain backwards compat across minor versions.\nexport type { Registry, ChunkData, FootnoteDef, LinkDef, RefRecord, RefKind } from './components/documentRegistry';\n\n// Utils\nexport type { PartialDeep } from './typings/partial-deep';\n","/**\n * React context for the AIMarkdown render state.\n *\n * Provides an immutable {@link AIMarkdownRenderState} object to all descendant\n * components. The provider deep-merges user-supplied partial configuration with\n * the built-in defaults so that consumers always receive a complete config.\n *\n * @module context\n */\n\nimport { PropsWithChildren, createContext, useContext, useId, useMemo } from 'react';\nimport mergeWith from 'lodash-es/mergeWith';\nimport {\n AIMarkdownRenderConfig,\n AIMarkdownMetadata,\n AIMarkdownRenderState,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n defaultAIMarkdownRenderConfig,\n} from './defs';\nimport { shortenDocumentId } from './components/shortenDocumentId';\nimport type { PartialDeep } from './typings/partial-deep';\n\nconst AIMarkdownRenderStateContext = createContext<AIMarkdownRenderState<AIMarkdownRenderConfig> | null>(null);\n\nconst AIMarkdownMetadataContext = createContext<AIMarkdownMetadata | undefined>(undefined);\n\n/**\n * Access the current {@link AIMarkdownRenderState} from within the `<AIMarkdown>` tree.\n *\n * Must be called inside a component rendered as a descendant of `<AIMarkdown>`.\n * Throws if called outside the provider boundary.\n *\n * ### `TConfig` is a caller-asserted type, not a derived one\n *\n * The generic parameter is **an assertion the caller makes about the provider\n * above it** — TypeScript cannot verify that the actual `<AIMarkdown>` in the\n * tree was configured with a matching `defaultConfig: TConfig`. If you pass a\n * wider `TConfig` than what the provider actually carries, field access at\n * compile time will look fine but resolve to `undefined` at runtime.\n *\n * The intended pattern is that extension packages (e.g. `@ai-react-markdown/mantine`)\n * ship their own narrow wrapper hook alongside a matching `defaultConfig`, so the\n * assertion is made *once* next to the provider configuration and consumers of the\n * wrapper never touch the raw generic.\n *\n * @typeParam TConfig - Caller-asserted configuration shape (defaults to\n * {@link AIMarkdownRenderConfig}). Must be aligned with the provider's\n * `defaultConfig` — the library does not check this at runtime.\n * @returns The current render state (does not include metadata — use\n * {@link useAIMarkdownMetadata} for that).\n * @throws If called outside an `<AIMarkdown>` provider tree.\n *\n * @example Base usage — no generic, always safe:\n * ```tsx\n * function CustomCodeBlock({ children }: PropsWithChildren) {\n * const { streaming, config } = useAIMarkdownRenderState();\n * // config: AIMarkdownRenderConfig — guaranteed shape\n * }\n * ```\n *\n * @example Wrapper-hook pattern — the intended way to use an extended TConfig:\n * ```tsx\n * // In your extension package (pin the assertion in one place):\n * interface ExtendedConfig extends AIMarkdownRenderConfig {\n * themeMode: 'light' | 'dark' | 'auto';\n * }\n * export const extendedDefaultConfig: ExtendedConfig = {\n * ...defaultAIMarkdownRenderConfig,\n * themeMode: 'auto',\n * };\n * export const useExtendedRenderState = () =>\n * useAIMarkdownRenderState<ExtendedConfig>();\n *\n * // Provider is always configured with the matching defaultConfig:\n * <AIMarkdown defaultConfig={extendedDefaultConfig} ...>{children}</AIMarkdown>\n *\n * // Consumers use the narrow wrapper — no raw generic anywhere:\n * const { config } = useExtendedRenderState();\n * config.themeMode; // correctly typed and present at runtime\n * ```\n *\n * @see `@ai-react-markdown/mantine` — real-world reference. Its\n * `MantineAIMarkdownRenderConfig`, `defaultMantineAIMarkdownRenderConfig`,\n * `<MantineAIMarkdown>` (which passes `defaultConfig` by default), and\n * `useMantineAIMarkdownRenderState` implement this exact pattern.\n */\nexport function useAIMarkdownRenderState<TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig>() {\n // `as` is intentional: TConfig is a caller assertion (see JSDoc). The\n // alignment with the provider's `defaultConfig` is the caller's contract.\n const context = useContext(AIMarkdownRenderStateContext) as AIMarkdownRenderState<TConfig> | null;\n\n if (!context) {\n throw new Error('useAIMarkdownRenderState must be used within an <AIMarkdown /> component.');\n }\n\n return context;\n}\n\n/**\n * Access the current metadata from within the `<AIMarkdown>` tree.\n *\n * Metadata lives in a separate React context so that changes to metadata\n * do not cause re-renders in components that only consume render state\n * (e.g. {@link MarkdownContent}).\n *\n * ### `TMetadata` is a caller-asserted type\n *\n * Same contract as {@link useAIMarkdownRenderState} — the generic is an\n * assertion about the `metadata` prop passed to the provider above, not a\n * value TypeScript can derive. Unlike render-state config, metadata has no\n * runtime fallback: if the provider received no `metadata`, the hook returns\n * `undefined` regardless of the asserted type. Prefer wrapping this hook in\n * a project-local hook that pins `TMetadata` next to the call site that\n * actually provides the metadata.\n *\n * @typeParam TMetadata - Caller-asserted metadata shape (defaults to\n * {@link AIMarkdownMetadata}). Caller is responsible for ensuring the\n * provider's `metadata` prop matches this shape.\n * @returns The current metadata, or `undefined` if none was provided.\n *\n * @see `@ai-react-markdown/mantine` — `useMantineAIMarkdownMetadata` applies\n * the wrapper pattern to this hook, pinning `MantineAIMarkdownMetadata` in\n * a single location.\n */\nexport function useAIMarkdownMetadata<TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata>() {\n // `as` is intentional: TMetadata is a caller assertion (see JSDoc).\n return useContext(AIMarkdownMetadataContext) as TMetadata | undefined;\n}\n\n/** Props for {@link AIMarkdownRenderStateProvider}. */\nexport interface AIMarkdownRenderStateProviderProps<\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n> extends PropsWithChildren {\n streaming: boolean;\n fontSize: string;\n variant: AIMarkdownVariant;\n colorScheme: AIMarkdownColorScheme;\n /**\n * Logical-document identifier used as the id namespace for clobberable\n * attributes (id / hash hrefs). Optional — when omitted, the provider\n * auto-generates one via {@link useId} so the provider stays drop-in\n * usable for direct consumers (e.g. extension packages that don't go\n * through `<AIMarkdown>`).\n *\n * Pass the SAME value to multiple providers / `<AIMarkdown>` instances\n * when they render chunks of the same logical document — their id\n * prefixes will align so cross-chunk anchors and (once the parser sees\n * the full doc) footnote navigation work.\n */\n documentId?: string;\n /**\n * Base default config to merge against. When omitted, falls back to\n * {@link defaultAIMarkdownRenderConfig}. Sub-packages (e.g. mantine) can\n * pass their own extended defaults here.\n */\n defaultConfig?: TConfig;\n /** Partial config that will be deep-merged with the default config. */\n config?: PartialDeep<TConfig>;\n}\n\n/** Props for {@link AIMarkdownMetadataProvider}. */\nexport interface AIMarkdownMetadataProviderProps<\n TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata,\n> extends PropsWithChildren {\n metadata?: TMetadata;\n}\n\n/**\n * Custom lodash `mergeWith` handler: arrays from the source (user config)\n * fully replace the target (default config) instead of being merged by index.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst configMergeCustomizer = (\n _objValue: any,\n srcValue: any,\n _key: string,\n _object: any,\n _source: any,\n _stack: any\n) => {\n if (Array.isArray(srcValue)) {\n return srcValue;\n }\n};\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * Provider that exposes consumer-provided metadata via a dedicated React context.\n * Separated from render state so that metadata changes do not trigger\n * re-renders in components that only consume render state.\n */\nexport const AIMarkdownMetadataProvider = <RDT extends AIMarkdownMetadata = AIMarkdownMetadata>({\n metadata,\n children,\n}: AIMarkdownMetadataProviderProps<RDT>) => {\n return <AIMarkdownMetadataContext.Provider value={metadata}>{children}</AIMarkdownMetadataContext.Provider>;\n};\n\n/**\n * Internal provider that deep-merges user config with defaults and exposes\n * the resulting {@link AIMarkdownRenderState} to the component tree.\n */\nconst AIMarkdownRenderStateProvider = <RCT extends AIMarkdownRenderConfig = AIMarkdownRenderConfig>({\n streaming,\n fontSize,\n variant,\n colorScheme,\n documentId,\n defaultConfig,\n config,\n children,\n}: AIMarkdownRenderStateProviderProps<RCT>) => {\n // Deep-merge user config with defaults into a fresh `{}` so the frozen\n // default is never mutated — avoids the extra cloneDeep pass.\n const baseConfig = defaultConfig ?? defaultAIMarkdownRenderConfig;\n const mergedConfig = useMemo(\n () => (config ? (mergeWith({}, baseConfig, config, configMergeCustomizer) as RCT) : baseConfig),\n [baseConfig, config]\n );\n\n // Fallback id when the caller did not supply one. `useId()` is SSR-safe\n // and stable per component instance. We expose its raw value; HTML/URI\n // safety is applied at the `clobberPrefix` derivation below.\n const fallbackId = useId();\n const resolvedDocumentId = documentId && documentId.length > 0 ? documentId : fallbackId;\n\n // Freeze the state object to enforce immutability downstream.\n const state = useMemo(\n () =>\n Object.freeze({\n streaming,\n fontSize,\n variant,\n colorScheme,\n documentId: resolvedDocumentId,\n // URI-fragment safe per-document prefix derived once here so downstream\n // consumers (MarkdownContent, cross-chunk placeholder components) read\n // from one canonical source. `encodeURIComponent` runs at the prefix\n // construction site, not at the documentId storage site, so consumers\n // accessing `documentId` directly still see the raw React-native value\n // (e.g. `useId()`'s `_r_0_`) while id=\"...\"/href=\"#...\" bytes are safe.\n //\n // `shortenDocumentId` is applied here (NOT at the documentId storage\n // site) for the same reason: consumer-supplied UUIDs and nanoids\n // shouldn't bloat every rendered `id=\"…\"`. Registry keying — which\n // reads `state.documentId` directly — stays on the raw value, so the\n // shortening is a pure HTML-output concern and the `useDocumentRegistry`\n // API surface is unaffected. Pure function ⇒ all chunks sharing one\n // logical documentId still produce identical prefixes.\n clobberPrefix: `${encodeURIComponent(shortenDocumentId(resolvedDocumentId))}-user-content-`,\n config: mergedConfig,\n }),\n [streaming, fontSize, variant, colorScheme, resolvedDocumentId, mergedConfig]\n );\n\n return <AIMarkdownRenderStateContext.Provider value={state}>{children}</AIMarkdownRenderStateContext.Provider>;\n};\n\nexport default AIMarkdownRenderStateProvider;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n","import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n","import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n","import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignMergeValue;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n","import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n","import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n","import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n","import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n","import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n","import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nexport default baseMergeDeep;\n","import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nexport default baseMerge;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n","import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n","import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n","import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n","import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\n\n/**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\nvar mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n});\n\nexport default mergeWith;\n","/**\n * Core type definitions, enums, and default configuration for ai-react-markdown.\n *\n * This module defines the public API surface for configuring the renderer,\n * including extra markdown syntax extensions, display optimization abilities,\n * typography theming, and the shared render state shape.\n *\n * @module defs\n */\n\nimport { ComponentType, CSSProperties, PropsWithChildren } from 'react';\nimport type { Components } from './components/markdown';\n\n/**\n * Custom component overrides for the markdown renderer.\n * Alias for the local Markdown wrapper's `Components` type (a vendored fork of\n * react-markdown's), re-exported under the library's `AIMarkdown` naming\n * convention so consumers don't need a direct `react-markdown` dependency\n * for type imports.\n */\nexport type AIMarkdownCustomComponents = Components;\n\n/**\n * Extra markdown syntax extensions beyond standard GFM.\n * Enable or disable these via {@link AIMarkdownRenderConfig.extraSyntaxSupported}.\n */\nexport enum AIMarkdownRenderExtraSyntax {\n /** `==Highlight==` syntax support. */\n HIGHLIGHT = 'HIGHLIGHT',\n /** Definition list syntax. @see https://michelf.ca/projects/php-markdown/extra/#def-list */\n DEFINITION_LIST = 'DEFINITION_LIST',\n}\n\n/**\n * Display optimization abilities applied during markdown processing.\n * Enable or disable these via {@link AIMarkdownRenderConfig.displayOptimizeAbilities}.\n */\nexport enum AIMarkdownRenderDisplayOptimizeAbility {\n /** Strip HTML comments from the content. */\n REMOVE_COMMENTS = 'REMOVE_COMMENTS',\n /** Typographic enhancements via SmartyPants (curly quotes, em-dashes, etc.). @see https://www.npmjs.com/package/smartypants */\n SMARTYPANTS = 'SMARTYPANTS',\n /** Automatically insert spaces between CJK and half-width characters. */\n PANGU = 'PANGU',\n}\n\n/**\n * Configuration object controlling which markdown extensions and\n * display optimizations are active during rendering.\n *\n * Arrays are typed `readonly` so the interface is assignable from the frozen\n * {@link defaultAIMarkdownRenderConfig}. Consumers can still pass mutable\n * arrays since `readonly T[]` is assignable from `T[]`. Note: this is a\n * compile-time hint only — user-supplied configs are not deep-frozen at\n * runtime, so the library does not guarantee the object remains unchanged\n * after it is passed in.\n */\nexport interface AIMarkdownRenderConfig {\n /** Extra syntax extensions to enable. */\n readonly extraSyntaxSupported: readonly AIMarkdownRenderExtraSyntax[];\n /** Display optimization abilities to enable. */\n readonly displayOptimizeAbilities: readonly AIMarkdownRenderDisplayOptimizeAbility[];\n /**\n * Whether to enable block-level memoization across renders.\n *\n * When `true` (default), the renderer splits each rendered document into\n * per-block units and memoizes the React subtree of each block by its\n * source identity (`raw + occurrence + ctx + position`). Unchanged blocks\n * during streaming skip `toJsxRuntime` and React reconcile work, reducing\n * per-frame cost roughly proportional to the unchanged fraction of the\n * document. Output is byte-identical to the disabled path.\n *\n * When `false`, the renderer falls back to the legacy bare `<Markdown>`\n * flow — every render runs the full pipeline end-to-end with no\n * cross-frame reuse. Useful for debugging, for environments where the\n * extra `useRef`-backed cache is undesirable, or as an escape hatch if a\n * future custom rehype plugin interacts badly with the plan abstraction.\n *\n * @default true\n */\n readonly blockMemoEnabled: boolean;\n /**\n * Default `true`. Controls Direction A: whether `<AIMarkdown>` (standalone\n * mode) protects orphan `footnoteDefinition` nodes from being silently\n * dropped by `mdast-util-to-hast` when no corresponding `footnoteReference`\n * exists. Implemented via a custom `footnoteDefinition` handler that\n * proactively registers the label in `state.footnoteOrder`.\n *\n * When `<AIMarkdown>` is wrapped in `<AIMarkdownDocuments>`, this field\n * is ignored — the wrapper's `preserveOrphanReferences` prop overrides\n * unconditionally for all chunks under it.\n */\n readonly preserveOrphanReferences: boolean;\n}\n\n/**\n * Sensible default configuration with all extensions and optimizations enabled.\n * Frozen at both the top level and the inner arrays so this shared singleton\n * cannot be mutated by any consumer.\n */\nexport const defaultAIMarkdownRenderConfig = Object.freeze({\n extraSyntaxSupported: Object.freeze([\n AIMarkdownRenderExtraSyntax.HIGHLIGHT,\n AIMarkdownRenderExtraSyntax.DEFINITION_LIST,\n ]),\n displayOptimizeAbilities: Object.freeze([\n AIMarkdownRenderDisplayOptimizeAbility.REMOVE_COMMENTS,\n AIMarkdownRenderDisplayOptimizeAbility.SMARTYPANTS,\n AIMarkdownRenderDisplayOptimizeAbility.PANGU,\n ]),\n blockMemoEnabled: true,\n preserveOrphanReferences: true,\n}) satisfies AIMarkdownRenderConfig;\n\n/**\n * Arbitrary metadata that consumers can pass through a dedicated React context.\n * Custom renderers can access this via the {@link useAIMarkdownMetadata} hook.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AIMarkdownMetadata extends Record<string, any> {}\n\n/**\n * Typography variant identifier. Built-in variant is `'default'`;\n * consumers may define additional variants via custom typography components.\n */\nexport type AIMarkdownVariant = 'default' | (string & {});\n\n/**\n * Color scheme identifier. Built-in schemes are `'light'` and `'dark'`;\n * consumers may define additional schemes via custom typography CSS.\n */\nexport type AIMarkdownColorScheme = 'light' | 'dark' | (string & {});\n\n/** Props accepted by a typography wrapper component. */\nexport interface AIMarkdownTypographyProps extends PropsWithChildren {\n /** Resolved CSS font-size value (e.g. `'14px'`, `'0.875rem'`). */\n fontSize: string;\n /** Active typography variant. */\n variant?: AIMarkdownVariant;\n /** Active color scheme. */\n colorScheme?: AIMarkdownColorScheme;\n /**\n * Inline styles injected by the core renderer. Custom Typography implementations\n * **must** merge this object into their root element's `style` to ensure CSS\n * custom properties set by the core are available to all descendant nodes.\n *\n * ### Currently injected variables\n *\n * | Variable | Value | Purpose |\n * |-------------------------|----------------|----------------------------------------------------------|\n * | `--aim-font-size-root` | `fontSize` prop | Absolute font-size anchor for the component instance. |\n *\n * #### Why `--aim-font-size-root`?\n *\n * Markdown content frequently nests elements that use relative `em` units\n * (blockquotes, lists, code blocks). Each nesting level compounds the\n * effective size — a `0.875em` code span inside a `1.125em` blockquote\n * becomes `0.984375em` of the parent, not `0.875em` of the root.\n *\n * `--aim-font-size-root` provides the component-level root font-size as an\n * absolute reference so that inner CSS rules can use\n * `font-size: var(--aim-font-size-root)` to opt out of `em` compounding\n * when a stable size is needed.\n *\n * @example\n * ```tsx\n * const MyTypography: AIMarkdownTypographyComponent = ({ children, fontSize, style }) => (\n * <div className=\"my-typo\" style={{ fontSize, ...style }}>\n * {children}\n * </div>\n * );\n * ```\n */\n style?: CSSProperties;\n}\n\n/** React component type for the typography wrapper. */\nexport type AIMarkdownTypographyComponent = ComponentType<AIMarkdownTypographyProps>;\n\n/** Props accepted by an optional extra style wrapper component. */\nexport interface AIMarkdownExtraStylesProps extends PropsWithChildren {}\n\n/** React component type for an optional extra style wrapper. */\nexport type AIMarkdownExtraStylesComponent = ComponentType<AIMarkdownExtraStylesProps>;\n\n/**\n * Immutable render state exposed to all descendant components via React context.\n * Access this with the {@link useAIMarkdownRenderState} hook.\n *\n * Metadata is provided via a separate context — use {@link useAIMarkdownMetadata} instead.\n *\n * @typeParam TConfig - Render configuration type (defaults to {@link AIMarkdownRenderConfig}).\n */\nexport interface AIMarkdownRenderState<TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig> {\n /** Whether the content is currently being streamed (e.g. from an LLM). */\n streaming: boolean;\n /** Resolved CSS font-size value. */\n fontSize: string;\n /** Active typography variant. */\n variant: AIMarkdownVariant;\n /** Active color scheme. */\n colorScheme: AIMarkdownColorScheme;\n /**\n * Stable identifier unique to this *logical markdown document*. Used as\n * the id namespace for clobberable attributes (`id`, hash hrefs) so two\n * documents on the same page don't cross-link — e.g. clicking a footnote\n * `[^1]` in message A won't scroll to the `[^1]` definition in message B.\n *\n * Named `documentId` (not `instanceId`) intentionally: when one logical\n * markdown document is split into multiple `<AIMarkdown>` instances\n * (chunked / streamed rendering), every chunk SHOULD share the same value\n * so id-prefixes align across the chunks.\n *\n * Auto-generated via React's `useId()` (SSR-safe, stable across\n * re-renders) when not provided by the consumer; consumer-supplied values\n * always win.\n */\n documentId: string;\n /**\n * Per-document URI-safe id prefix used by all clobberable attributes\n * (`id=\"…\"` / `href=\"#…\"`). Derived once by the provider and exposed here\n * so downstream consumers (placeholder components, cross-chunk anchor\n * logic) read a single canonical source instead of recomputing locally.\n *\n * Derivation is `${encodeURIComponent(shortenDocumentId(documentId))}-user-content-`:\n * `documentId` is first run through a MurmurHash3 → Base62 shortener\n * (no-op for ids ≤16 chars, ≤6-char hash otherwise) to keep the rendered\n * HTML compact when consumers pass long UUIDs/nanoids. The shortening\n * is purely a render-output concern — `state.documentId` itself is left\n * raw, and registry keying (`useDocumentRegistry`) reads that raw value.\n * Do not reconstruct this prefix from `documentId` at call sites; always\n * read it through this field.\n */\n clobberPrefix: string;\n /** Active render configuration. */\n config: TConfig;\n}\n","/**\n * Shorten long consumer-supplied `documentId` values down to a fixed-length\n * Base62 hash so they don't bloat every rendered `id=\"…\"` / `href=\"#…\"`.\n *\n * Trade-offs:\n * - Non-cryptographic hash (MurmurHash3 x86 32-bit) — pure speed, excellent\n * avalanche on the structured inputs we actually receive (UUIDs, nanoids,\n * `useId()` outputs, opaque chat-message ids). Collision domain is 2^32;\n * at ~77,000 active document ids the birthday-paradox collision rate hits\n * ~50%, which is far beyond any realistic single-page chat workload.\n * - Only kicks in past a length threshold (default 16) so short, hand-picked\n * ids stay readable and existing test fixtures (`'tst'`, `'doc-a'`, …)\n * plus `useId()`'s `'_r_0_'`-style output (≤7 chars) pass through untouched.\n * - Pure function: same input always yields the same output. Two chunks\n * sharing one logical `documentId` therefore still produce identical\n * prefixes, so cross-chunk anchor and footnote coordination is preserved.\n *\n * Why MurmurHash3 specifically (vs the simpler FNV-1a):\n * - FNV-1a does NOT pass SMHasher's avalanche test. For *structured* inputs\n * like UUIDs (fixed hyphen positions, hex-only alphabet) its lower bits\n * show measurable bias, which translates to a higher *practical* collision\n * rate than the theoretical 2^32 figure suggests.\n * - MurmurHash3's finalizer (`fmix32`) — `h ^= h>>>16; h = imul(h, M1);\n * h ^= h>>>13; h = imul(h, M2); h ^= h>>>16` — is purpose-built to\n * flatten any local pattern that survives the body, which is what gets\n * it through SMHasher. That's the entire engineering reason for the\n * ~30-line code-size delta vs FNV-1a.\n *\n * @module components/shortenDocumentId\n */\n\nconst BASE62_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n/** Encode a non-negative 32-bit integer as a Base62 string (no padding). */\nfunction toBase62(n: number): string {\n if (n === 0) return BASE62_ALPHABET[0];\n // Treat `n` as unsigned 32-bit so the sign bit doesn't make the loop spin.\n let v = n >>> 0;\n let out = '';\n while (v > 0) {\n out = BASE62_ALPHABET[v % 62] + out;\n v = Math.floor(v / 62);\n }\n return out;\n}\n\n/** 32-bit unsigned rotate-left, in pure JS. */\nfunction rotl32(x: number, r: number): number {\n return (((x << r) | (x >>> (32 - r))) >>> 0);\n}\n\n// MurmurHash3 x86 32-bit mixing constants — from Appleby's reference impl.\n// Naming follows the spec so the code reads against the paper verbatim.\nconst C1 = 0xcc9e2d51;\nconst C2 = 0x1b873593;\n\n// Single TextEncoder reused per process — instantiation is non-trivial and\n// the hash runs once per `<AIMarkdown>` provider commit. UTF-8 bytes (not\n// JS UTF-16 code units) are the canonical Murmur3 input so the hash stays\n// portable with reference implementations in other languages.\nconst UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();\n\n/**\n * MurmurHash3 x86 32-bit. Pure function over the UTF-8 byte sequence of `s`.\n *\n * Implementation notes:\n * - `Math.imul(a, b)` performs signed 32-bit integer multiplication with\n * proper overflow truncation. Plain `a * b` would promote to IEEE-754\n * double and silently lose precision past 2^53, breaking the hash.\n * - The body processes the input in 4-byte little-endian blocks; the\n * 1–3 byte tail is folded in with the canonical Murmur3 cascade.\n * - The finalize step (the three `imul` + `xor >>> n` lines below the\n * tail) is `fmix32` — the avalanche stage that distinguishes Murmur3\n * from naive multiply-xor hashes.\n *\n * @param s - Arbitrary input string (any Unicode).\n * @param seed - Optional 32-bit seed. Defaults to `0` for deterministic\n * reproducibility across machines.\n * @returns Unsigned 32-bit integer.\n */\nfunction murmur3_32(s: string, seed: number = 0): number {\n const bytes = UTF8_ENCODER.encode(s);\n const len = bytes.length;\n let h1 = seed >>> 0;\n const nblocks = len >>> 2;\n\n // ── Body: 4-byte little-endian blocks ───────────────────────────────────\n for (let i = 0; i < nblocks; i++) {\n const b = i * 4;\n let k1 =\n bytes[b] |\n (bytes[b + 1] << 8) |\n (bytes[b + 2] << 16) |\n (bytes[b + 3] << 24);\n\n k1 = Math.imul(k1, C1);\n k1 = rotl32(k1, 15);\n k1 = Math.imul(k1, C2);\n\n h1 ^= k1;\n h1 = rotl32(h1, 13);\n h1 = (Math.imul(h1, 5) + 0xe6546b64) >>> 0;\n }\n\n // ── Tail: 1–3 leftover bytes, folded in with classic Murmur3 cascade ────\n // The three `if`s implement C-style switch fallthrough: rem==3 runs all\n // three statements; rem==2 runs the bottom two; rem==1 runs only the last\n // block (which is the one that also mixes into h1).\n const tail = nblocks * 4;\n const rem = len & 3;\n if (rem > 0) {\n let k1 = 0;\n if (rem === 3) k1 ^= bytes[tail + 2] << 16;\n if (rem >= 2) k1 ^= bytes[tail + 1] << 8;\n k1 ^= bytes[tail];\n k1 = Math.imul(k1, C1);\n k1 = rotl32(k1, 15);\n k1 = Math.imul(k1, C2);\n h1 ^= k1;\n }\n\n // ── Finalize (fmix32): the avalanche stage ──────────────────────────────\n h1 ^= len;\n h1 ^= h1 >>> 16;\n h1 = Math.imul(h1, 0x85ebca6b);\n h1 ^= h1 >>> 13;\n h1 = Math.imul(h1, 0xc2b2ae35);\n h1 ^= h1 >>> 16;\n\n return h1 >>> 0;\n}\n\n/**\n * Shorten a `documentId` for use inside an HTML id prefix.\n *\n * @param id - The raw documentId (consumer-supplied or `useId()` fallback).\n * @param threshold - Only ids strictly longer than this get hashed.\n * Defaults to `16`, which leaves short hand-picked ids and React's\n * `useId()` outputs unchanged but catches UUIDs (36 chars) and nanoids.\n * @returns Either the original `id` (when short) or a 1–6 char Base62 hash.\n */\nexport function shortenDocumentId(id: string, threshold: number = 16): string {\n if (id.length <= threshold) return id;\n return toBase62(murmur3_32(id));\n}\n","/**\n * LaTeX preprocessing pipeline.\n *\n * Normalizes raw markdown so that LaTeX expressions survive the remark/rehype\n * rendering pipeline intact. The main entry point is {@link preprocessLaTeX},\n * which splits content into protected regions (code blocks, inline code, HTML\n * tags) and applies a sequence of transformations to the unprotected text:\n *\n * 1. Escape mhchem commands (`\\ce`, `\\pu`)\n * 2. Escape currency dollar signs (e.g. `$100`, `$1,000.50`)\n * 3. Convert bracket delimiters (`\\[...\\]`, `\\(...\\)`) to dollar delimiters\n * 4. Escape pipes inside closed LaTeX blocks to prevent GFM table interference\n * 5. Escape pipes inside unclosed LaTeX blocks (streaming partial content)\n * 6. Escape underscores inside `\\text{...}` commands\n * 7. Convert single-dollar delimiters to double-dollar delimiters\n * 8. Truncate trailing unclosed LaTeX blocks (streaming protection)\n *\n * Thanks to the implementations from the following repositories:\n * - https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n * - https://github.com/danny-avila/LibreChat/blob/main/client/src/utils/latex.ts\n *\n * @module preprocessors/latex\n */\n\ninterface Segment {\n text: string;\n isCode: boolean;\n}\n\ntype FenceMarker = '`' | '~';\n\nfunction getRepeatedMarkerLength(content: string, start: number, marker: FenceMarker): number {\n let end = start;\n while (end < content.length && content[end] === marker) {\n end += 1;\n }\n return end - start;\n}\n\n/**\n * Sticky regex for matching known HTML tags at a specific position.\n * The `y` (sticky) flag anchors the match at `lastIndex`, avoiding the need\n * to create a substring for each `<` character encountered during scanning.\n */\nconst HTML_TAG_REGEX =\n /<\\/?(span|div|p|br|hr|img|a|em|strong|b|i|u|s|sub|sup|code|pre|table|tr|td|th|thead|tbody|tfoot|ul|ol|li|dl|dt|dd|h[1-6]|blockquote|details|summary|figure|figcaption|section|article|aside|nav|header|footer|main|mark|del|ins|small|abbr|cite|dfn|kbd|samp|var|ruby|rt|rp|bdo|wbr|input|button|select|textarea|label|fieldset|legend|output|iframe|video|audio|source|canvas|svg|math|time)(?:\\s[^>]*)?\\/?>/iy;\n\n/**\n * Tags whose inner text must be treated as literal (never processed as LaTeX).\n * For these, an opening tag triggers protection of the entire paired region\n * `<tag>...</tag>` rather than just the tag itself, so dollar signs and other\n * LaTeX-looking characters inside (e.g. `<code>$x^2$</code>`) survive untouched.\n */\nconst LITERAL_CONTENT_TAGS = new Set(['code', 'pre', 'kbd', 'samp', 'math', 'svg']);\nconst LITERAL_CONTENT_CLOSE_REGEX: Record<string, RegExp> = {\n code: /<\\/code\\s*>/gi,\n pre: /<\\/pre\\s*>/gi,\n kbd: /<\\/kbd\\s*>/gi,\n samp: /<\\/samp\\s*>/gi,\n math: /<\\/math\\s*>/gi,\n svg: /<\\/svg\\s*>/gi,\n};\n\n/**\n * Is `pos` the start of a line with at most 3 spaces of leading indentation?\n *\n * CommonMark requires a fence opener/closer to sit at the beginning of a\n * line (optionally indented by up to 3 spaces). A 4-space indent turns the\n * line into an indented-code-block candidate instead, which we do not treat\n * as a fence at all.\n */\nfunction isAtLineStart(content: string, pos: number): boolean {\n let i = pos - 1;\n let spaces = 0;\n while (i >= 0 && content[i] === ' ') {\n spaces++;\n if (spaces > 3) return false;\n i--;\n }\n return i < 0 || content[i] === '\\n' || content[i] === '\\r';\n}\n\n/**\n * Find the next run of *exactly* `n` consecutive backticks at or after\n * `start`. Runs of any other length are skipped over. Returns the start\n * index of the matching run, or `-1` if no such run exists.\n *\n * Used to locate the closing delimiter of a CommonMark inline code span:\n * the closer must be a backtick run of the *same* length as the opener.\n */\nfunction findClosingBacktickRun(content: string, start: number, n: number): number {\n let i = start;\n while (i < content.length) {\n if (content[i] === '`') {\n const runLen = getRepeatedMarkerLength(content, i, '`');\n if (runLen === n) return i;\n i += runLen;\n } else {\n i += 1;\n }\n }\n return -1;\n}\n\n/**\n * Split content into alternating text and protected segments.\n * Protected segments (isCode: true) are excluded from LaTeX processing:\n * - fenced multiline code blocks: 3+ backticks or tildes at the *start of a\n * line* (≤3 space indent). Mid-line runs are never fence openers.\n * - inline code spans: a run of N backticks closed by another run of exactly\n * N backticks. May span newlines. Multi-backtick forms (e.g. `` `` `x` ``)\n * are supported so literal backtick characters can appear inside.\n * - HTML tags (e.g. `<span>$</span>` where `$` should not be treated as LaTeX).\n */\nexport function splitByProtectedRegions(content: string): Segment[] {\n const segments: Segment[] = [];\n let lastIndex = 0;\n let multilineStart = -1;\n let multilineFenceMarker: FenceMarker | null = null;\n let multilineFenceLength = 0;\n\n function pushProtected(start: number, end: number) {\n if (start > lastIndex) {\n segments.push({ text: content.substring(lastIndex, start), isCode: false });\n }\n segments.push({ text: content.substring(start, end), isCode: true });\n lastIndex = end;\n }\n\n let i = 0;\n while (i < content.length) {\n const char = content[i];\n\n // Inside a fenced code block: only look for a closing fence line.\n if (multilineStart !== -1) {\n if (char === multilineFenceMarker) {\n const runLen = getRepeatedMarkerLength(content, i, multilineFenceMarker);\n if (runLen >= multilineFenceLength && isAtLineStart(content, i)) {\n pushProtected(multilineStart, i + runLen);\n multilineStart = -1;\n multilineFenceMarker = null;\n multilineFenceLength = 0;\n i += runLen;\n continue;\n }\n i += runLen;\n continue;\n }\n i += 1;\n continue;\n }\n\n // Outside code: check fence opener, inline code span, then HTML tag.\n if (char === '`' || char === '~') {\n const runLen = getRepeatedMarkerLength(content, i, char);\n\n // Fenced code block opener: ≥3 markers and at a valid line start.\n if (runLen >= 3 && isAtLineStart(content, i)) {\n multilineStart = i;\n multilineFenceMarker = char;\n multilineFenceLength = runLen;\n i += runLen;\n continue;\n }\n\n // Inline code span: only backticks (tildes are never inline delimiters).\n if (char === '`') {\n const closeIdx = findClosingBacktickRun(content, i + runLen, runLen);\n if (closeIdx !== -1) {\n pushProtected(i, closeIdx + runLen);\n i = closeIdx + runLen;\n continue;\n }\n }\n\n // Unmatched run — skip the whole run so we don't re-interpret its\n // individual backticks on subsequent iterations.\n i += runLen;\n continue;\n }\n\n if (char === '<') {\n // Only match known HTML tags to avoid false positives with angle brackets\n // in markdown links (<Slides Demo>), math comparisons ($a < b$), etc.\n // Use sticky regex to match at position i without creating a substring.\n HTML_TAG_REGEX.lastIndex = i;\n const tagMatch = HTML_TAG_REGEX.exec(content);\n if (tagMatch) {\n let endIndex = i + tagMatch[0].length;\n // For literal-content tags (code/pre/math/...), protect the paired\n // <tag>...</tag> region so inner `$` never enters LaTeX processing.\n const tagName = tagMatch[1].toLowerCase();\n const isOpeningPairedTag =\n content[i + 1] !== '/' && !tagMatch[0].endsWith('/>') && LITERAL_CONTENT_TAGS.has(tagName);\n if (isOpeningPairedTag) {\n const closeRegex = LITERAL_CONTENT_CLOSE_REGEX[tagName];\n closeRegex.lastIndex = endIndex;\n const closeMatch = closeRegex.exec(content);\n if (closeMatch) {\n endIndex = closeMatch.index + closeMatch[0].length;\n } else {\n // Streaming: closing tag hasn't arrived yet. Protect everything\n // to the end of input so inner `$` etc. aren't mutated before\n // the closer shows up in a later chunk.\n endIndex = content.length;\n }\n }\n pushProtected(i, endIndex);\n i = endIndex;\n continue;\n }\n }\n\n i += 1;\n }\n\n if (multilineStart !== -1) {\n pushProtected(multilineStart, content.length);\n }\n\n // Push remaining text\n if (lastIndex < content.length) {\n segments.push({ text: content.substring(lastIndex), isCode: false });\n }\n\n return segments;\n}\n\n/**\n * Escape mhchem commands in LaTeX expressions to ensure proper rendering.\n *\n * @param text Input string containing LaTeX expressions with mhchem commands\n * @returns String with escaped mhchem commands\n * @from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction escapeMhchemCommands(text: string) {\n return text.replaceAll('$\\\\ce{', '$\\\\\\\\ce{').replaceAll('$\\\\pu{', '$\\\\\\\\pu{');\n}\n\nconst CURRENCY_REGEX = /(?<![\\\\$])\\$(?!\\$)(?=\\d+(?:,\\d{3})*(?:\\.\\d+)?(?:[KMBkmb])?(?:\\s|$|[^a-zA-Z\\d]))/g;\nconst NO_ESCAPED_DOLLAR_REGEX = /(?<![\\\\$])\\$(?!\\$)/g;\n// Match \\[...\\] and \\(...\\) as LaTeX delimiters, but exclude:\n// - !\\[...\\] (markdown image)\n// - \\[...\\]( (markdown link)\nconst DELIMITERS_REGEX = /(?<!!)\\\\\\[([\\S\\s]*?[^\\\\])\\\\](?!\\()|\\\\\\((.*?)\\\\\\)/g;\nconst ARRAY_COL_SPEC_OR_PIPE_REGEX = /(\\\\begin\\{(?:array|tabular[x*]?)\\}\\{[^}]*\\})|(?<!\\\\)\\|/g;\n// Display $$ allows multiline; inline $ forbids newlines (consistent with SINGLE_DOLLAR_REGEX)\nconst LATEX_BLOCK_REGEX = /\\$\\$([\\S\\s]*?)\\$\\$|(?<![\\\\$])\\$(?!\\$)((?:[^$\\n]|\\\\\\$)*?)(?<![\\\\`])\\$(?!\\$)/g;\nconst TEXT_COMMAND = '\\\\text{';\nconst SINGLE_DOLLAR_REGEX = /(?<![\\\\$])\\$(?!\\$)((?:[^$\\n]|\\\\[$])+?)(?<!\\\\)(?<!`)\\$(?!\\$)/g;\n\n/**\n * Escape currency dollar signs (e.g. $100, $1,000.50) so they are not\n * misinterpreted as LaTeX delimiters.\n *\n * The tricky part: a `$` followed by digits might still be inside a LaTeX\n * expression (e.g. `$8.29 \\text{ B} \\times 4$`). We detect this by checking\n * whether there is an odd number of unescaped `$` on the same line after the\n * current match — if so, the current `$` is a LaTeX opener, not currency.\n */\nfunction escapeCurrencyDollarSigns(text: string): string {\n const parts: string[] = [];\n let lastIndex = 0;\n const currencyMatches = Array.from(text.matchAll(CURRENCY_REGEX));\n\n // Track the processed content of the current line incrementally\n // to avoid O(n²) from joining all parts on every match.\n let currentLineProcessed = '';\n\n for (let i = 0; i < currencyMatches.length; i++) {\n const match = currencyMatches[i];\n const segment = text.substring(lastIndex, match.index);\n parts.push(segment);\n\n // Update currentLineProcessed: keep only content after the last newline.\n const newlineIdx = Math.max(segment.lastIndexOf('\\n'), segment.lastIndexOf('\\r'));\n if (newlineIdx !== -1) {\n currentLineProcessed = segment.substring(newlineIdx + 1);\n } else {\n currentLineProcessed += segment;\n }\n\n let needEscape = true;\n let restBeforeNextMatchOrEnd = '';\n if (i < currencyMatches.length - 1) {\n const nextMatch = currencyMatches[i + 1];\n if (nextMatch.index - match.index > 1) {\n restBeforeNextMatchOrEnd = text.substring(match.index + 1, nextMatch.index);\n }\n } else {\n restBeforeNextMatchOrEnd = text.substring(match.index + 1);\n }\n const firstLineBeforeNextMatch = restBeforeNextMatchOrEnd.split(/\\r\\n|\\r|\\n/g)[0];\n if (Array.from(firstLineBeforeNextMatch.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {\n const wholeLineBeforeNextMatchWithoutCurrentDollar = currentLineProcessed + firstLineBeforeNextMatch;\n if (Array.from(wholeLineBeforeNextMatchWithoutCurrentDollar.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {\n needEscape = false;\n }\n }\n\n const replacement = needEscape ? '\\\\$' : '$';\n parts.push(replacement);\n // Append to currentLineProcessed so subsequent parity checks on the same\n // line see the correct count of unescaped `$` (e.g. a left-as-`$` opener\n // that the next match's check must count).\n currentLineProcessed += replacement;\n lastIndex = match.index + 1;\n }\n parts.push(text.substring(lastIndex));\n return parts.join('');\n}\n\n/**\n * Convert LaTeX bracket delimiters to dollar sign delimiters.\n * Converts \\[...\\] to $$...$$ and \\(...\\) to $...$\n *\n * @param text Input string containing LaTeX expressions\n * @returns String with LaTeX bracket delimiters converted to dollar sign delimiters\n * @modified from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction convertLatexDelimiters(text: string): string {\n return text.replaceAll(\n DELIMITERS_REGEX,\n (match: string, squareBracket: string | undefined, roundBracket: string | undefined): string => {\n if (squareBracket !== undefined) {\n return `$$${squareBracket}$$`;\n } else if (roundBracket !== undefined) {\n return `$${roundBracket}$`;\n }\n return match;\n }\n );\n}\n\n/**\n * Helper function: replace unescaped pipes with \\vert in LaTeX math fragments\n * @from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nconst replaceUnescapedPipes = (formula: string): string =>\n // Use \\vert{} so the control sequence terminates before the next token.\n // Preserve `|` inside \\begin{array}{...} / \\begin{tabular}{...} column specifiers.\n formula.replaceAll(ARRAY_COL_SPEC_OR_PIPE_REGEX, (match, colSpec: string | undefined) =>\n colSpec !== undefined ? match : '\\\\vert{}'\n );\n/**\n * Escape pipes in LaTeX expressions to prevent them from being interpreted as\n * column separators in markdown tables.\n *\n * @param text Input string containing LaTeX expressions\n * @returns String with pipes escaped in LaTeX expressions\n * @modified from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction escapeLatexPipes(text: string): string {\n return text.replaceAll(LATEX_BLOCK_REGEX, (match, display, inline) => {\n if (display !== undefined) return `$$${replaceUnescapedPipes(display)}$$`;\n if (inline !== undefined) return `$${replaceUnescapedPipes(inline)}$`;\n return match;\n });\n}\n\n/**\n * Whether the character at position `pos` is escaped by the immediately\n * preceding backslash run. An even-count run (including zero) means the\n * `$` is unescaped; an odd count means it is escaped. Example: `\\\\$` has\n * two preceding backslashes — the `\\` escapes the `\\`, leaving `$` real.\n */\nfunction isEscapedByBackslashRun(text: string, pos: number): boolean {\n let count = 0;\n let j = pos - 1;\n while (j >= 0 && text[j] === '\\\\') {\n count++;\n j--;\n }\n return count % 2 === 1;\n}\n\n/**\n * Find the start index of the trailing unclosed `$$` or `$` delimiter.\n *\n * Scans through all dollar-sign tokens tracking open/close state.\n * Returns the index of the last *opening* delimiter that was never closed,\n * or `-1` if every delimiter is paired.\n *\n * @param text Input string to scan.\n * @param mode `'both'` tracks `$$` and `$`; `'double-only'` tracks only `$$`.\n */\nfunction findUnclosedDelimiterStart(text: string, mode: 'both' | 'double-only'): number {\n let unclosedStart = -1;\n let i = 0;\n while (i < text.length) {\n if (text[i] === '$' && i + 1 < text.length && text[i + 1] === '$' && !isEscapedByBackslashRun(text, i)) {\n unclosedStart = unclosedStart === -1 ? i : -1;\n i += 2;\n } else if (\n mode === 'both' &&\n text[i] === '$' &&\n !isEscapedByBackslashRun(text, i) &&\n (i + 1 >= text.length || text[i + 1] !== '$')\n ) {\n unclosedStart = unclosedStart === -1 ? i : -1;\n i += 1;\n } else {\n i += 1;\n }\n }\n return unclosedStart;\n}\n\nfunction escapeLatexPipesInUnclosed(text: string): string {\n const unclosedStart = findUnclosedDelimiterStart(text, 'both');\n if (unclosedStart === -1) return text;\n\n // Escape pipes only in the unclosed tail\n const before = text.substring(0, unclosedStart);\n const delimLen = text[unclosedStart + 1] === '$' ? 2 : 1;\n const delim = text.substring(unclosedStart, unclosedStart + delimLen);\n const tail = text.substring(unclosedStart + delimLen);\n return before + delim + replaceUnescapedPipes(tail);\n}\n\n/**\n * Truncate trailing unclosed `$$` blocks (streaming protection).\n *\n * During streaming, an unclosed `$$` at the start of a line triggers\n * remarkMath's `mathFlow` tokenizer, which treats all subsequent content\n * as part of a display math block until a closing `$$` fence is found.\n * Since the closing fence hasn't arrived yet, the entire remainder of the\n * document is swallowed into one giant math node — producing a wall of\n * red KaTeX error text.\n *\n * This function detects the trailing unclosed `$$` and removes it\n * (including any preceding whitespace/newlines) so that remarkMath never\n * sees the incomplete delimiter. Once the closing delimiter arrives in\n * a later streaming chunk, the complete block will render normally.\n *\n * Only tracks `$$` — single `$` does not trigger mathFlow and is harmless\n * when `singleDollarTextMath` is `false`.\n */\nfunction truncateUnclosedLatexBlock(text: string): string {\n const unclosedStart = findUnclosedDelimiterStart(text, 'double-only');\n if (unclosedStart === -1) return text;\n\n // Strip the unclosed $$ block and any trailing whitespace before it.\n return text.substring(0, unclosedStart).trimEnd();\n}\n\n/**\n * Escape unescaped underscores within `\\text{...}` commands in LaTeX expressions.\n * For example, `\\text{node_domain}` becomes `\\text{node\\_domain}`, but\n * `\\text{node\\_domain}` stays unchanged.\n *\n * The body scan is brace-aware: nested groups `\\text{outer {inner}_x}`\n * are matched via a depth counter that respects `\\{` / `\\}` escapes and\n * the escape for `\\\\` itself, so the entire body (depth ≥ 0) is scanned\n * before we escape its underscores. An unclosed `\\text{` body (missing\n * closing brace, e.g. during streaming) is left untouched.\n *\n * @param text Input string that may contain LaTeX expressions\n * @returns String with unescaped underscores escaped within `\\text{...}` commands\n */\nfunction escapeTextUnderscores(text: string): string {\n let out = '';\n let i = 0;\n while (i < text.length) {\n const start = text.indexOf(TEXT_COMMAND, i);\n if (start === -1) {\n out += text.substring(i);\n return out;\n }\n\n out += text.substring(i, start);\n const bodyStart = start + TEXT_COMMAND.length;\n let depth = 1;\n let j = bodyStart;\n while (j < text.length && depth > 0) {\n const c = text[j];\n if (c === '\\\\' && j + 1 < text.length) {\n // Skip the escaped character so `\\{`, `\\}`, `\\\\` don't affect depth.\n j += 2;\n continue;\n }\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) break;\n }\n j++;\n }\n\n if (depth !== 0) {\n // Unclosed \\text{ — leave the remainder as-is so a later streaming\n // chunk can complete it.\n out += text.substring(start);\n return out;\n }\n\n const body = text.substring(bodyStart, j);\n const escapedBody = body.replaceAll(/(?<!\\\\)_/g, '\\\\_');\n out += `\\\\text{${escapedBody}}`;\n i = j + 1; // past closing `}`\n }\n return out;\n}\n\n/**\n * Convert single dollar delimiters to double dollar delimiters.\n * e.g. $x^2$ → $$x^2$$\n */\nfunction convertSingleToDoubleDollar(text: string): string {\n return text.replaceAll(SINGLE_DOLLAR_REGEX, (_match, content: string) => `$$${content}$$`);\n}\n\n/**\n * Main LaTeX preprocessor entry point.\n *\n * Splits the input into protected regions (code blocks, inline code, HTML tags)\n * and applies the full normalization pipeline to unprotected text segments.\n * Returns the input unchanged when no LaTeX-related characters (`$`, `\\[`, `\\(`)\n * are detected.\n *\n * @param str - Raw markdown string.\n * @returns The preprocessed string with normalized LaTeX delimiters.\n */\nexport function preprocessLaTeX(str: string): string {\n // Return early if no LaTeX patterns are found\n if (!str.includes('$') && !str.includes('\\\\[') && !str.includes('\\\\(')) return str;\n\n // Step 1: split by code blocks\n const segments = splitByProtectedRegions(str);\n\n // Step 2: process each non-code segment through the LaTeX pipeline\n const result = segments.map((segment) => {\n if (segment.isCode) return segment.text;\n\n let text = segment.text;\n text = escapeMhchemCommands(text);\n text = escapeCurrencyDollarSigns(text);\n text = convertLatexDelimiters(text);\n text = escapeLatexPipes(text);\n text = escapeLatexPipesInUnclosed(text);\n text = escapeTextUnderscores(text);\n text = convertSingleToDoubleDollar(text);\n text = truncateUnclosedLatexBlock(text);\n return text;\n });\n\n return result.join('');\n}\n","/**\n * Content preprocessing pipeline.\n *\n * Runs all preprocessors (built-in + user-supplied) in sequence before\n * the markdown string is handed to react-markdown. The built-in LaTeX\n * preprocessor always runs first, followed by any extra preprocessors\n * provided by the consumer.\n *\n * @module preprocessors\n */\n\nimport { AIMDContentPreprocessor } from './defs';\nimport { preprocessLaTeX } from './latex';\n\n/** Sequentially apply an array of preprocessor functions via left-fold. */\nfunction applyPreprocessors(value: string, ...fns: Array<AIMDContentPreprocessor>): string {\n return fns.reduce((result, fn) => fn(result), value);\n}\n\n/** Stable empty array to avoid re-renders when no extra preprocessors are given. */\nconst defaultExtraPreprocessors: AIMDContentPreprocessor[] = [];\n\n/**\n * Run the full preprocessing pipeline on raw markdown content.\n *\n * @param content - Raw markdown string.\n * @param extraPreprocessors - Optional user-supplied preprocessors appended after the built-in ones.\n * @returns The preprocessed markdown string ready for rendering.\n */\nexport default function preprocessAIMDContent(\n content: string,\n extraPreprocessors: AIMDContentPreprocessor[] = defaultExtraPreprocessors\n) {\n return applyPreprocessors(content, preprocessLaTeX, ...extraPreprocessors);\n}\n","/**\n * Core markdown rendering component.\n *\n * Wraps the local `Markdown` (a vendored fork of react-markdown — see\n * `./markdown/`) with a curated set of remark and rehype plugins for GFM,\n * math/LaTeX, emoji, CJK support, and configurable extra syntax extensions\n * and display optimizations. Plugin selection is driven by the\n * {@link AIMarkdownRenderConfig} from context.\n *\n * ## Render strategy\n *\n * Two render paths gated by `config.blockMemoEnabled` (default `true`):\n *\n * - **Block-memo path** (`BlockMemoizedRenderer`): the rendered hast is cut\n * into per-block units and memoized across frames by source identity\n * (`raw + occurrence + ctx + position triple`). Streaming append where\n * prior blocks are unchanged skips `toJsxRuntime` + React reconcile for\n * those blocks.\n *\n * - **Legacy path** (`LegacyRenderer`): the vendored `<Markdown>` is called\n * directly with no cache. Every render runs the full pipeline; output is\n * byte-identical to the block-memo path (locked in by\n * `byteEquivalence.test.tsx`).\n *\n * The branch is at the component-tree level: only one of the two child\n * renderers is mounted at a time, so the disabled path pays no `useRef` /\n * `useMemo` cost from block-memo's bookkeeping. Toggling the option at\n * runtime unmounts one and mounts the other (the discarded path's cache\n * is GC'd).\n *\n * ## Performance contract — block-level memoization\n *\n * For the cache to be effective, props that influence rendered output must\n * be referentially stable across renders. This component stabilizes its own\n * plugin arrays via `useMemo`. The outer `<AIMarkdown>` stabilizes\n * `customComponents` via `useStableValue`. If you wire `<AIMarkdownContent>`\n * directly, ensure `customComponents` is memoized at the call site.\n *\n * @module components/MarkdownContent\n */\n\nimport { Fragment, memo, useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport Markdown, { parseStage, transformStage, type Options as MarkdownOptions } from './markdown';\n\ntype RemarkPlugins = NonNullable<MarkdownOptions['remarkPlugins']>;\ntype RehypePlugins = NonNullable<MarkdownOptions['rehypePlugins']>;\ntype RemarkRehypeOptions = NonNullable<MarkdownOptions['remarkRehypeOptions']>;\nimport rehypeKatex from 'rehype-katex';\nimport rehypeRaw from 'rehype-raw';\nimport rehypeUnwrapImages from 'rehype-unwrap-images';\nimport rehypeSanitize from 'rehype-sanitize';\nimport { sanitizeSchema } from './sanitizeSchema';\nimport rehypeRebaseHashLinks from './rehypeRebaseHashLinks';\nimport rehypeFooterAdorn from './rehypeFooterAdorn';\nimport remarkBreaks from 'remark-breaks';\nimport remarkCjkFriendly from 'remark-cjk-friendly';\nimport remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough';\nimport remarkEmoji from 'remark-emoji';\nimport remarkGfm from 'remark-gfm';\nimport remarkMath from 'remark-math';\nimport { remarkDefinitionList, defListHastHandlers } from 'remark-definition-list';\nimport { remarkMark as remarkMarkHighlight } from 'remark-mark-highlight';\nimport remarkSqueezeParagraphs from 'remark-squeeze-paragraphs';\nimport remarkSmartypants from 'remark-smartypants';\nimport remarkPangu from 'remark-pangu';\nimport remarkRemoveComments from 'remark-remove-comments';\nimport { buildBlocks, createCache, renderBlocksWithCache, type Cache, type PostOptions } from './blockMemo';\nimport { useAIMarkdownRenderState } from '../context';\nimport {\n AIMarkdownCustomComponents,\n AIMarkdownRenderDisplayOptimizeAbility,\n AIMarkdownRenderExtraSyntax,\n} from '../defs';\nimport { collectDefLabels } from './collectDefLabels';\nimport { useDocumentRegistry, usePreserveOrphanReferences } from './AIMarkdownDocuments';\nimport type { Registry } from './documentRegistry';\nimport { augmentSourceWithPhantoms } from './remarkInjectPhantomDefs';\nimport { buildCrossChunkHandlers } from './customMdastHandlers';\nimport { normalizeForMatch } from './normalizeId';\nimport { crossChunkComponents } from './crossChunkPlaceholders';\nimport { extractContributions } from './extractContributions';\nimport { extractDefBodiesFromHast } from './extractDefBodiesFromHast';\nimport { AggregateFootnotesIfLast } from './aggregateFootnotesIfLast';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport type { ElementContent as HastElementContent } from 'hast';\n\n/** Module-level SSR snapshot constant for useSyncExternalStore. Hoisted out\n * of the component so its identity is stable across renders (a fresh `() => 0`\n * every render would defeat the snapshot-stability guarantees the hook\n * relies on). */\nconst REGISTRY_SSR_SNAPSHOT = () => 0;\n\n/** Maps display optimization abilities to their corresponding remark plugins. */\nconst DisplayOptimizeRemarkPluginMap = {\n [AIMarkdownRenderDisplayOptimizeAbility.REMOVE_COMMENTS]: remarkRemoveComments,\n [AIMarkdownRenderDisplayOptimizeAbility.SMARTYPANTS]: remarkSmartypants,\n [AIMarkdownRenderDisplayOptimizeAbility.PANGU]: remarkPangu,\n};\n\n/** Maps extra syntax extensions to their corresponding remark plugins. */\nconst ExtraSyntaxRemarkPluginMap = {\n [AIMarkdownRenderExtraSyntax.HIGHLIGHT]: remarkMarkHighlight,\n [AIMarkdownRenderExtraSyntax.DEFINITION_LIST]: remarkDefinitionList,\n};\n\n/** Stable empty object to avoid unnecessary re-renders when no custom components are given. */\nconst DefaultCustomComponents: AIMarkdownCustomComponents = {};\n\ninterface AIMarkdownContentProps {\n /** Preprocessed markdown string to render. */\n content: string;\n /** Optional react-markdown component overrides (e.g. custom code block renderer). */\n customComponents?: AIMarkdownCustomComponents;\n}\n\ninterface RendererProps {\n content: string;\n usedComponents: AIMarkdownCustomComponents;\n remarkPlugins: RemarkPlugins;\n rehypePlugins: RehypePlugins;\n remarkRehypeOptions: RemarkRehypeOptions;\n}\n\n/**\n * Block-memo render path. Mounted when `config.blockMemoEnabled === true`.\n * Encapsulates the `useRef`-backed cache, G3 sync flush, and the three-stage\n * unified pipeline (parse → transform → buildBlocks → renderBlocksWithCache).\n */\nconst BlockMemoizedRenderer = memo(\n ({ content, usedComponents, remarkPlugins, rehypePlugins, remarkRehypeOptions }: RendererProps) => {\n // Vendored Markdown options that AIMarkdown does not currently expose. They\n // are tracked in the G3 flush below so the cache stays correct if any of\n // these are ever surfaced upstream.\n const urlTransform: MarkdownOptions['urlTransform'] = undefined;\n const allowedElements: MarkdownOptions['allowedElements'] = undefined;\n const disallowedElements: MarkdownOptions['disallowedElements'] = undefined;\n const allowElement: MarkdownOptions['allowElement'] = undefined;\n const skipHtml: MarkdownOptions['skipHtml'] = undefined;\n const unwrapDisallowed: MarkdownOptions['unwrapDisallowed'] = undefined;\n\n // ─── Cross-chunk coordination wiring (Phase 11) ──────────────────────────\n // All effects below are NO-OP when `registry === null` (standalone mode\n // without `<AIMarkdownDocuments>`): the gating is on `registry` truthiness.\n const { documentId, clobberPrefix, config } = useAIMarkdownRenderState();\n const reactId = useId();\n const registry = useDocumentRegistry(documentId);\n // Allocate-and-publish state: the Symbol for THIS chunk PAIRED with the\n // registry it was allocated from. Modelling as state — instead of a\n // ref — makes both fields real deps for downstream effects, so React's\n // dep system (not microtask FIFO) enforces \"allocate before contribute\"\n // ordering.\n //\n // Why the registry is bundled with sym: a parent that re-renders with a\n // different `documentId` (read from context) causes `registry` to flip\n // to a NEW Registry instance on the next render. React retains state\n // across that render, so `sym` still holds the OLD registry's Symbol\n // until Effect 1's cleanup runs and clears it. If Effect 2 reads `sym`\n // directly during that gap, it contributes the stale Symbol into the\n // NEW registry — polluting `chunkData` with an unowned entry that\n // `onEmpty`'s `chunkData.size === 0` check never sees as gone, leaking\n // the registry. Storing the registry alongside the sym lets Effect 2\n // gate on `allocation.registry === registry` and skip the stale tick.\n const [allocation, setAllocation] = useState<{ registry: Registry; sym: symbol } | null>(null);\n const sym = allocation && allocation.registry === registry ? allocation.sym : null;\n\n // Subscribe to registry version changes. Without this, useMemo deps that\n // include `registry?.version` would never re-evaluate — useMemo only re-\n // runs when its component re-renders, and a version bump from another\n // chunk's contribute step doesn't trigger our re-render on its own.\n // useSyncExternalStore's subscribe handle does the wake-up: when any\n // chunk calls registry._notify, every subscribed renderer re-renders,\n // PASS 0.5 picks up new labelSet entries, PASS 1 augments + re-parses,\n // placeholder hast tags emerge, and the placeholder components (which\n // also useSyncExternalStore) resolve their numbers/URLs.\n // Subscribe identity must be stable across renders — useSyncExternalStore\n // resubscribes whenever `subscribe` changes identity, so an inline\n // `(cb) => ...` would trigger unsubscribe+resubscribe on every render.\n // For N coordinated chunks each waking on every notify, that's O(N²)\n // subscriber-list churn during initial mount.\n const subscribeRegistry = useCallback(\n (cb: () => void) => (registry ? registry.subscribe(cb) : () => {}),\n [registry]\n );\n const getRegistryVersion = useCallback(() => registry?.version ?? 0, [registry]);\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, REGISTRY_SSR_SNAPSHOT);\n\n // PASS 0: lightweight def-label scan, then publish to registry.labelSet.\n const ownLabels = useMemo(() => collectDefLabels(content ?? ''), [content]);\n\n useEffect(() => {\n if (!registry) return;\n const s = registry.registerChunk(reactId, ownLabels.footnoteLabels, ownLabels.linkLabels);\n setAllocation({ registry, sym: s });\n return () => {\n registry.releaseSymbol(reactId);\n setAllocation(null);\n };\n }, [reactId, registry, ownLabels]);\n\n // G3 — synchronous deps-diff flush. Discards the per-block cache when any\n // option that affects rendered output (but not parse output) changes\n // identity. The check runs synchronously at the top of render: an\n // `useEffect` would only fire after commit, by which time the current\n // render has already read from the (now stale) cache and emitted incorrect\n // output. The cache is best-effort memoization across renders, not state\n // the UI depends on for correctness — concurrent render aborts are safe\n // because (a) cache hits return identical node references, and (b) cache\n // misses always recompute from inputs that are themselves pure.\n //\n // Cache-memoization pattern documented above is an established exception\n // to the React Compiler purity check (rule renamed across react-hooks\n // plugin versions, so the previous block disable no longer suppresses\n // anything in v7+). See design `/tmp/phase5-block-memo-decisions.md` §4.\n const cacheRef = useRef<Cache>(createCache());\n const depsRef = useRef<{\n usedComponents: typeof usedComponents;\n remarkPlugins: typeof remarkPlugins;\n rehypePlugins: typeof rehypePlugins;\n remarkRehypeOptions: typeof remarkRehypeOptions;\n urlTransform: typeof urlTransform;\n allowedElements: typeof allowedElements;\n disallowedElements: typeof disallowedElements;\n allowElement: typeof allowElement;\n skipHtml: typeof skipHtml;\n unwrapDisallowed: typeof unwrapDisallowed;\n registry: Registry | null;\n symbol: symbol | null;\n }>({\n usedComponents,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n symbol: sym,\n });\n if (\n depsRef.current.usedComponents !== usedComponents ||\n depsRef.current.remarkPlugins !== remarkPlugins ||\n depsRef.current.rehypePlugins !== rehypePlugins ||\n depsRef.current.remarkRehypeOptions !== remarkRehypeOptions ||\n depsRef.current.urlTransform !== urlTransform ||\n depsRef.current.allowedElements !== allowedElements ||\n depsRef.current.disallowedElements !== disallowedElements ||\n depsRef.current.allowElement !== allowElement ||\n depsRef.current.skipHtml !== skipHtml ||\n depsRef.current.unwrapDisallowed !== unwrapDisallowed ||\n depsRef.current.registry !== registry ||\n depsRef.current.symbol !== sym\n ) {\n cacheRef.current = createCache();\n depsRef.current = {\n usedComponents,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n symbol: sym,\n };\n }\n\n // PASS 0.5: which labels does this chunk reference that are defined\n // elsewhere? Substring over-approximation: normalize content (resolve \\X +\n // ws-collapse + uppercase) and check against the registry's union labelSet.\n // labelSet entries are already normalized; any standard ref form contains\n // the label as substring after normalization. False-positive (wasted\n // reparse) acceptable; false-negative for backslash-escaped / multi-line\n // whitespace labels accepted as v1 limit.\n //\n // Stable reference: every `registry._notify` (3× per chunk on mount: alloc,\n // contributeLabels, contributeChunkData) bumps `registry.version`, which is\n // a useMemo dep here. Without ref-stability, every bump produces fresh Set\n // instances → `parsed` useMemo invalidates → full re-parse runs. With N\n // chunks coordinating, that's O(N²) parses at mount and a visible white\n // screen for 30+ chunks. We compare the freshly-computed Sets to the\n // previous result via a ref and return the previous reference when the\n // contents are identical — collapsing the cascade to one parse per chunk.\n const targetPhantomsRef = useRef<{ missingFootnotes: Set<string>; missingLinks: Set<string> }>({\n missingFootnotes: new Set<string>(),\n missingLinks: new Set<string>(),\n });\n const targetPhantoms = useMemo(() => {\n let nextFootnotes: Set<string>;\n let nextLinks: Set<string>;\n if (!registry) {\n nextFootnotes = new Set<string>();\n nextLinks = new Set<string>();\n } else {\n const normalized = normalizeForMatch(content ?? '');\n nextFootnotes = new Set<string>();\n nextLinks = new Set<string>();\n for (const label of registry.labelSet.footnoteLabels) {\n if (ownLabels.footnoteLabels.has(label)) continue;\n if (normalized.includes(label)) nextFootnotes.add(label);\n }\n for (const label of registry.labelSet.linkLabels) {\n if (ownLabels.linkLabels.has(label)) continue;\n if (normalized.includes(label)) nextLinks.add(label);\n }\n }\n const prev = targetPhantomsRef.current;\n if (\n nextFootnotes.size === prev.missingFootnotes.size &&\n nextLinks.size === prev.missingLinks.size &&\n [...nextFootnotes].every((l) => prev.missingFootnotes.has(l)) &&\n [...nextLinks].every((l) => prev.missingLinks.has(l))\n ) {\n return prev;\n }\n const next = { missingFootnotes: nextFootnotes, missingLinks: nextLinks };\n targetPhantomsRef.current = next;\n return next;\n // version is the freshness anchor (subscribe in placeholder components handles re-render)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [registry, registry?.version, content, ownLabels]);\n\n const effectivePreserveOrphan = usePreserveOrphanReferences(config.preserveOrphanReferences);\n // In coordinated client renders, def-only chunks may be referenced by\n // other chunks even when visible orphan rendering is disabled. Once this\n // chunk has a Symbol, keep real defs in the synthetic footer so\n // extractDefBodiesFromHast can harvest their post-pipeline bodyHast; the\n // aggregate footer below still uses effectivePreserveOrphan to decide\n // whether unreferenced defs are visible.\n const preserveForBodyHarvest = effectivePreserveOrphan || Boolean(registry && sym);\n\n // PASS 1: full parse on (possibly) augmented source, with custom handlers\n // wired through remarkRehypeOptions.\n //\n // Two activation conditions:\n // 1. `registry` present → coordinated mode → ALL 4 handlers (Direction A\n // orphan protection + Direction B cross-chunk ref placeholders).\n // 2. `registry` absent + `effectivePreserveOrphan` → standalone mode →\n // ONLY `footnoteDefinition` handler (Direction A orphan protection\n // via state.footnoteOrder push). The other 3 handlers must NOT run in\n // standalone, otherwise:\n // - `footnoteReference` would emit `<footnote-sup>` placeholder\n // which depends on registry for the number → renders null → all\n // standalone footnotes disappear (regression).\n // - `linkReference`/`imageReference` would emit cross-chunk-*\n // placeholders that also depend on registry → broken links.\n const handlers = useMemo(() => {\n if (registry) return buildCrossChunkHandlers();\n if (effectivePreserveOrphan) {\n const { footnoteDefinition } = buildCrossChunkHandlers();\n return { footnoteDefinition };\n }\n return undefined;\n }, [registry, effectivePreserveOrphan]);\n\n // Stage 1 + 2: parse → run remark/rehype pipeline. The `parsed.mdast` is\n // mutated in place during `transformStage`; the useMemo chain below keeps\n // ordering correct for `buildBlocks`.\n const parsed = useMemo(() => {\n const augmented = augmentSourceWithPhantoms(content ?? '', targetPhantoms);\n const baseHandlers = remarkRehypeOptions?.handlers ?? {};\n const mergedRemarkRehypeOptions = handlers\n ? {\n ...remarkRehypeOptions,\n handlers: { ...baseHandlers, ...handlers },\n // Phantom label sets are empty in standalone mode (no PASS 0.5\n // injection happened); the footnoteDefinition handler still reads\n // them via `state.options.phantomFootnoteLabels.has(id)`, which\n // returns false for every id → orphan-protect path proceeds.\n phantomFootnoteLabels: targetPhantoms.missingFootnotes,\n phantomLinkLabels: targetPhantoms.missingLinks,\n preserveOrphan: preserveForBodyHarvest,\n documentId,\n }\n : {\n ...remarkRehypeOptions,\n };\n return parseStage({\n children: augmented,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions: mergedRemarkRehypeOptions as RemarkRehypeOptions,\n });\n }, [\n content,\n targetPhantoms,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n handlers,\n preserveForBodyHarvest,\n documentId,\n ]);\n const hast = useMemo(() => transformStage(parsed), [parsed]);\n\n // Cut hast into per-block units indexed back to mdast for cache identity,\n // and compute the document-wide ctx digest for cross-block invalidation.\n const built = useMemo(() => buildBlocks(parsed.mdast, hast, content ?? ''), [parsed.mdast, hast, content]);\n\n const postOptions = useMemo<PostOptions>(\n () => ({\n components: { ...crossChunkComponents, ...usedComponents },\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n // v6 fingerprint cache fields:\n registry: registry ?? undefined,\n thisChunkSymbol: sym ?? undefined,\n clobberPrefix,\n }),\n // `sym` is now real state (setSym after allocateSymbol), so it's a\n // proper dep and postOptions refreshes when allocation completes.\n // `registry?.version` stays in deps so the per-block fingerprint cache\n // path sees the latest registry version on every coordinated update.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n usedComponents,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n registry?.version,\n sym,\n clobberPrefix,\n ]\n );\n\n // Post-PASS-1 contribute: walk the parsed mdast and publish refs/defs\n // back to the registry so other chunks can resolve cross-chunk labels.\n //\n // Guarded by a fingerprint to prevent an infinite re-render cascade:\n // contributeChunkData calls _notify → version++ → useSyncExternalStore\n // wakes this renderer → targetPhantoms recomputes (fresh Set instances)\n // → parsed re-runs (new mdast reference) → this effect would re-fire\n // and re-contribute the same data → loop. Comparing serialized payload\n // to last contribution breaks the cycle at the side-effect layer.\n //\n // Ordering: `sym` is in the dep array, so this effect re-fires after the\n // allocate effect commits its setSym(...). The previous microtask/flushSync\n // dance is gone; React's dep system enforces \"allocate before contribute\".\n const lastContributionRef = useRef<{\n registry: Registry;\n symbol: symbol;\n fp: string;\n } | null>(null);\n useEffect(() => {\n if (!registry || !sym) return;\n const refs: {\n label: string;\n kind: 'footnote' | 'link' | 'image';\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n }[] = [];\n // Collect def metadata first so the fingerprint compares only cheap\n // fields. bodyHast is sourced from the post-pipeline hast (not from a\n // bare mdast→hast walk) so def bodies inside the cross-chunk aggregate\n // render with full plugin output (math, raw HTML, defLists, …).\n const defMeta = new Map<string, { identifier: string; sourceIdentifier: string; contentSource: string }>();\n const linkDefs = new Map<string, { identifier: string; url: string; title?: string }>();\n for (const node of extractContributions(parsed.mdast, {\n phantomFootnoteLabels: targetPhantoms.missingFootnotes,\n })) {\n if (node.kind === 'ref') {\n refs.push({ label: node.label, kind: node.refKind, referenceType: node.referenceType });\n } else if (node.kind === 'fnDef') {\n defMeta.set(node.label, {\n identifier: node.label,\n sourceIdentifier: node.sourceIdentifier,\n contentSource: node.content,\n });\n } else if (node.kind === 'linkDef') {\n linkDefs.set(node.label, { identifier: node.label, url: node.url, title: node.title });\n }\n }\n const fp = JSON.stringify({\n r: refs,\n d: Array.from(defMeta.entries()).map(([k, v]) => [k, v.sourceIdentifier, v.contentSource]),\n l: Array.from(linkDefs.entries()).map(([k, v]) => [k, v.url, v.title ?? '']),\n ofn: Array.from(ownLabels.footnoteLabels).sort(),\n ol: Array.from(ownLabels.linkLabels).sort(),\n // Include targetPhantoms in the fingerprint: a phantom→resolved\n // transition (another chunk publishes a def for a label this chunk\n // references inside one of its OWN def bodies) changes the rendered\n // hast — the `<cross-chunk-link>` / `<cross-chunk-image>` placeholder\n // disappears and a real `<a>` / `<img>` takes its place — without\n // touching this chunk's refs / defMeta / linkDefs / ownLabels. Without\n // including the phantom snapshot in the fingerprint, the fp check\n // would short-circuit and the registry would keep stale bodyHast\n // forever, leaving the aggregate footer rendering the placeholder\n // long after the label was resolved.\n tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),\n tpl: Array.from(targetPhantoms.missingLinks).sort(),\n });\n if (\n lastContributionRef.current?.registry === registry &&\n lastContributionRef.current.symbol === sym &&\n lastContributionRef.current.fp === fp\n ) {\n return;\n }\n // Fingerprint changed → harvest bodyHast from the post-pipeline hast\n // and publish. Missing entries are defensive: after allocation,\n // preserveForBodyHarvest keeps real local defs in the synthetic footer\n // even when visible orphan rendering is disabled.\n const bodiesByLabel = extractDefBodiesFromHast(hast, clobberPrefix);\n const defs = new Map<\n string,\n { identifier: string; sourceIdentifier: string; contentSource: string; bodyHast: HastElementContent[] }\n >();\n for (const [label, meta] of defMeta) {\n defs.set(label, {\n identifier: meta.identifier,\n sourceIdentifier: meta.sourceIdentifier,\n contentSource: meta.contentSource,\n bodyHast: (bodiesByLabel.get(label) ?? []) as HastElementContent[],\n });\n }\n lastContributionRef.current = { registry, symbol: sym, fp };\n registry.contributeChunkData(sym, {\n refs,\n defs,\n linkDefs,\n ownFootnoteLabels: ownLabels.footnoteLabels,\n ownLinkLabels: ownLabels.linkLabels,\n });\n }, [parsed, ownLabels, registry, targetPhantoms, sym, hast, clobberPrefix]);\n\n // Intentional cache memoization via cacheRef; see G3 comment above.\n const rendered = renderBlocksWithCache(cacheRef, built.plan, built.globalCtx, postOptions);\n\n // React keys come from buildBlocks:\n // - `block-${hastOffset}` for cacheable blocks (the hast element's own\n // source offset, NOT the mdast offset — this is what makes multi-root\n // raw HTML produce unique keys when two hast siblings share one mdast\n // html node)\n // - `__footnote_section__` for the synthetic footnote section (fixed\n // literal lets its fiber state survive toggle T1→T2→T3)\n // - `inline-${offset}` for top-level whitespace / sanitized comments,\n // falling back to `inline-i${planIndex}` if the inline has no position\n // In coordinated mode, the per-chunk synthetic `<section data-footnotes>`\n // is suppressed by renderBlocksWithCache (postOptions.registry present).\n // Render the aggregate footer here so it sits at the end of the LAST\n // chunk's output. The component is a no-op when this chunk is not last.\n return (\n <ChunkSymbolContext.Provider value={sym}>\n {rendered.map(({ node, reactKey }) => (\n <Fragment key={reactKey}>{node}</Fragment>\n ))}\n {registry && sym ? (\n <AggregateFootnotesIfLast\n registry={registry}\n thisChunkSym={sym}\n clobberPrefix={clobberPrefix}\n postOptions={postOptions}\n preserveOrphanReferences={effectivePreserveOrphan}\n />\n ) : null}\n </ChunkSymbolContext.Provider>\n );\n }\n);\nBlockMemoizedRenderer.displayName = 'BlockMemoizedRenderer';\n\n/**\n * Legacy render path. Mounted when `config.blockMemoEnabled === false`.\n * Calls the vendored `<Markdown>` directly — every render runs the full\n * pipeline end-to-end with no cross-frame reuse. Output is byte-identical\n * to the block-memo path in standalone mode (validated by\n * `byteEquivalence.test.tsx`).\n *\n * **Cross-chunk coordination (Phase 11) is NOT wired through this path.**\n * Wrapping `<AIMarkdown>` with `<AIMarkdownDocuments>` while keeping\n * `blockMemoEnabled: false` silently runs without coordination — orphan\n * defs are not protected, refs across chunks don't resolve. If you need\n * cross-chunk behavior, keep `blockMemoEnabled: true` (the default).\n */\nconst LegacyRenderer = memo(\n ({ content, usedComponents, remarkPlugins, rehypePlugins, remarkRehypeOptions }: RendererProps) => (\n <Markdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={remarkRehypeOptions}\n components={usedComponents}\n >\n {content}\n </Markdown>\n )\n);\nLegacyRenderer.displayName = 'LegacyRenderer';\n\n/**\n * Internal component that assembles the remark/rehype plugin chain based on\n * the current render config, then dispatches to either the block-memo\n * renderer or the legacy renderer based on `config.blockMemoEnabled`.\n */\nconst AIMarkdownContent = memo(({ content, customComponents }: AIMarkdownContentProps) => {\n const { config, clobberPrefix } = useAIMarkdownRenderState();\n\n // Resolve extra-syntax remark plugins and check if definition list HAST handlers are needed.\n const { extraSyntaxRemarkPlugins, enableDefinitionList } = useMemo(\n () => ({\n extraSyntaxRemarkPlugins: config.extraSyntaxSupported.map((syntax) => ExtraSyntaxRemarkPluginMap[syntax]),\n enableDefinitionList: config.extraSyntaxSupported.includes(AIMarkdownRenderExtraSyntax.DEFINITION_LIST),\n }),\n [config.extraSyntaxSupported]\n );\n\n const displayOptimizeRemarkPlugins = useMemo(() => {\n return config.displayOptimizeAbilities.map((ability) => DisplayOptimizeRemarkPluginMap[ability]);\n }, [config.displayOptimizeAbilities]);\n\n const usedComponents = useMemo(() => {\n return customComponents ? { ...DefaultCustomComponents, ...customComponents } : DefaultCustomComponents;\n }, [customComponents]);\n\n // Stable plugin/options arrays so this component's React.memo wrapper can\n // skip re-renders when only the parent re-rendered. The vendored\n // `parseStage` rebuilds the unified processor on every call regardless —\n // there is no internal processor cache to feed.\n const remarkPlugins = useMemo<RemarkPlugins>(\n () => [\n // --- Core plugins (always active) ---\n remarkGfm,\n [\n remarkMath,\n {\n // Disable single-dollar inline math to avoid conflicts with currency\n // signs and other dollar usages; the preprocessor converts $...$ to $$...$$.\n singleDollarTextMath: false,\n },\n ],\n // --- Configurable extra syntax plugins ---\n ...extraSyntaxRemarkPlugins,\n // --- Formatting & normalization ---\n remarkBreaks,\n remarkEmoji,\n remarkSqueezeParagraphs,\n remarkCjkFriendly,\n remarkCjkFriendlyGfmStrikethrough,\n // --- Configurable display optimizations ---\n ...displayOptimizeRemarkPlugins,\n ],\n [extraSyntaxRemarkPlugins, displayOptimizeRemarkPlugins]\n );\n\n const rehypePlugins = useMemo<RehypePlugins>(\n () => [\n // Allow raw HTML through so rehype-sanitize can handle it.\n [rehypeRaw, { passThrough: [] }],\n // Sanitize HTML while allowing <mark> (highlight) and KaTeX class names.\n // Override `clobberPrefix` with the instance-scoped value so every id\n // and clobberable attribute is namespaced to this `<AIMarkdown>` instance.\n [rehypeSanitize, { ...sanitizeSchema, clobberPrefix }],\n // Normalize the auto-generated `<section data-footnotes>`: strip the\n // sr-only `<h2>Footnotes</h2>` label and prepend `<hr>`. Keeps standalone\n // single-doc rendering visually consistent with the cross-chunk aggregate\n // footer (which builds the same shape from scratch).\n rehypeFooterAdorn,\n // Re-prefix intra-document hash hrefs so they match the ids that\n // rehype-sanitize just clobbered. Must use the SAME prefix as the schema\n // above — that's why both read from `clobberPrefix`.\n [rehypeRebaseHashLinks, { prefix: clobberPrefix }],\n rehypeKatex,\n rehypeUnwrapImages,\n ],\n [clobberPrefix]\n );\n\n const remarkRehypeOptions = useMemo<RemarkRehypeOptions>(\n () => ({\n allowDangerousHtml: true,\n // Suppress mdast-util-to-hast's `user-content-` prefix on footnote\n // ids/hrefs; rehype-sanitize will apply the same prefix downstream\n // and `rehypeRebaseHashLinks` mirrors it onto matching hash hrefs.\n // Without this, ids would end up double-prefixed\n // (`user-content-user-content-fn-x`).\n clobberPrefix: '',\n handlers: {\n // Inject definition-list HAST handlers when the extension is active.\n ...(enableDefinitionList ? defListHastHandlers : {}),\n },\n }),\n [enableDefinitionList]\n );\n\n const Renderer = config.blockMemoEnabled ? BlockMemoizedRenderer : LegacyRenderer;\n return (\n <Renderer\n content={content}\n usedComponents={usedComponents}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={remarkRehypeOptions}\n />\n );\n});\n\nAIMarkdownContent.displayName = 'AIMarkdownContent';\n\nexport default AIMarkdownContent;\n","/**\n * Synchronous Markdown component. Ported from react-markdown v10\n * (`Markdown` named/default export) and refactored to expose the pipeline as\n * three independently callable stages so callers can interpose between them\n * (notably the block-memo cache in `MarkdownContent`).\n *\n * Public stages:\n * - {@link parseStage} — `createProcessor` → `parse` → raw mdast\n * - {@link transformStage} — `runSync` → final hast root\n * - {@link renderHastSubtree} — visit transform + `toJsxRuntime` on a hast tree or block\n *\n * The legacy synchronous {@link Markdown} export is preserved and now delegates\n * to those three stages so behavior matches react-markdown 1:1.\n *\n * @module components/markdown/Markdown\n */\n\nimport { unreachable } from 'devlop';\nimport { toJsxRuntime } from 'hast-util-to-jsx-runtime';\nimport type { Element, Root as HastRoot, RootContent } from 'hast';\nimport type { Root as MdastRoot } from 'mdast';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport type { Processor } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { VFile } from 'vfile';\nimport { createFile, createProcessor } from './processor';\nimport { buildTransform } from './transform';\nimport type { Deprecation, Options } from './types';\nimport { defaultUrlTransform } from './urlTransform';\n\nconst changelog = 'https://github.com/remarkjs/react-markdown/blob/main/changelog.md';\n\n/** Mirrors the deprecation table react-markdown ships — kept verbatim so error\n * messages and changelog hashes match upstream. */\nconst deprecations: ReadonlyArray<Readonly<Deprecation>> = [\n { from: 'astPlugins', id: 'remove-buggy-html-in-markdown-parser' },\n { from: 'allowDangerousHtml', id: 'remove-buggy-html-in-markdown-parser' },\n {\n from: 'allowNode',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'allowElement',\n },\n {\n from: 'allowedTypes',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'allowedElements',\n },\n { from: 'className', id: 'remove-classname' },\n {\n from: 'disallowedTypes',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'disallowedElements',\n },\n { from: 'escapeHtml', id: 'remove-buggy-html-in-markdown-parser' },\n { from: 'includeElementIndex', id: '#remove-includeelementindex' },\n {\n from: 'includeNodeIndex',\n id: 'change-includenodeindex-to-includeelementindex',\n },\n { from: 'linkTarget', id: 'remove-linktarget' },\n { from: 'plugins', id: 'change-plugins-to-remarkplugins', to: 'remarkPlugins' },\n { from: 'rawSourcePos', id: '#remove-rawsourcepos' },\n { from: 'renderers', id: 'change-renderers-to-components', to: 'components' },\n { from: 'source', id: 'change-source-to-children', to: 'children' },\n { from: 'sourcePos', id: '#remove-sourcepos' },\n { from: 'transformImageUri', id: '#add-urltransform', to: 'urlTransform' },\n { from: 'transformLinkUri', id: '#add-urltransform', to: 'urlTransform' },\n];\n\n/**\n * Validate options that have nothing to do with the input markdown — kept\n * separate so the block-memo wrapper can validate once per render rather than\n * once per block-render call.\n */\nfunction validateOptions(options: Readonly<Options>): void {\n for (const deprecation of deprecations) {\n if (Object.hasOwn(options, deprecation.from)) {\n unreachable(\n 'Unexpected `' +\n deprecation.from +\n '` prop, ' +\n (deprecation.to ? 'use `' + deprecation.to + '` instead' : 'remove it') +\n ' (see <' +\n changelog +\n '#' +\n deprecation.id +\n '> for more info)'\n );\n }\n }\n\n if (options.allowedElements && options.disallowedElements) {\n unreachable('Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other');\n }\n}\n\n/** Bundled processor + parsed mdast + VFile, ready to feed `transformStage`. */\nexport interface ParsedMarkdown {\n processor: Processor<MdastRoot, MdastRoot, HastRoot, undefined, undefined>;\n file: VFile;\n mdast: MdastRoot;\n}\n\n/**\n * Stage 1: validate options, build the unified processor, parse the markdown\n * source into raw (pre-transform) mdast. The returned `mdast` is mutated in\n * place by remark plugins during {@link transformStage}, but its top-level\n * `position` offsets remain valid keys for hast→mdast lookup.\n */\nexport function parseStage(options: Readonly<Options>): ParsedMarkdown {\n validateOptions(options);\n const processor = createProcessor(options);\n const file = createFile(options);\n const mdast = processor.parse(file);\n return { processor, file, mdast };\n}\n\n/**\n * Stage 2: run remark transformers, remark-rehype, and rehype plugins. Returns\n * the final hast Root. The mdast in {@link ParsedMarkdown} may be mutated\n * by remark transformers as a side effect of this call.\n */\nexport function transformStage(parsed: ParsedMarkdown): HastRoot {\n return parsed.processor.runSync(parsed.mdast, parsed.file);\n}\n\n/**\n * Stage 3: apply the hast visit transform (urlTransform, allow/disallow\n * filters, raw HTML handling) and render via `hast-util-to-jsx-runtime`.\n *\n * Accepts either the full hast Root or a single top-level child (typed as\n * `RootContent` to match hast's union of element/text/comment/etc.). When\n * given a single child, the child is wrapped in a synthetic Root so the\n * splice-based filters (`unwrapDisallowed`) have a parent context to work\n * against.\n *\n * Note: the visit transform mutates the input tree in place. For the legacy\n * `<Markdown>` flow this is harmless (the tree is freshly produced). For the\n * block-memo flow, hast is also fresh per render, so callers do not need to\n * defensively clone.\n */\nexport function renderHastSubtree(tree: HastRoot | RootContent, options: Readonly<Options>): ReactNode {\n const root: HastRoot = tree.type === 'root' ? tree : { type: 'root', children: [tree] };\n\n visit(\n root,\n buildTransform({\n allowedElements: options.allowedElements,\n allowElement: options.allowElement,\n disallowedElements: options.disallowedElements,\n skipHtml: options.skipHtml,\n unwrapDisallowed: options.unwrapDisallowed,\n urlTransform: options.urlTransform || defaultUrlTransform,\n })\n );\n\n return toJsxRuntime(root, {\n Fragment,\n components: options.components,\n ignoreInvalidStyle: true,\n jsx,\n jsxs,\n passKeys: true,\n passNode: true,\n });\n}\n\n/**\n * Render a markdown string to React elements.\n *\n * Mirrors `react-markdown`'s synchronous `<Markdown>` exactly: same prop\n * shape, same plugin pipeline (remark-parse → remarkPlugins → remark-rehype →\n * rehypePlugins → toJsxRuntime), same deprecation errors. Use this directly\n * via the local barrel; outside callers should keep using `<AIMarkdown>`.\n */\nexport function Markdown(options: Readonly<Options>): ReactElement {\n const parsed = parseStage(options);\n const tree = transformStage(parsed);\n return renderHastSubtree(tree, options) as ReactElement;\n}\n\nexport default Markdown;\n\n// Re-export for typing convenience at call sites that hold onto a single\n// top-level hast block.\nexport type { Element as HastElement, HastRoot, RootContent as HastChild };\n","/**\n * Unified processor and VFile setup. Ported 1:1 from react-markdown\n * v10 `createProcessor` and `createFile`.\n *\n * @module components/markdown/processor\n */\n\nimport { unreachable } from 'devlop';\nimport type { Root as HastRoot } from 'hast';\nimport type { Root as MdastRoot } from 'mdast';\nimport remarkParse from 'remark-parse';\nimport remarkRehype, { type Options as RemarkRehypeOptions } from 'remark-rehype';\nimport { type PluggableList, type Processor, unified } from 'unified';\nimport { VFile } from 'vfile';\nimport type { Options } from './types';\n\nconst emptyPlugins: PluggableList = [];\nconst emptyRemarkRehypeOptions: Readonly<RemarkRehypeOptions> = { allowDangerousHtml: true };\n\n/**\n * Build the unified processor: remark-parse → remarkPlugins → remark-rehype →\n * rehypePlugins. Returns an unfrozen processor — caller is expected to call\n * `.parse()` and `.runSync()` (or `.run()`) on it.\n */\nexport function createProcessor(\n options: Readonly<Options>\n): Processor<MdastRoot, MdastRoot, HastRoot, undefined, undefined> {\n const rehypePlugins = options.rehypePlugins || emptyPlugins;\n const remarkPlugins = options.remarkPlugins || emptyPlugins;\n const remarkRehypeOptions = options.remarkRehypeOptions\n ? { ...options.remarkRehypeOptions, ...emptyRemarkRehypeOptions }\n : emptyRemarkRehypeOptions;\n\n return unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, remarkRehypeOptions).use(rehypePlugins);\n}\n\n/**\n * Wrap the markdown string in a VFile so plugins that consume `file.value`\n * work. Mirrors react-markdown: in dev `unreachable` throws an AssertionError\n * for non-string `children`; in prod it silently no-ops, leaving `file.value`\n * undefined and unified treating the input as empty.\n */\nexport function createFile(options: Readonly<Options>): VFile {\n const children = options.children || '';\n const file = new VFile();\n\n if (typeof children === 'string') {\n file.value = children;\n } else {\n unreachable('Unexpected value `' + String(children) + '` for `children` prop, expected `string`');\n }\n\n return file;\n}\n","/**\n * Single-pass hast tree transform: rewrites raw HTML, runs `urlTransform` on\n * URL attributes, and applies `allowedElements` / `disallowedElements` /\n * `allowElement` filters. Ported 1:1 from react-markdown v10.\n *\n * @module components/markdown/transform\n */\n\nimport type { Element, Root } from 'hast';\nimport { urlAttributes } from 'html-url-attributes';\nimport type { BuildVisitor } from 'unist-util-visit';\nimport type { AllowElement, UrlTransform } from './types';\n\nexport interface TransformContext {\n allowedElements: ReadonlyArray<string> | null | undefined;\n allowElement: AllowElement | null | undefined;\n disallowedElements: ReadonlyArray<string> | null | undefined;\n skipHtml: boolean | null | undefined;\n unwrapDisallowed: boolean | null | undefined;\n urlTransform: UrlTransform;\n}\n\nexport function buildTransform(ctx: TransformContext): BuildVisitor<Root> {\n return function transform(node, index, parent) {\n if (node.type === 'raw' && parent && typeof index === 'number') {\n if (ctx.skipHtml) {\n parent.children.splice(index, 1);\n } else {\n parent.children[index] = { type: 'text', value: (node as { value: string }).value };\n }\n return index;\n }\n\n if (node.type === 'element') {\n const element = node as Element;\n let key: string;\n\n for (key in urlAttributes) {\n if (Object.hasOwn(urlAttributes, key) && Object.hasOwn(element.properties, key)) {\n const value = element.properties[key];\n const test = (urlAttributes as Record<string, ReadonlyArray<string> | null>)[key];\n if (test === null || test.includes(element.tagName)) {\n element.properties[key] = ctx.urlTransform(String(value || ''), key, element);\n }\n }\n }\n }\n\n if (node.type === 'element') {\n const element = node as Element;\n let remove = ctx.allowedElements\n ? !ctx.allowedElements.includes(element.tagName)\n : ctx.disallowedElements\n ? ctx.disallowedElements.includes(element.tagName)\n : false;\n\n if (!remove && ctx.allowElement && typeof index === 'number') {\n remove = !ctx.allowElement(element, index, parent);\n }\n\n if (remove && parent && typeof index === 'number') {\n if (ctx.unwrapDisallowed && element.children) {\n parent.children.splice(index, 1, ...element.children);\n } else {\n parent.children.splice(index, 1);\n }\n return index;\n }\n }\n\n return undefined;\n };\n}\n","/**\n * Default URL transform — same allowlist as react-markdown / GitHub.\n *\n * @module components/markdown/urlTransform\n */\n\nimport type { UrlTransform } from './types';\n\nconst safeProtocol = /^(https?|ircs?|mailto|xmpp)$/i;\n\n/**\n * Make a URL safe.\n *\n * Allows `http`, `https`, `irc`, `ircs`, `mailto`, and `xmpp` protocols, plus\n * URLs relative to the current protocol (e.g. `/foo`). Other protocols are\n * stripped to the empty string. Mirrors GitHub's behaviour and matches\n * `micromark-util-sanitize-uri` minus the URL-encoding pass.\n */\nexport const defaultUrlTransform: UrlTransform = (value) => {\n const colon = value.indexOf(':');\n const questionMark = value.indexOf('?');\n const numberSign = value.indexOf('#');\n const slash = value.indexOf('/');\n\n if (\n // No protocol → relative.\n colon === -1 ||\n // First colon is after `/`, `?`, or `#` → not a protocol.\n (slash !== -1 && colon > slash) ||\n (questionMark !== -1 && colon > questionMark) ||\n (numberSign !== -1 && colon > numberSign) ||\n // Allowed protocol.\n safeProtocol.test(value.slice(0, colon))\n ) {\n return value;\n }\n\n return '';\n};\n","/**\n * Builds the `rehype-sanitize` schema used by {@link MarkdownContent}.\n *\n * Extracted into its own module so the merge logic can be unit-tested in\n * isolation without pulling in React or the full markdown pipeline.\n *\n * @module components/sanitizeSchema\n */\n\nimport { defaultSchema } from 'rehype-sanitize';\n\ntype Schema = typeof defaultSchema;\ntype AttributeEntry = NonNullable<NonNullable<Schema['attributes']>[string]>[number];\n\n/**\n * Extend the allowlist for a tag's `className` attribute with extra class\n * names while preserving all other default entries.\n *\n * `findDefinition` in hast-util-sanitize returns the *first* matching entry\n * for a given property name, so appending a second `className` entry would be\n * ignored. Instead, merge the allowed values into the existing entry.\n *\n * Edge cases:\n * - `existing` is `undefined` → returns a single new `['className', ...extra]`\n * - `existing` has no `className` entry → appends one with just the extras\n * - `existing` has a bare-string `'className'` entry (hast-util-sanitize's\n * \"allow all values\" form) → would be narrowed to an allow-list. This is a\n * semantics change, but the current `defaultSchema.attributes.code` entry\n * is always tuple-form, so this branch is defensive only.\n */\nexport function mergeClassNameAllowlist(\n existing: ReadonlyArray<AttributeEntry> | undefined,\n extraClassNames: readonly string[]\n): AttributeEntry[] {\n const entries: AttributeEntry[] = existing ? [...existing] : [];\n const idx = entries.findIndex((entry) =>\n typeof entry === 'string' ? entry === 'className' : entry[0] === 'className'\n );\n if (idx === -1) {\n return [...entries, ['className', ...extraClassNames]];\n }\n const current = entries[idx];\n const merged: AttributeEntry =\n typeof current === 'string' ? ['className', ...extraClassNames] : [...current, ...extraClassNames];\n entries[idx] = merged;\n return entries;\n}\n\nconst crossChunkTags = ['cross-chunk-link', 'cross-chunk-image', 'footnote-sup'] as const;\n\n/**\n * The full sanitize schema used by the markdown renderer: extends\n * `defaultSchema` to allow `<mark>`, the KaTeX math class names, and the\n * three custom hast tags emitted by cross-chunk coordination handlers.\n */\nexport const sanitizeSchema: Schema = {\n ...defaultSchema,\n tagNames: [...(defaultSchema.tagNames || []), 'mark', ...crossChunkTags],\n attributes: {\n ...defaultSchema.attributes,\n code: mergeClassNameAllowlist(defaultSchema.attributes?.code, ['math-inline', 'math-display']),\n 'cross-chunk-link': ['label', 'referenceType', 'documentId'],\n 'cross-chunk-image': ['label', 'referenceType', 'documentId', 'alt'],\n 'footnote-sup': ['label', 'localOccurrence', 'documentId'],\n },\n};\n","/**\n * `rehypeRebaseHashLinks` — restore intra-document hash navigation after\n * `rehype-sanitize` clobbers `id` attributes.\n *\n * ### Why this exists\n *\n * `rehype-sanitize` defends against ID-clobbering attacks (e.g. a malicious\n * `<div id=\"window\">` shadowing `window.window`) by prefixing every clobberable\n * attribute (`id`, `name`, `aria-describedby`, `aria-labelledby`) with\n * `clobberPrefix` (default `'user-content-'`). It does **not** rewrite `href`\n * values, since hashes are not themselves clobbering vectors. As a result,\n * any intra-document link — `[ref](#section)`, GFM footnote anchors, or raw\n * `<a id=\"x\"><a href=\"#x\">` pairs — points at an unprefixed hash while its\n * target id has been prefixed: navigation breaks.\n *\n * Pair this plugin with `remarkRehypeOptions: { clobberPrefix: '' }` so that\n * `mdast-util-to-hast` does not also prefix (avoiding `user-content-user-content-`\n * double prefixes), and place it **after** `rehype-sanitize` in the rehype\n * pipeline. The result mirrors GitHub's rendering: a single, consistent\n * `user-content-` prefix on every id and matching hash href.\n *\n * @module components/rehypeRebaseHashLinks\n */\n\nimport type { Root } from 'hast';\nimport type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\n\nconst DEFAULT_PREFIX = 'user-content-';\n\nexport interface RehypeRebaseHashLinksOptions {\n /** Prefix to apply. Must match the `clobberPrefix` used by `rehype-sanitize`. */\n prefix?: string;\n}\n\nconst rehypeRebaseHashLinks: Plugin<[RehypeRebaseHashLinksOptions?], Root> = (options) => {\n const prefix = options?.prefix ?? DEFAULT_PREFIX;\n const hashPrefix = '#' + prefix;\n return (tree) => {\n visit(tree, 'element', (node) => {\n if (node.tagName !== 'a') return;\n const href = node.properties?.href;\n if (typeof href !== 'string' || !href.startsWith('#')) return;\n if (href.startsWith(hashPrefix)) return;\n node.properties.href = hashPrefix + href.slice(1);\n });\n };\n};\n\nexport default rehypeRebaseHashLinks;\n","/**\n * Rehype plugin that normalizes the auto-generated footnote footer so its\n * shape matches the cross-chunk aggregate footer (rendered by\n * `AggregateFootnotesIfLast`).\n *\n * mdast-util-to-hast's default `state.footer()` emits:\n *\n * <section data-footnotes class=\"footnotes\">\n * <h2 id=\"...footnote-label\" class=\"sr-only\">Footnotes</h2>\n * <ol>...</ol>\n * </section>\n *\n * The aggregate footer used in coordinated mode (and which the user prefers\n * visually) emits:\n *\n * <section data-footnotes class=\"footnotes\">\n * <hr />\n * <ol>...</ol>\n * </section>\n *\n * Running this plugin on the parsed hast lets standalone single-doc\n * rendering produce the same structure as the aggregate, so a 1-chunk doc and\n * an N-chunk coordinated doc with identical content look the same.\n *\n * Operates only on `<section data-footnotes>` and is idempotent.\n *\n * @module components/rehypeFooterAdorn\n */\nimport { visit } from 'unist-util-visit';\nimport type { Element as HastElement, Root as HastRoot, ElementContent } from 'hast';\n\nconst FOOTNOTE_LABEL_ID_RE = /(?:^|-)footnote-label$/;\n\nfunction isFootnoteLabelH2(node: ElementContent): boolean {\n if (node.type !== 'element') return false;\n const el = node as HastElement;\n if (el.tagName !== 'h2') return false;\n const id = el.properties?.id;\n return typeof id === 'string' && FOOTNOTE_LABEL_ID_RE.test(id);\n}\n\nfunction isHr(node: ElementContent): boolean {\n if (node.type !== 'element') return false;\n return (node as HastElement).tagName === 'hr';\n}\n\nexport default function rehypeFooterAdorn() {\n return (tree: HastRoot) => {\n visit(tree, 'element', (n) => {\n const el = n as HastElement;\n if (el.tagName !== 'section') return;\n if (!(el.properties && 'dataFootnotes' in el.properties)) return;\n // Strip the auto-generated <h2 id=\"...footnote-label\"> — the visible\n // \"Footnotes\" header reads awkwardly, especially in streaming AI chat\n // contexts. To keep screen-reader announcement working, set\n // `aria-label=\"Footnotes\"` on the section landmark so assistive tech\n // still names the region.\n const filtered = el.children.filter((c) => !isFootnoteLabelH2(c)) as ElementContent[];\n // Prepend <hr> as the first child, unless one is already present.\n if (!filtered.some(isHr)) {\n const hr: HastElement = {\n type: 'element',\n tagName: 'hr',\n properties: {},\n children: [],\n };\n filtered.unshift(hr);\n }\n el.children = filtered;\n if (!el.properties) el.properties = {};\n if (!('ariaLabel' in el.properties)) {\n el.properties.ariaLabel = 'Footnotes';\n }\n });\n };\n}\n","/**\n * Block-level memoization for streaming markdown.\n *\n * A single unified parse produces both an mdast (for syntax-level ctx like\n * footnote / link / image references) and a hast (the actual render input).\n * `buildBlocks` cuts the hast into per-block units 1:1 with hast top-level\n * children that have an mdast counterpart, plus an optional synthetic\n * footnote section. `renderBlocksWithCache` then memoizes each block by\n * `(raw, occurrence index, ctx, startOffset)` so cached blocks skip the\n * downstream `toJsxRuntime` + React reconcile work.\n *\n * Design contract is in `/tmp/phase5-block-memo-decisions.md`. Read it before\n * touching any of the invariants in this file.\n *\n * @module components/blockMemo\n */\n\nimport type { Element as HastElement, Root as HastRoot, RootContent as HastChild } from 'hast';\nimport type { Root as MdastRoot, RootContent as MdastContent, Nodes as MdastNodes } from 'mdast';\nimport type { ReactNode } from 'react';\nimport { visit } from 'unist-util-visit';\nimport { renderHastSubtree, type Options } from './markdown';\nimport { normalizeId } from './normalizeId';\nimport type { Registry } from './documentRegistry';\n\n/**\n * mdast types whose presence in a block makes that block dependent on\n * cross-block syntax (footnote/link/image references and definitions).\n * Tainted blocks invalidate via the document `globalCtx` digest; non-tainted\n * blocks invalidate only on raw + position change.\n */\nconst TAINT_TYPES: ReadonlySet<string> = new Set([\n 'footnoteReference',\n 'footnoteDefinition',\n 'linkReference',\n 'imageReference',\n 'definition',\n]);\n\n/**\n * mdast types that contribute to the document-wide `globalCtx` digest.\n * Currently identical to {@link TAINT_TYPES} — refs/defs are simultaneously\n * \"things that make a block tainted\" and \"things that change a tainted\n * block's render output\". Kept as a separate constant so the two roles can\n * diverge later (e.g. a future plugin that introduces a new node type which\n * is a ctx contributor but not a per-block taint source).\n */\nconst CTX_TYPES: ReadonlySet<string> = TAINT_TYPES;\n\n/**\n * Subset of {@link Options} consumed by per-block rendering — i.e. everything\n * except the pipeline plugins (those have already run by the time we reach\n * `renderHastSubtree`). Marked Readonly to discourage callers from mutating\n * the captured options reference between frames.\n */\nexport interface PostOptions extends Readonly<Options> {\n /** Required for cross-chunk coordination. Provided by AIMarkdownContent\n * when wrapped in <AIMarkdownDocuments>; undefined in standalone mode. */\n registry?: Registry;\n /** Required when registry is set. Per-chunk Symbol; used by fingerprint\n * to encode canonical-vs-this comparison. */\n thisChunkSymbol?: symbol;\n /** Required when registry is set. From useAIMarkdownRenderState; entered\n * into fingerprint so id/href prefix changes invalidate the cache. */\n clobberPrefix?: string;\n}\n\n/** Source-level identity of one renderable hast block. */\nexport interface BlockInfo {\n raw: string;\n startOffset: number;\n endOffset: number;\n /**\n * Line and column at the block's start. Tracked alongside `startOffset`\n * because two different source documents can produce the same byte offset\n * for the \"same\" content (`A\\n\\nB\\n\\nTarget` vs `ABCD\\n\\nTarget` — both\n * have `Target` starting at offset 6 but on different lines). Custom\n * components that read `node.position.start.line` would otherwise see\n * stale data from a false-positive cache hit.\n */\n startLine: number;\n startColumn: number;\n /** True if the block contains any TAINT_TYPES node — invalidate on globalCtx change. */\n hasReference: boolean;\n /** TAINT-block 专属:按节点类型分桶的 label set。Normalized 形态(uppercase)。\n * Undefined when hasReference === false. */\n taintLabels?: {\n footnoteRefLabels: string[];\n linkRefLabels: string[];\n imageRefLabels: string[];\n footnoteDefLabels: string[];\n };\n}\n\n/** Cache entry for one rendered block. */\nexport interface BlockCacheEntry {\n node: ReactNode;\n /** `globalCtx` digest if the block is tainted, '' otherwise. Sentinel collapses both code paths. */\n ctx: string;\n /** Position triple — must all match for the cached node to be valid. */\n startOffset: number;\n startLine: number;\n startColumn: number;\n}\n\n/** Cache entry for the synthesized footnote section (single slot, keyed by globalCtx). */\nexport interface FootnoteSectionEntry {\n ctx: string;\n node: ReactNode;\n}\n\n/**\n * Per-instance memo state.\n *\n * ## Memory characteristics\n *\n * The cache holds one `ReactNode` reference per live block in the current\n * document plus an optional single slot for the synthesized footnote\n * section. Memory therefore scales linearly with document size, NOT with\n * session duration: every frame's render produces a fresh `next` Cache, and\n * the previous frame's Cache is atomically replaced (orphaned for GC).\n * Blocks that disappear between frames are dropped from the cache the same\n * frame they vanish from the document.\n *\n * For typical AI chat (≤ 1000 blocks per response, individual ReactNode\n * trees in the low-KB range), per-instance memory stays comfortably below\n * ~10 MB. If you build a UI that keeps very long single-document instances\n * alive indefinitely (≥ 10k live blocks), consider mounting on a virtual\n * scroll boundary so blocks above the fold can unmount and release their\n * cached subtrees.\n */\nexport interface Cache {\n /** raw → bucket of entries indexed by occurrence within the document. */\n blocks: Map<string, BlockCacheEntry[]>;\n /** Synthesized footnote section, if the previous frame produced one. */\n footnoteSection?: FootnoteSectionEntry;\n}\n\n/** Build a fresh, empty Cache. */\nexport function createCache(): Cache {\n return { blocks: new Map() };\n}\n\n/**\n * Slice the source string for the given mdast node's position. mdast nodes\n * produced by remark-parse always carry `position`; the empty-string fallback\n * is purely defensive.\n */\nfunction extractRaw(node: MdastNodes, source: string): string {\n if (!node.position) return '';\n return source.slice(node.position.start.offset, node.position.end.offset);\n}\n\n/**\n * Detect mdast-util-to-hast's synthesized footnote `<section data-footnotes>`.\n * Position-based detection alone would be too broad — any future rehype plugin\n * that appends a position-less node would be misclassified. We assert by\n * `tagName === 'section'` AND presence of the `dataFootnotes` property.\n */\nexport function isFootnoteSection(node: HastElement): boolean {\n if (node.tagName !== 'section') return false;\n const props = node.properties as Record<string, unknown> | undefined;\n return props?.dataFootnotes !== undefined;\n}\n\n/** Dev invariant: every block hast child must retain its mdast `position`. */\nexport function hasMdastSource(node: HastElement): boolean {\n return node.position !== undefined;\n}\n\n/**\n * One step of the document render plan, in source order.\n *\n * The plan covers EVERY top-level hast child so that {@link renderBlocksWithCache}\n * can preserve react-markdown's byte-equivalent output — including the whitespace\n * `text` nodes that `mdast-util-to-hast` inserts between block elements.\n *\n * - `block`: a hast element with an mdast counterpart, eligible for caching by\n * `(raw, occurrence index, ctx, startOffset)`.\n * - `inline`: a non-element top-level child (whitespace text, comment, …) or\n * an element that has no mdast counterpart but is still safe to render.\n * These are rendered every frame without caching — they are typically\n * single whitespace characters.\n * - `synthetic`: the synthesized footnote `<section data-footnotes>`, cached\n * in a single slot keyed by `globalCtx`.\n */\nexport type RenderItem =\n | { kind: 'block'; el: HastElement; reactKey: string; info: BlockInfo }\n | { kind: 'inline'; el: HastChild; reactKey: string }\n | { kind: 'synthetic'; el: HastElement; reactKey: string };\n\n/** Result of {@link buildBlocks}. */\nexport interface BuildBlocksResult {\n /** Render plan in document order — drives {@link renderBlocksWithCache}. */\n plan: RenderItem[];\n /** JSON-stringified ordered list of TAINT-typed nodes in document order. */\n globalCtx: string;\n // ── Derived views (kept for tests and convenience) ─────────────────────\n /** Flat list of `BlockInfo` for cacheable blocks, in document order. */\n blocks: BlockInfo[];\n /** 1:1 with `blocks` — the hast Element each BlockInfo refers to. */\n blockHasts: HastElement[];\n /** Synthesized footnote section, if present. */\n synthetic?: HastElement;\n}\n\n/** A single rendered output item with its stable React key. */\nexport interface RenderedItem {\n node: ReactNode;\n reactKey: string;\n}\n\nconst FOOTNOTE_SECTION_KEY = '__footnote_section__';\n\n/**\n * Build the document render plan + ctx digest from a parsed mdast and its\n * rendered hast.\n *\n * Plan construction is driven by `hast.children` (NOT `mdast.children`):\n * pipeline transformers like `remarkSqueezeParagraphs` and\n * `remarkRemoveComments` drop blocks, so the rendered hast may have fewer\n * top-level children than the parsed mdast. Driving by hast guarantees the\n * plan covers exactly what will be rendered.\n *\n * Each hast top-level child becomes one plan item:\n * - `<section data-footnotes>` → `synthetic` (cached in a single slot)\n * - element with mdast counterpart → `block` (cacheable by raw + occurrence + ctx + offset)\n * - text / comment / element-without-counterpart → `inline` (rendered fresh every frame)\n *\n * The mdast counterpart of a block element is found by source offset using\n * a two-tier lookup: an exact-offset Map (mdast-util-to-hast's default 1:1\n * propagation), then range-containment `findLast` fallback for cases like\n * `rehype-raw` splitting one mdast `html` node into multiple hast siblings\n * (e.g. ` <div>Hi</div>` — leading spaces shift the `<div>` offset\n * inside the parent html node's source range).\n *\n * In dev, a hast block whose offset matches no mdast counterpart at all\n * throws — that means a rehype plugin synthesized positions outside the\n * source range, which is a bug worth surfacing. In production it falls\n * through to an `inline` plan item so user content is never silently lost.\n *\n * `globalCtx` walks the full mdast for footnote/link/image refs and\n * definitions in document order (no dedupe — order matters for footnote\n * numbering), then JSON-stringifies the collected tuples. That string is the\n * invalidation key for tainted blocks and the synthetic footnote section.\n */\nexport function buildBlocks(mdast: MdastRoot, hast: HastRoot, source: string): BuildBlocksResult {\n const mdastByOffset = new Map<number, MdastContent>();\n // Sorted [start, end, node] table for the range-containment fallback used\n // when a hast block's offset is INSIDE an mdast node's source range\n // (`rehype-raw` splitting one mdast `html` node into multiple hast\n // siblings is the canonical case). Pre-sorted because mdast children come\n // out of remark-parse in source order; we collect positioned ones in\n // place, preserving order. Binary search at lookup time replaces the\n // previous O(N) `findLast` — without it, M hast blocks × N mdast children\n // degrades to O(N×M) on pathological streams with many splits.\n type Range = { start: number; end: number; node: MdastContent };\n const mdastRanges: Range[] = [];\n for (const child of mdast.children) {\n const off = child.position?.start.offset;\n const endOff = child.position?.end.offset;\n if (off !== undefined) {\n mdastByOffset.set(off, child);\n }\n if (off !== undefined && endOff !== undefined) {\n mdastRanges.push({ start: off, end: endOff, node: child });\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n for (let i = 1; i < mdastRanges.length; i++) {\n if (mdastRanges[i].start < mdastRanges[i - 1].start) {\n // Should never trip: mdast.children is source-order. If it does\n // trip, the binary search below is wrong — surface it loudly so\n // we sort defensively rather than silently misroute hast blocks.\n throw new Error(\n 'block-memo: mdast.children not sorted by source offset — ' +\n 'a remark plugin is reordering top-level children.'\n );\n }\n }\n }\n function findContainingMdast(offset: number): MdastContent | undefined {\n // Upper-bound binary search: find first index where range.start > offset.\n // The candidate is the immediate predecessor (largest start <= offset).\n let lo = 0;\n let hi = mdastRanges.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (mdastRanges[mid].start <= offset) lo = mid + 1;\n else hi = mid;\n }\n const idx = lo - 1;\n if (idx < 0) return undefined;\n const r = mdastRanges[idx];\n // Top-level mdast children have non-overlapping source ranges, so the\n // single largest-start candidate is the unique container (if any).\n return offset < r.end ? r.node : undefined;\n }\n\n const ctxParts: unknown[] = [];\n visit(mdast, (n) => {\n if (!CTX_TYPES.has(n.type)) return;\n if (n.type === 'footnoteReference') ctxParts.push(['fr', n.identifier]);\n else if (n.type === 'footnoteDefinition') ctxParts.push(['fd', n.identifier, extractRaw(n, source)]);\n else if (n.type === 'linkReference') ctxParts.push(['lr', n.identifier]);\n else if (n.type === 'imageReference') ctxParts.push(['ir', n.identifier]);\n else if (n.type === 'definition') ctxParts.push(['d', n.identifier, n.url, n.title ?? null]);\n });\n const globalCtx = JSON.stringify(ctxParts);\n\n const plan: RenderItem[] = [];\n const blocks: BlockInfo[] = [];\n const blockHasts: HastElement[] = [];\n let synthetic: HastElement | undefined;\n\n for (let i = 0; i < hast.children.length; i++) {\n const hastChild = hast.children[i];\n\n if (hastChild.type !== 'element') {\n // Top-level non-element child (whitespace text inserted by\n // mdast-util-to-hast between block elements, sanitized comment, …).\n // Render inline without caching to preserve byte-equivalent output.\n const off = hastChild.position?.start.offset;\n const reactKey = off !== undefined ? `inline-${off}` : `inline-i${i}`;\n plan.push({ kind: 'inline', el: hastChild, reactKey });\n continue;\n }\n\n const el = hastChild;\n\n if (isFootnoteSection(el)) {\n synthetic = el;\n plan.push({ kind: 'synthetic', el, reactKey: FOOTNOTE_SECTION_KEY });\n continue;\n }\n const hastOffset = el.position?.start.offset;\n if (hastOffset === undefined) {\n // Element without position (synthesized by some plugin) — preserve in\n // document order, rendered as inline (no cache key available).\n plan.push({ kind: 'inline', el, reactKey: `inline-i${i}` });\n continue;\n }\n\n let mdastNode = mdastByOffset.get(hastOffset);\n\n if (!mdastNode) {\n mdastNode = findContainingMdast(hastOffset);\n }\n\n if (!mdastNode) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `block-memo: hast block at offset ${hastOffset} has no mdast counterpart. ` +\n `A rehype plugin may have synthesized positions outside source. tagName=${el.tagName}`\n );\n }\n // Production fallback: render inline, no cache.\n plan.push({ kind: 'inline', el, reactKey: `inline-${hastOffset}` });\n continue;\n }\n\n if (mdastNode.type === 'footnoteDefinition') {\n // Footnote definitions are hoisted into the synthetic section by\n // mdast-util-to-hast — they should not appear as top-level hast blocks\n // in any current plugin chain. If the range fallback ever resolves an\n // unrelated hast block to a footnoteDefinition's mdast source range,\n // preserve it as `inline` rather than silently dropping it (defensive\n // parity with the other no-counterpart fallbacks above).\n plan.push({ kind: 'inline', el, reactKey: `inline-${hastOffset}` });\n continue;\n }\n\n let hasReference = false;\n const footnoteRefLabels: string[] = [];\n const linkRefLabels: string[] = [];\n const imageRefLabels: string[] = [];\n const footnoteDefLabels: string[] = [];\n visit(mdastNode, (n) => {\n if (!TAINT_TYPES.has(n.type)) return;\n hasReference = true;\n const id = 'identifier' in n ? normalizeId(String(n.identifier)) : null;\n if (id === null) return;\n if (n.type === 'footnoteReference') footnoteRefLabels.push(id);\n else if (n.type === 'linkReference') linkRefLabels.push(id);\n else if (n.type === 'imageReference') imageRefLabels.push(id);\n else if (n.type === 'footnoteDefinition') footnoteDefLabels.push(id);\n // 'definition' nodes don't carry per-block fingerprint significance\n // (they're metadata, not visible); intentionally not bucketed.\n });\n\n const mdastPos = mdastNode.position;\n if (!mdastPos || mdastPos.start.offset === undefined || mdastPos.end.offset === undefined) {\n continue;\n }\n\n const info: BlockInfo = {\n raw: extractRaw(mdastNode, source),\n startOffset: mdastPos.start.offset,\n endOffset: mdastPos.end.offset,\n startLine: mdastPos.start.line,\n startColumn: mdastPos.start.column,\n hasReference,\n ...(hasReference\n ? {\n taintLabels: { footnoteRefLabels, linkRefLabels, imageRefLabels, footnoteDefLabels },\n }\n : {}),\n };\n blocks.push(info);\n blockHasts.push(el);\n // React key is keyed off the HAST element's source offset (not the mdast\n // node's), because multi-root raw HTML produces multiple hast siblings\n // that share one mdast `html` node — same `mdastPos.start.offset` for\n // both, which would collide as a React key. Hast positions are unique\n // per element in the rendered tree.\n plan.push({ kind: 'block', el, info, reactKey: `block-${hastOffset}` });\n }\n\n return { plan, globalCtx, blocks, blockHasts, synthetic };\n}\n\n/**\n * Compute a per-block cache fingerprint from the registry slice this block\n * actually depends on (footnote/link/image refs and footnote defs). Two blocks\n * with the same fingerprint render byte-equal output; if any encoded value\n * differs, the block must re-render.\n *\n * Encoding format (deterministic, stable across versions):\n * `<clobberPrefix>|fn:<L>=<globalNumber>|lr:<L>=<url>|<title>|ir:<L>=<url>|fd:<L>=<canonical>/<refCount>`\n *\n * @param taintLabels - Per-block label dependency footprint (from BlockInfo.taintLabels).\n * @param registry - Shared cross-chunk registry.\n * @param thisChunkSym- The Symbol of the chunk this rendering belongs to (for canonical-vs-this comparison).\n * @param clobberPrefix - The documentId-derived id prefix; included so href/id changes invalidate.\n */\nexport function computeBlockFingerprint(\n taintLabels: NonNullable<BlockInfo['taintLabels']>,\n registry: Registry,\n thisChunkSym: symbol,\n clobberPrefix: string\n): string {\n const parts: string[] = [clobberPrefix];\n for (const label of taintLabels.footnoteRefLabels) {\n parts.push(`fn:${label}=${registry.globalNumber(label) ?? 'null'}`);\n }\n for (const label of taintLabels.linkRefLabels) {\n const def = registry.resolveLinkDef(label);\n parts.push(`lr:${label}=${def?.url ?? 'null'}|${def?.title ?? ''}`);\n }\n for (const label of taintLabels.imageRefLabels) {\n const def = registry.resolveLinkDef(label);\n parts.push(`ir:${label}=${def?.url ?? 'null'}|${def?.title ?? ''}`);\n }\n for (const label of taintLabels.footnoteDefLabels) {\n const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;\n parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);\n }\n return parts.join('|');\n}\n\n/**\n * Render the document plan with cache lookup + atomic Cache replacement.\n *\n * Cache identity for a `block` item is `(raw, occurrence index within bucket,\n * ctx, startOffset)`. ctx == globalCtx for tainted blocks, '' otherwise\n * (sentinel collapses both paths into one validation).\n *\n * The synthesized footnote section is a single-slot cache keyed by globalCtx.\n * Atomic Cache replacement (`cacheRef.current = next`) ensures stale slots\n * cannot leak across frames: when synthetic disappears in frame T2,\n * `next.footnoteSection` is left undefined and the old node is orphaned with\n * the rest of the previous Cache for GC.\n *\n * `inline` items (top-level whitespace text, sanitized comments, etc.) are\n * rendered every frame without caching — they are typically a single\n * character and would not benefit from memoization.\n */\nexport function renderBlocksWithCache(\n cacheRef: { current: Cache },\n plan: RenderItem[],\n globalCtx: string,\n postOptions: PostOptions\n): RenderedItem[] {\n const prev = cacheRef.current;\n const next: Cache = { blocks: new Map() };\n const rendered: RenderedItem[] = [];\n\n if (process.env.NODE_ENV !== 'production') {\n for (const item of plan) {\n if (item.kind === 'block' && !hasMdastSource(item.el)) {\n throw new Error(\n 'block-memo: block hast child has no position. Did a rehype plugin strip it? ' +\n '(Run positionPropagation.test.ts to verify.)'\n );\n }\n }\n }\n\n for (const item of plan) {\n if (item.kind === 'inline') {\n rendered.push({\n node: renderHastSubtree(item.el, postOptions),\n reactKey: item.reactKey,\n });\n continue;\n }\n\n if (item.kind === 'synthetic') {\n // Cross-chunk coordination: in coordinated mode (registry AND this chunk's\n // Symbol registered) the per-chunk local `<section data-footnotes>` is\n // replaced by `<AggregateFootnotesIfLast>` mounted at the end of each\n // document's last chunk. Skip the local synthetic to avoid duplicate\n // footers across chunks.\n //\n // The thisChunkSymbol guard preserves SSR semantics: during\n // `renderToStaticMarkup` useEffect doesn't fire, so the chunk hasn't\n // registered with the registry yet (`thisChunkSymbol` undefined). Falling\n // back to the local footer keeps each chunk's defs visible in the static\n // output — which is what `byteEquivalence.test.tsx` exercises and what\n // users doing SSR-without-hydration expect.\n if (postOptions.registry && postOptions.thisChunkSymbol) {\n continue;\n }\n // Standalone mode (or SSR pre-registration): cache the local section by\n // globalCtx and render it.\n const cached = prev.footnoteSection;\n let node: ReactNode;\n if (cached && cached.ctx === globalCtx) {\n node = cached.node;\n } else {\n node = renderHastSubtree(item.el, postOptions);\n }\n next.footnoteSection = { ctx: globalCtx, node };\n rendered.push({ node, reactKey: item.reactKey });\n continue;\n }\n\n // kind === 'block'\n const block = item.info;\n let bucket = next.blocks.get(block.raw);\n if (!bucket) {\n bucket = [];\n next.blocks.set(block.raw, bucket);\n }\n const occ = bucket.length;\n\n if (block.hasReference) {\n const useFingerprint =\n postOptions.registry &&\n block.taintLabels &&\n postOptions.thisChunkSymbol &&\n postOptions.clobberPrefix !== undefined;\n const blockCtx = useFingerprint\n ? computeBlockFingerprint(\n block.taintLabels!,\n postOptions.registry!,\n postOptions.thisChunkSymbol!,\n postOptions.clobberPrefix!\n )\n : globalCtx; // fallback: standalone mode pre-v6 behavior\n\n const entry = prev.blocks.get(block.raw)?.[occ];\n const valid =\n entry !== undefined &&\n entry.ctx === blockCtx &&\n entry.startOffset === block.startOffset &&\n entry.startLine === block.startLine &&\n entry.startColumn === block.startColumn;\n\n let node: ReactNode;\n if (valid) {\n node = entry.node; // cache hit: skip everything\n } else {\n // Coordinated-mode hast post-transforms used to run here, but the\n // aggregate footer (AggregateFootnotesIfLast) now reconstructs the\n // footnote section from registry state, and the synthetic plan item\n // for `<section data-footnotes>` is skipped earlier in this loop.\n // Regular blocks never contain a top-level footnote section, so a\n // post-transform pass would be a no-op anyway.\n node = renderHastSubtree(item.el, postOptions);\n }\n\n bucket.push({\n node,\n ctx: blockCtx,\n startOffset: block.startOffset,\n startLine: block.startLine,\n startColumn: block.startColumn,\n });\n rendered.push({ node, reactKey: item.reactKey });\n continue;\n }\n\n // Non-TAINT block: existing cache-by-(raw, occurrence, '', position) path\n {\n const entry = prev.blocks.get(block.raw)?.[occ];\n const valid =\n entry !== undefined &&\n entry.ctx === '' &&\n entry.startOffset === block.startOffset &&\n entry.startLine === block.startLine &&\n entry.startColumn === block.startColumn;\n const node = valid ? entry.node : renderHastSubtree(item.el, postOptions);\n bucket.push({\n node,\n ctx: '',\n startOffset: block.startOffset,\n startLine: block.startLine,\n startColumn: block.startColumn,\n });\n rendered.push({ node, reactKey: item.reactKey });\n }\n }\n\n cacheRef.current = next;\n return rendered;\n}\n","/**\n * CommonMark §4.7 label normalization. Used as the single canonical form\n * for all label-keyed structures (registry maps, phantomFootnoteLabels Set,\n * labelSet, etc.) and for handler comparisons against mdast-util-to-hast's\n * internal `state.definitionById` / `state.footnoteById` keys.\n *\n * Direction is uppercase to align with mdast-util-to-hast internals\n * (`String(identifier).toUpperCase()`). Direction is irrelevant once both\n * sides agree; uppercase chosen to match the upstream library to minimize\n * adapter calls.\n *\n * @module components/normalizeId\n */\nexport function normalizeId(s: string): string {\n return s.replace(/\\s+/g, ' ').toUpperCase();\n}\n\n/**\n * Same as {@link normalizeId} plus resolution of backslash escapes.\n * Used by PASS 0.5 substring pre-check against raw chunk source text:\n * sources may write `[foo\\]bar]` but the resulting label identifier is\n * `foo]bar`, so we must unescape source before substring matching.\n */\nexport function normalizeForMatch(s: string): string {\n return s.replace(/\\\\(.)/g, '$1').replace(/\\s+/g, ' ').toUpperCase();\n}\n","/**\n * Lightweight def-only parse: runs a minimal unified pipeline\n * (remark-parse + remark-gfm) to extract identifiers of all\n * `footnoteDefinition` and `definition` nodes from a markdown source string.\n *\n * Used by PASS 0 of cross-chunk coordination to discover label sets without\n * triggering the full to-hast pipeline. Output is normalized via normalizeId\n * (uppercase, whitespace-collapsed) — same canonical form used everywhere in\n * the registry, phantomFootnoteLabels Set, and handler comparisons.\n *\n * @module components/collectDefLabels\n */\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkGfm from 'remark-gfm';\nimport { visit } from 'unist-util-visit';\nimport type { Root as MdastRoot } from 'mdast';\nimport { normalizeId } from './normalizeId';\n\nexport interface DefLabels {\n footnoteLabels: Set<string>;\n linkLabels: Set<string>;\n}\n\n// Build helper kept as its own function so the cached processor's type is\n// inferred as the FULL chained Processor (remark-parse + remark-gfm), not\n// the bare `unified()` Processor with `undefined` extension types.\nfunction buildProcessor() {\n return unified().use(remarkParse).use(remarkGfm);\n}\nlet _processor: ReturnType<typeof buildProcessor> | null = null;\nfunction processor(): ReturnType<typeof buildProcessor> {\n if (!_processor) _processor = buildProcessor();\n return _processor;\n}\n\nexport function collectDefLabels(source: string): DefLabels {\n if (!source) {\n return { footnoteLabels: new Set(), linkLabels: new Set() };\n }\n const mdast = processor().parse(source) as MdastRoot;\n const footnoteLabels = new Set<string>();\n const linkLabels = new Set<string>();\n visit(mdast, (node) => {\n if (node.type === 'footnoteDefinition' && 'identifier' in node) {\n footnoteLabels.add(normalizeId(node.identifier as string));\n } else if (node.type === 'definition' && 'identifier' in node) {\n linkLabels.add(normalizeId(node.identifier as string));\n }\n });\n return { footnoteLabels, linkLabels };\n}\n","/**\n * Optional outer wrapper enabling cross-chunk coordination for any\n * `<AIMarkdown>` instances rendered as descendants. Each unique\n * `documentId` partitions its own Registry.\n *\n * Without this wrapper, `<AIMarkdown>` instances render independently\n * (current behavior). With it, multiple chunks sharing a `documentId`\n * coordinate footnote numbering, linkReference/imageReference resolution,\n * and anchor jumps across chunks.\n *\n * @module components/AIMarkdownDocuments\n */\nimport { createContext, useContext, useMemo, useRef, type PropsWithChildren, type FC } from 'react';\nimport { createRegistry, type Registry } from './documentRegistry';\n\ninterface AIMarkdownDocumentsContextValue {\n getRegistry: (documentId: string) => Registry;\n preserveOrphanReferences: boolean;\n}\n\nconst AIMarkdownDocumentsContext = createContext<AIMarkdownDocumentsContextValue | null>(null);\n\nexport interface AIMarkdownDocumentsProps extends PropsWithChildren {\n /**\n * Default `true`. Unconditionally controls orphan-reference protection\n * for all chunks under this wrapper, overriding their individual\n * `config.preserveOrphanReferences`. Does not control cross-chunk\n * coordination itself (that's gated by wrapper presence + `documentId`).\n */\n preserveOrphanReferences?: boolean;\n}\n\nexport const AIMarkdownDocuments: FC<AIMarkdownDocumentsProps> = ({ preserveOrphanReferences = true, children }) => {\n const parent = useContext(AIMarkdownDocumentsContext);\n if (parent !== null) {\n throw new Error(\n '<AIMarkdownDocuments> must not be nested inside another <AIMarkdownDocuments>. Use a single top-level wrapper per coordinated scope.'\n );\n }\n\n // Registries are persistent across renders. Map<documentId, Registry>.\n //\n // Eviction: each registry receives an `onEmpty` callback that the\n // wrapper invokes when the registry's last chunk just released its\n // Symbol. The callback removes the registry from this Map iff the\n // entry is STILL the one we created — a fresh `getRegistry(documentId)`\n // racing the cleanup microtask would have already replaced it, in\n // which case eviction is a no-op. This keeps the Map bounded by the\n // number of `documentId` values with at least one chunk alive at any\n // given moment.\n //\n // Known edge case (acceptable v1 limitation): `getRegistry` is called\n // synchronously from `useDocumentRegistry` during render, and creates\n // the registry + writes the Map entry as a render-time side effect.\n // React 19's concurrent rendering allows aborting a render before\n // commit; if a render is aborted AFTER `getRegistry(X)` has created a\n // new registry but BEFORE any chunk's allocate effect commits, AND the\n // next render uses a different `documentId`, the aborted render's\n // registry leaks (no chunk ever attaches, so `onEmpty` never fires).\n // The leak is bounded (one empty Registry shell per aborted-render-\n // with-unique-documentId), the shell is small (a few empty Sets and a\n // version counter), and concurrent aborts on documentId-bearing\n // components are rare in practice. A proper fix would defer the Map\n // insert to chunk-subscription time, but that breaks the synchronous-\n // getter contract `useDocumentRegistry` relies on. Deferred.\n const registriesRef = useRef<Map<string, Registry>>(new Map());\n\n const value = useMemo<AIMarkdownDocumentsContextValue>(\n () => ({\n preserveOrphanReferences,\n getRegistry(documentId: string) {\n let r = registriesRef.current.get(documentId);\n if (!r) {\n // Capture `r` in the closure so the identity check below\n // compares against the exact registry instance we created.\n // A microtask-delayed onEmpty firing AFTER a subsequent\n // getRegistry replaced the entry must NOT evict the new one.\n const created = createRegistry(() => {\n if (registriesRef.current.get(documentId) === created) {\n registriesRef.current.delete(documentId);\n }\n });\n r = created;\n registriesRef.current.set(documentId, r);\n }\n return r;\n },\n }),\n [preserveOrphanReferences]\n );\n\n return <AIMarkdownDocumentsContext.Provider value={value}>{children}</AIMarkdownDocumentsContext.Provider>;\n};\n\n/**\n * Returns the registry for the given `documentId`, or `null` if:\n * - `<AIMarkdown>` is not inside an `<AIMarkdownDocuments>` wrapper, OR\n * - `documentId` is undefined / empty string.\n *\n * Callers should treat `null` as \"no coordination; run standalone path.\"\n */\nexport function useDocumentRegistry(documentId: string | undefined): Registry | null {\n const ctx = useContext(AIMarkdownDocumentsContext);\n if (!ctx || !documentId) return null;\n return ctx.getRegistry(documentId);\n}\n\n/** Returns the effective preserveOrphanReferences for this position in the tree:\n * the wrapper's prop value if inside one, otherwise the supplied fallback\n * (typically `config.preserveOrphanReferences`). */\nexport function usePreserveOrphanReferences(fallback: boolean): boolean {\n const ctx = useContext(AIMarkdownDocumentsContext);\n return ctx?.preserveOrphanReferences ?? fallback;\n}\n\n/** @internal — for tests only. */\nexport function __internalGetContext(): AIMarkdownDocumentsContextValue | null {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(AIMarkdownDocumentsContext);\n}\n","/**\n * Cross-chunk shared state. Holds per-chunk contributions (refs, defs,\n * linkDefs) keyed by Symbol identity allocated via useId reactId, with\n * refcount + microtask-deferred reclamation for React Strict Mode safety.\n *\n * @module components/documentRegistry\n */\n\nimport type { ElementContent as HastElementContent } from 'hast';\nimport { normalizeId } from './normalizeId';\n\nexport interface FootnoteDef {\n /** Already-normalized identifier (uppercase). Used as dictionary key for\n * case-insensitive cross-chunk lookups. */\n identifier: string;\n /** mdast's case-folded identifier — the exact string mdast-util-to-hast\n * emits in `<li id=\"${clobberPrefix}fn-${sourceIdentifier}\">` and that\n * `FootnoteSupNumber` mirrors in its anchor href. Needed so the aggregate\n * footer's `<li id>` and backref href match the inline `<sup>`'s href\n * exactly (otherwise hash navigation breaks). Optional so unit-test\n * fixtures don't need to fabricate it; production data always supplies it. */\n sourceIdentifier?: string;\n /** Content extracted from the source markdown footnote definition. */\n contentSource: string;\n /** Per-def hast body (the def's mdast children after mdast-util-to-hast\n * conversion). Drives AggregateFootnotesIfLast to render the consolidated\n * footer at the end of each document's last chunk. Optional so unit-test\n * fixtures can build minimal FootnoteDef objects without producing hast. */\n bodyHast?: HastElementContent[];\n}\n\nexport interface LinkDef {\n /** Already-normalized identifier (uppercase). */\n identifier: string;\n url: string;\n title?: string;\n}\n\nexport type RefKind = 'footnote' | 'link' | 'image';\n\nexport interface RefRecord {\n /** Already-normalized identifier (uppercase). */\n label: string;\n /** Which markdown reference space this entry belongs to. Footnote refs,\n * link refs, and image refs occupy disjoint namespaces in GFM, so they\n * must be filtered separately when computing footnote numbers / refcounts. */\n kind: RefKind;\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n}\n\nexport interface ChunkData {\n refs: RefRecord[];\n defs: Map<string, FootnoteDef>;\n linkDefs: Map<string, LinkDef>;\n ownFootnoteLabels: Set<string>;\n ownLinkLabels: Set<string>;\n}\n\nexport interface Registry {\n /** Chunk mount-order Symbol list. **Read-only from outside the registry.**\n * Direct mutation (`.push`, `.splice`, index assignment) corrupts\n * footnote numbering, \"last chunk\" detection, and eviction. Use the\n * `allocateSymbol` / `releaseSymbol` / `registerChunk` API instead. */\n readonly chunkOrder: readonly symbol[];\n /** Chunk Symbol → contribution payload. **Read-only from outside.**\n * Use `contributeChunkData` / `contributeLabels` / `registerChunk` to\n * publish; direct `.set` / `.delete` bypasses version bumps and\n * subscriber wake-ups. */\n readonly chunkData: ReadonlyMap<symbol, ChunkData>;\n /** Union of own-def labels across all chunks. PASS 0.5 phantom-injection\n * driver. **Read-only from outside.** The registry derives this from\n * per-chunk contributions; direct mutation breaks the derivation. */\n readonly labelSet: {\n readonly footnoteLabels: ReadonlySet<string>;\n readonly linkLabels: ReadonlySet<string>;\n };\n /** Monotonic version counter bumped by every mutation. **Read-only from\n * outside** — consumers should observe via `subscribe`, not by writing. */\n readonly version: number;\n\n // === API ===\n /** Allocate (or reuse, for Strict Mode remount) the chunk Symbol for\n * `reactId` AND publish this chunk's own def labels (footnotes + links)\n * in one call. Canonical pair API used by `MarkdownContent`'s allocate\n * effect — combining the two reduces the pair to a single registry\n * version step, which downstream consumers see as one wake-up rather\n * than two (the second was already coalesced by microtask, but this\n * keeps the version monotonic-by-1-per-mount which makes debugging\n * easier). The granular `allocateSymbol` / `contributeLabels` methods\n * remain available for tests that need to exercise each step. */\n registerChunk(reactId: string, footnotes: Set<string>, links: Set<string>): symbol;\n allocateSymbol(reactId: string): symbol;\n releaseSymbol(reactId: string): void;\n contributeLabels(symbol: symbol, footnotes: Set<string>, links: Set<string>): void;\n contributeChunkData(symbol: symbol, data: ChunkData): void;\n subscribe(cb: () => void): () => void;\n\n // Selectors (memoized internally by version).\n canonicalFootnoteFor(label: string): symbol | null;\n canonicalLinkFor(label: string): symbol | null;\n globalNumber(label: string): number | null;\n resolveLinkDef(label: string): LinkDef | null;\n getRefsForLabel(label: string): number;\n /** Map a chunk-local footnote-ref occurrence index (1-based, as emitted by\n * `customMdastHandlers`) to the corresponding document-wide occurrence\n * index across all chunks. Used by `FootnoteSupNumber` to build a unique\n * `id=\"fnref-X-N\"` for each ref instance and by `AggregateFootnotesIfLast`\n * to enumerate per-occurrence backrefs. Returns `null` if the ref isn't\n * registered yet (registry mid-flight). */\n globalOccurrenceForRef(chunkSym: symbol, label: string, localOccurrence: number): number | null;\n}\n\n/**\n * The shape actually realised inside `createRegistry`. Includes\n * implementation-private fields (reactId-keyed refcount table, subscriber\n * set, microtask-coalesce flag, `_notify` itself). Kept off the public\n * {@link Registry} interface so the dts emit doesn't leak mutable internals\n * — a consumer flipping `_notifyScheduled = true` would otherwise be able\n * to silently break the coalesce invariant.\n */\ninterface RegistryInternal extends Registry {\n _reactIdMap: Map<string, { symbol: symbol; refcount: number }>;\n _subscribers: Set<() => void>;\n _notifyScheduled: boolean;\n _notify(): void;\n}\n\n/**\n * Construct a new Registry. `onEmpty`, if supplied, is invoked once each\n * time the registry transitions to \"no chunks alive\" — i.e. the last\n * tracked chunk's deferred `releaseSymbol` cleanup just removed its\n * entry, leaving `chunkOrder` and `chunkData` both empty. The container\n * uses this to evict the registry from its `documentId → Registry` map\n * so long-lived SPAs that cycle through many `documentId` values don't\n * accumulate empty shells.\n *\n * `onEmpty` fires synchronously from inside the releaseSymbol microtask,\n * so the registry's state is guaranteed quiescent during the callback —\n * no other code can interleave between the empty-state check and the\n * caller's eviction logic.\n */\nexport function createRegistry(onEmpty?: () => void): Registry {\n const reg = {\n chunkOrder: [] as symbol[],\n chunkData: new Map<symbol, ChunkData>(),\n labelSet: { footnoteLabels: new Set<string>(), linkLabels: new Set<string>() },\n version: 0,\n _reactIdMap: new Map<string, { symbol: symbol; refcount: number }>(),\n _subscribers: new Set<() => void>(),\n _notifyScheduled: false,\n\n allocateSymbol(reactId: string): symbol {\n const existing = this._reactIdMap.get(reactId);\n if (existing) {\n existing.refcount++;\n return existing.symbol;\n }\n const sym = Symbol(reactId);\n this._reactIdMap.set(reactId, { symbol: sym, refcount: 1 });\n this.chunkOrder.push(sym);\n this._notify();\n return sym;\n },\n\n registerChunk(reactId: string, footnotes: Set<string>, links: Set<string>): symbol {\n // Composition of allocateSymbol + contributeLabels. Both `_notify`\n // calls coalesce into a single microtask wake-up, so the perf\n // shape is the same as the granular pair — the API just expresses\n // the canonical \"register one chunk\" intent.\n const sym = this.allocateSymbol(reactId);\n this.contributeLabels(sym, footnotes, links);\n return sym;\n },\n\n releaseSymbol(reactId: string): void {\n const entry = this._reactIdMap.get(reactId);\n if (!entry) return;\n entry.refcount--;\n if (entry.refcount === 0) {\n queueMicrotask(() => {\n const latest = this._reactIdMap.get(reactId);\n if (latest && latest.refcount === 0) {\n this._reactIdMap.delete(reactId);\n const idx = this.chunkOrder.indexOf(entry.symbol);\n if (idx !== -1) this.chunkOrder.splice(idx, 1);\n this.chunkData.delete(entry.symbol);\n // Rebuild labelSet from the surviving chunks. The contribute paths\n // (`contributeLabels`, `contributeChunkData`) already rebuild this\n // union on every write, but a chunk that simply UNMOUNTS would\n // otherwise leave `labelSet` referencing labels that no live chunk\n // owns. Downstream consumers (`targetPhantoms` in\n // `MarkdownContent`) read `registry.labelSet` to gate phantom\n // injection — without this rebuild, surviving chunks would keep\n // treating refs to the released chunk's labels as phantom, while\n // `canonicalFootnoteFor` (which walks live chunkData) returns\n // null, leaving inline `<sup>` anchors pointing at `<li>` ids\n // that the aggregate footer never renders.\n const nextFn = new Set<string>();\n const nextLink = new Set<string>();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) nextFn.add(l);\n for (const l of cd.ownLinkLabels) nextLink.add(l);\n }\n this.labelSet.footnoteLabels = nextFn;\n this.labelSet.linkLabels = nextLink;\n this._notify();\n // Last chunk just left: notify the container so it can drop\n // this registry from its `documentId → Registry` map. The\n // identity check on the container side prevents racing a\n // freshly-allocated registry under the same documentId.\n //\n // Ordering note: `onEmpty` fires SYNCHRONOUSLY here, after\n // `_notify` has scheduled subscriber fanout (which itself\n // runs in a later microtask, see `_notifyScheduled`). So\n // the container evicts FIRST, then subscribers wake. A\n // subscriber that re-resolves via `getRegistry(documentId)`\n // during its wake-up therefore sees a freshly-allocated\n // registry — which is the right behavior, because by then\n // the consumer is genuinely starting over.\n if (this.chunkOrder.length === 0 && this.chunkData.size === 0 && onEmpty) {\n onEmpty();\n }\n }\n });\n }\n },\n\n contributeLabels(symbol: symbol, footnotes: Set<string>, links: Set<string>): void {\n const data = this.chunkData.get(symbol);\n if (data) {\n data.ownFootnoteLabels = footnotes;\n data.ownLinkLabels = links;\n } else {\n this.chunkData.set(symbol, {\n refs: [],\n defs: new Map(),\n linkDefs: new Map(),\n ownFootnoteLabels: footnotes,\n ownLinkLabels: links,\n });\n }\n // Always notify. The prior `if (fnChanged || linkChanged)` optimization\n // skipped the wake-up when the UNION labelSet was unchanged — but\n // chunkData has ALWAYS mutated by the time we reach this line (we either\n // overwrote ownFootnoteLabels/ownLinkLabels on an existing entry, or we\n // just created a fresh chunkData entry above). A subscriber keyed on\n // `registry.version` would observe live chunkData changing under a\n // stable snapshot — a useSyncExternalStore tearing violation. With the\n // microtask-coalesced `_notify`, the per-call cost is the version++\n // plus a single subscriber fanout per batch, so the optimization's\n // savings are nil; correctness wins.\n const newFn = new Set<string>();\n const newLink = new Set<string>();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) newFn.add(l);\n for (const l of cd.ownLinkLabels) newLink.add(l);\n }\n this.labelSet.footnoteLabels = newFn;\n this.labelSet.linkLabels = newLink;\n this._notify();\n },\n\n contributeChunkData(symbol: symbol, data: ChunkData): void {\n this.chunkData.set(symbol, data);\n // Rebuild labelSet too (data may extend or shrink it)\n this.labelSet.footnoteLabels = new Set();\n this.labelSet.linkLabels = new Set();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) this.labelSet.footnoteLabels.add(l);\n for (const l of cd.ownLinkLabels) this.labelSet.linkLabels.add(l);\n }\n this._notify();\n },\n\n subscribe(cb: () => void): () => void {\n this._subscribers.add(cb);\n return () => {\n this._subscribers.delete(cb);\n };\n },\n\n canonicalFootnoteFor(label: string): symbol | null {\n const id = normalizeId(label);\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (data?.defs.has(id)) return sym;\n }\n return null;\n },\n\n canonicalLinkFor(label: string): symbol | null {\n const id = normalizeId(label);\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (data?.linkDefs.has(id)) return sym;\n }\n return null;\n },\n\n globalNumber(label: string): number | null {\n const id = normalizeId(label);\n let n = 0;\n const seen = new Set<string>();\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n for (const ref of data.refs) {\n // Footnote numbering is a per-space ordinal; link/image refs share\n // the `refs` array but occupy a disjoint namespace, so they must\n // NOT advance the footnote counter.\n if (ref.kind !== 'footnote') continue;\n if (!seen.has(ref.label)) {\n seen.add(ref.label);\n n++;\n if (ref.label === id) return n;\n }\n }\n }\n return null;\n },\n\n resolveLinkDef(label: string): LinkDef | null {\n const sym = this.canonicalLinkFor(label);\n if (!sym) return null;\n return this.chunkData.get(sym)?.linkDefs.get(normalizeId(label)) ?? null;\n },\n\n getRefsForLabel(label: string): number {\n const id = normalizeId(label);\n let n = 0;\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n // Only count footnote refs: the consumers (backref-strip and\n // backref-inject) decide based on whether a footnote `<li>` should\n // exist, which depends on footnote refs alone.\n for (const ref of data.refs) {\n if (ref.kind === 'footnote' && ref.label === id) n++;\n }\n }\n return n;\n },\n\n globalOccurrenceForRef(chunkSym: symbol, label: string, localOccurrence: number): number | null {\n const id = normalizeId(label);\n let global = 0;\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n let localCount = 0;\n for (const ref of data.refs) {\n if (ref.kind !== 'footnote') continue;\n if (ref.label !== id) continue;\n localCount++;\n global++;\n if (sym === chunkSym && localCount === localOccurrence) return global;\n }\n }\n return null;\n },\n\n _notify(): void {\n this.version++;\n if (this._notifyScheduled) return;\n this._notifyScheduled = true;\n queueMicrotask(() => {\n this._notifyScheduled = false;\n // Snapshot subscribers so unsubscribes during fanout don't shift the\n // iteration. New subscribers added during fanout will pick up the\n // current `version` on their next render.\n for (const cb of [...this._subscribers]) cb();\n });\n },\n };\n // Internally `reg` has both the public API and the private state.\n // The return type narrows to the public {@link Registry} so the dts\n // emit doesn't expose `_reactIdMap` / `_subscribers` / `_notifyScheduled` /\n // `_notify` — those are operational invariants, not API surface.\n return reg as unknown as RegistryInternal as Registry;\n}\n","/**\n * Direction B: source-level phantom-definition injection helpers.\n *\n * @module components/remarkInjectPhantomDefs\n */\n\nexport const SENTINEL_LINK_URL = '__aimd_sentinel_link__';\nexport const SENTINEL_FN_CONTENT = '__aimd_sentinel_fn__';\n\nexport interface PhantomLabels {\n missingFootnotes: Set<string>;\n missingLinks: Set<string>;\n}\n\n/**\n * Compute the source string to feed to the full PASS 1 parser: original\n * content + appended phantom definitions for labels not locally defined.\n *\n * Labels are expected to already be normalized via normalizeId (uppercase).\n * The output is suitable as input to remark-parse with the standard pipeline.\n */\nexport function augmentSourceWithPhantoms(source: string, phantoms: PhantomLabels): string {\n if (phantoms.missingFootnotes.size === 0 && phantoms.missingLinks.size === 0) {\n return source;\n }\n let suffix = '\\n\\n';\n for (const label of phantoms.missingLinks) {\n suffix += `[${label}]: ${SENTINEL_LINK_URL}\\n`;\n }\n for (const label of phantoms.missingFootnotes) {\n suffix += `[^${label}]: ${SENTINEL_FN_CONTENT}\\n`;\n }\n return source + suffix;\n}\n","/**\n * Custom mdast-util-to-hast handlers for cross-chunk label resolution.\n *\n * Direction A: `footnoteDefinitionHandler` mutates `state.footnoteOrder` so\n * `state.footer()` emits a `<section data-footnotes>` even when no\n * `footnoteReference` exists locally (orphan-def protection).\n *\n * Direction B: `linkReferenceHandler` / `imageReferenceHandler` /\n * `footnoteReferenceHandler` short-circuit the default to-hast output and\n * emit custom hast tags (`cross-chunk-link` / `cross-chunk-image` /\n * `footnote-sup`) carrying `label` + `referenceType` properties. These tags\n * map to React placeholder components in Phase 11. The sentinel URL is never\n * read — the handlers only need to know that the def is resolvable\n * (i.e. present in state.definitionById).\n *\n * All identifier comparisons normalize via {@link normalizeId} to match\n * mdast-util-to-hast's internal uppercase keying convention.\n *\n * @module components/customMdastHandlers\n */\nimport type { Handlers } from 'mdast-util-to-hast';\nimport type { LinkReference, ImageReference, FootnoteReference, FootnoteDefinition } from 'mdast';\nimport type { Element as HastElement } from 'hast';\nimport { normalizeId } from './normalizeId';\n\nexport interface CrossChunkHandlerOptions {\n /** Set of labels (already normalized) that this chunk phantom-injected\n * into its source for parser acceptance. Handlers use this to short-circuit\n * state writes that would otherwise leak sentinel content into the footer. */\n phantomFootnoteLabels: Set<string>;\n /** Same role for link/image defs. */\n phantomLinkLabels: Set<string>;\n /** When true, footnoteDefinitionHandler proactively registers orphan defs\n * to state.footnoteOrder (Direction A). */\n preserveOrphan: boolean;\n /** Passed through to placeholder hast properties so React components can\n * partition by document. */\n documentId: string;\n}\n\n// Type assertion helper for state shape (mdast-util-to-hast doesn't export it).\ninterface StateShape {\n options: CrossChunkHandlerOptions & Record<string, unknown>;\n footnoteOrder: string[];\n footnoteCounts: Map<string, number>;\n definitionById: Map<string, unknown>;\n all: (node: unknown) => unknown[];\n}\n\nexport function buildCrossChunkHandlers(): Handlers {\n return {\n footnoteDefinition: (state: unknown, node: FootnoteDefinition): undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n // Phantom def → noop: do not register, do not emit. Footer will skip it\n // because footnoteOrder does not contain id (unless a real ref pushed it).\n if (s.options.phantomFootnoteLabels.has(id)) {\n return undefined;\n }\n // Direction A: orphan def protection. Register so state.footer() emits <li>.\n if (s.options.preserveOrphan && !s.footnoteOrder.includes(id)) {\n s.footnoteOrder.push(id);\n // Deliberately do NOT bump footnoteCounts. transformStripBackrefs\n // (Phase 7) reads registry.getRefsForLabel to decide backref strip\n // — independent of state.footnoteCounts.\n }\n return undefined; // never emit inline hast\n },\n\n linkReference: ((state: unknown, node: LinkReference): HastElement | undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n const resolved = s.definitionById.has(id);\n if (!resolved) {\n // Unreachable in coordinated pipeline because augmentSourceWithPhantoms\n // guarantees a def for every referenced label that survives PASS 0.5.\n // Verified by experiment: remark-parse produces a `linkReference`\n // mdast node ONLY when a corresponding `[label]:` exists in the\n // source — without one, the brackets are emitted as plain text by\n // the parser, so neither this handler nor mdast's default ever\n // sees the reference. Defense-in-depth for an impossible state.\n return undefined;\n }\n return {\n type: 'element',\n tagName: 'cross-chunk-link',\n properties: {\n // `label` is the ORIGINAL source text (mdast's `label` field), NOT\n // the normalized `identifier`. The placeholder uses it to construct\n // hrefs that line up with mdast-util-to-hast's default `<li id>`\n // which also preserves source case. Registry lookups normalize\n // internally, so cross-chunk case-insensitive matching still works.\n label: node.label ?? node.identifier,\n referenceType: node.referenceType,\n documentId: s.options.documentId,\n },\n children: s.all(node) as HastElement['children'],\n };\n }) as Handlers['linkReference'],\n\n imageReference: ((state: unknown, node: ImageReference): HastElement | undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n const resolved = s.definitionById.has(id);\n if (!resolved) return undefined;\n return {\n type: 'element',\n tagName: 'cross-chunk-image',\n properties: {\n label: node.label ?? node.identifier,\n referenceType: node.referenceType,\n alt: node.alt ?? '',\n documentId: s.options.documentId,\n },\n children: [],\n };\n }) as Handlers['imageReference'],\n\n footnoteReference: ((state: unknown, node: FootnoteReference): HastElement => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n // Bump the per-id counter for ALL refs (phantom and real). The result\n // is the chunk-local occurrence index (1, 2, 3, …) which the placeholder\n // carries so FootnoteSupNumber can disambiguate duplicate fnref-* ids\n // when the same label is referenced multiple times. For phantom refs\n // bumping is safe: state.footer() emits <li> only for ids in\n // footnoteOrder, and phantoms never get pushed there.\n const localOccurrence = (s.footnoteCounts.get(id) ?? 0) + 1;\n s.footnoteCounts.set(id, localOccurrence);\n if (s.options.phantomFootnoteLabels.has(id)) {\n return {\n type: 'element',\n tagName: 'footnote-sup',\n properties: {\n label: node.identifier,\n localOccurrence,\n documentId: s.options.documentId,\n },\n children: [],\n };\n }\n // Real local def: register in footnoteOrder so the local synthetic\n // footer can emit a <li> for it.\n if (!s.footnoteOrder.includes(id)) s.footnoteOrder.push(id);\n return {\n type: 'element',\n tagName: 'footnote-sup',\n properties: {\n label: node.identifier,\n localOccurrence,\n documentId: s.options.documentId,\n },\n children: [],\n };\n }) as Handlers['footnoteReference'],\n };\n}\n","/**\n * Placeholder React components that custom hast tags\n * (`<cross-chunk-link>` / `<cross-chunk-image>` / `<footnote-sup>`)\n * map to via react-markdown's `components` prop.\n *\n * Each subscribes to its document's Registry via useSyncExternalStore.\n * On selector miss (registry not present, label not resolved):\n * - FootnoteSupNumber renders null\n * - CrossChunkLink falls back to literal source text by referenceType\n * - CrossChunkImage falls back to literal source text by referenceType\n *\n * @module components/crossChunkPlaceholders\n */\nimport { type ReactNode, isValidElement, useCallback, useContext, useSyncExternalStore } from 'react';\nimport { useAIMarkdownRenderState } from '../context';\nimport { useDocumentRegistry } from './AIMarkdownDocuments';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport type { LinkDef } from './documentRegistry';\n\ntype RefType = 'full' | 'collapsed' | 'shortcut' | undefined;\n\n/** Module-level SSR snapshot constant. Hoisted out of components so its\n * identity is stable across renders. */\nconst SSR_NUM_SNAPSHOT = () => 0;\nconst SSR_DEF_SNAPSHOT = () => null;\n\ninterface FootnoteSupProps {\n label: string;\n /** Chunk-local occurrence index (1-based) of THIS particular `[^x]`\n * reference within the chunk's parse. Used together with the per-chunk\n * Symbol from `ChunkSymbolContext` to compute the cross-chunk *global*\n * occurrence index, which disambiguates duplicate `id=\"fnref-X\"` when\n * the same footnote is referenced multiple times. Carried on the hast\n * tag by `customMdastHandlers.footnoteReference`.\n *\n * **Type note**: customMdastHandlers emits this as a JS number, but\n * rehype-raw's parse5 round-trip stringifies it (verified in\n * `customMdastHandlers.test.ts`). The component accepts either form\n * and coerces internally so the contract is robust to the pipeline. */\n localOccurrence?: number | string;\n /** Optional — but normally the hast tag carries it. */\n documentId?: string;\n}\n\n/** Coerce the on-the-wire `localOccurrence` (which may be a JS number from\n * the handler OR a stringified attr from rehype-raw's parse5 round-trip)\n * to a finite positive integer, or null if absent / malformed. */\nfunction coerceLocalOccurrence(v: number | string | undefined): number | null {\n if (v === undefined) return null;\n if (typeof v === 'number') return Number.isFinite(v) && v >= 1 ? Math.trunc(v) : null;\n const n = Number(v);\n return Number.isFinite(n) && n >= 1 ? Math.trunc(n) : null;\n}\n\nexport function FootnoteSupNumber({ label, localOccurrence: localOccurrenceRaw }: FootnoteSupProps): ReactNode {\n const localOccurrence = coerceLocalOccurrence(localOccurrenceRaw);\n const { documentId, clobberPrefix } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const chunkSym = useContext(ChunkSymbolContext);\n // Subscribe identity stabilised across renders (see top of file).\n // useSyncExternalStore's selector must return an `Object.is`-stable value\n // across notifications when the underlying registry state is unchanged —\n // `registry.version` is just a number, so this property holds.\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.version ?? 0, [registry]);\n useSyncExternalStore(subscribe, getSnapshot, SSR_NUM_SNAPSHOT);\n const num = registry?.globalNumber(label) ?? null;\n if (num === null) return null;\n if (localOccurrence !== null && !chunkSym) return null;\n const globalOcc =\n registry && chunkSym && localOccurrence !== null\n ? registry.globalOccurrenceForRef(chunkSym, label, localOccurrence)\n : null;\n if (localOccurrence !== null && globalOcc === null) return null;\n // Append `-N` when this is the 2nd+ occurrence of the same label across\n // the document. The first occurrence keeps the bare `fnref-${id}` so a\n // ref-once-only doc renders byte-identical to the pre-multi-ref design.\n const occSuffix = globalOcc !== null && globalOcc > 1 ? `-${globalOcc}` : '';\n return (\n <sup>\n <a href={`#${clobberPrefix}fn-${label}`} id={`${clobberPrefix}fnref-${label}${occSuffix}`} data-footnote-ref>\n {num}\n </a>\n </sup>\n );\n}\n\ninterface CrossChunkLinkProps {\n label: string;\n referenceType: RefType;\n children?: ReactNode;\n}\n\n/** Recursively flatten a ReactNode tree to plain text. The fallback for\n * an unresolved CrossChunkLink renders the literal markdown source\n * (`[text][label]`); the `[text]` slot must therefore be a string, not a\n * React element tree. Rich children — e.g. `[**bold**][missing]` whose\n * `[text]` slot mdast lowered to `<strong>bold</strong>` then react-\n * markdown handed us as `<strong>bold</strong>` React element — would\n * otherwise stringify as the literal `\"[object Object]\"` via the previous\n * `children?.toString?.()` path. Walking the tree and concatenating text\n * nodes degrades the rich markup to plain text but preserves the human-\n * readable label slot, which is what the fallback aims for. */\nfunction reactNodeToText(node: ReactNode): string {\n if (node === null || node === undefined || typeof node === 'boolean') return '';\n if (typeof node === 'string') return node;\n if (typeof node === 'number' || typeof node === 'bigint') return String(node);\n if (Array.isArray(node)) return node.map(reactNodeToText).join('');\n if (isValidElement(node)) {\n return reactNodeToText((node.props as { children?: ReactNode }).children);\n }\n return '';\n}\n\nfunction literalLink(rt: RefType, label: string, children: ReactNode): string {\n const text = reactNodeToText(children);\n switch (rt) {\n case 'full':\n return `[${text}][${label}]`;\n case 'collapsed':\n return `[${label}][]`;\n case 'shortcut':\n default:\n return `[${label}]`;\n }\n}\n\nexport function CrossChunkLink({ label, referenceType, children }: CrossChunkLinkProps): ReactNode {\n const { documentId } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.resolveLinkDef(label) ?? null, [registry, label]);\n const def = useSyncExternalStore<LinkDef | null>(subscribe, getSnapshot, SSR_DEF_SNAPSHOT);\n if (!def) {\n return literalLink(referenceType, label, children);\n }\n return (\n <a href={def.url} title={def.title}>\n {children}\n </a>\n );\n}\n\ninterface CrossChunkImageProps {\n label: string;\n referenceType: RefType;\n alt?: string;\n}\n\nfunction literalImage(rt: RefType, label: string, alt: string): string {\n switch (rt) {\n case 'full':\n return `![${alt}][${label}]`;\n case 'collapsed':\n return `![${alt}][]`;\n case 'shortcut':\n default:\n return `![${label}]`;\n }\n}\n\nexport function CrossChunkImage({ label, referenceType, alt = '' }: CrossChunkImageProps): ReactNode {\n const { documentId } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.resolveLinkDef(label) ?? null, [registry, label]);\n const def = useSyncExternalStore<LinkDef | null>(subscribe, getSnapshot, SSR_DEF_SNAPSHOT);\n if (!def) {\n return literalImage(referenceType, label, alt);\n }\n return <img src={def.url} alt={alt} title={def.title} />;\n}\n\n/**\n * Components map suitable for spreading into react-markdown's `components` prop.\n * Keys are lowercase tag names matching the custom hast tags emitted by\n * Phase 6 handlers.\n */\nexport const crossChunkComponents = {\n 'footnote-sup': FootnoteSupNumber,\n 'cross-chunk-link': CrossChunkLink,\n 'cross-chunk-image': CrossChunkImage,\n};\n","/**\n * Per-chunk Symbol identity exposed via React context.\n *\n * Each coordinated `<AIMarkdownContent>` allocates a Symbol against its\n * documentId's Registry (via `useId` + `Registry.allocateSymbol`). Inline\n * placeholder components like `FootnoteSupNumber` need to know which chunk\n * they belong to so they can ask the registry for a chunk-scoped value\n * (e.g. the *global* occurrence index of a chunk-local footnote ref).\n *\n * Modelled as a tiny standalone context so consumers can subscribe without\n * dragging the full `MarkdownContent` module into their import graph.\n *\n * Value is `null` outside of a coordinated render (standalone single-doc\n * mode, or pre-allocation paint).\n *\n * @module components/chunkSymbolContext\n */\nimport { createContext } from 'react';\n\nexport const ChunkSymbolContext = createContext<symbol | null>(null);\n","/**\n * Walk an mdast tree and yield ref/def records in source order. Used by\n * AIMarkdownContent's PASS 1 contribute step to populate Registry.chunkData.\n *\n * Phantom definitions (Direction B) carry sentinel content/url but the\n * sentinel parse may not produce exactly the sentinel string at the AST\n * level (e.g. `__aimd_sentinel_fn__` parses as <strong>aimd_sentinel_fn</strong>).\n * Therefore phantom detection is done both ways:\n * - linkDef: check `url === SENTINEL_LINK_URL` (raw string survives parsing).\n * - fnDef: skip if the def's normalized identifier is in the supplied\n * `phantomFootnoteLabels` set. The caller knows which labels it\n * injected (PASS 0.5 `targetPhantoms.missingFootnotes`).\n *\n * @module components/extractContributions\n */\nimport { SKIP, visit } from 'unist-util-visit';\nimport type { Root as MdastRoot } from 'mdast';\nimport { normalizeId } from './normalizeId';\nimport { SENTINEL_LINK_URL } from './remarkInjectPhantomDefs';\n\nexport type Contribution =\n | {\n kind: 'ref';\n refKind: 'footnote' | 'link' | 'image';\n label: string;\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n }\n | { kind: 'fnDef'; label: string; sourceIdentifier: string; content: string }\n | { kind: 'linkDef'; label: string; url: string; title?: string };\n\nexport interface ExtractContributionsOptions {\n /** Already-normalized labels that were phantom-injected at PASS 0.5.\n * Defs matching these are skipped to avoid leaking sentinel rows into\n * registry.chunkData. */\n phantomFootnoteLabels?: Set<string>;\n}\n\nexport function* extractContributions(\n mdast: MdastRoot,\n options: ExtractContributionsOptions = {}\n): Generator<Contribution> {\n const phantomFn = options.phantomFootnoteLabels;\n const out: Contribution[] = [];\n visit(mdast, (n) => {\n if (n.type === 'footnoteReference') {\n out.push({\n kind: 'ref',\n refKind: 'footnote',\n label: normalizeId((n as { identifier: string }).identifier),\n });\n } else if (n.type === 'linkReference') {\n const r = n as { identifier: string; referenceType: 'full' | 'collapsed' | 'shortcut' };\n out.push({ kind: 'ref', refKind: 'link', label: normalizeId(r.identifier), referenceType: r.referenceType });\n } else if (n.type === 'imageReference') {\n const r = n as { identifier: string; referenceType: 'full' | 'collapsed' | 'shortcut' };\n out.push({ kind: 'ref', refKind: 'image', label: normalizeId(r.identifier), referenceType: r.referenceType });\n } else if (n.type === 'footnoteDefinition') {\n const d = n as { identifier: string; children: unknown[] };\n const label = normalizeId(d.identifier);\n // Skip phantom-injected (by injected-label set, since the sentinel\n // string may not survive markdown parsing intact).\n if (phantomFn?.has(label)) return SKIP;\n // Best-effort raw content snapshot: stringify the first child's\n // structure. Footnote definitions are typed `(BlockContent | DefinitionContent)[]`\n // so we serialize loosely. Used only as a coarse fingerprint string.\n const content = JSON.stringify(d.children ?? []);\n // d.identifier is mdast's already-case-folded form — the same string\n // mdast-util-to-hast uses in `<li id=\"...fn-${id}\">`. Tracked separately\n // from the uppercase-normalized `label` (used as a dictionary key) so\n // HTML ids built downstream match the inline sup's href byte-for-byte.\n //\n // bodyHast is NOT computed here — see extractDefBodiesFromHast for\n // why we source it from the post-pipeline hast instead.\n out.push({ kind: 'fnDef', label, sourceIdentifier: d.identifier, content });\n // SKIP descent into the def's children: NESTED footnoteReferences /\n // linkReferences / imageReferences inside a def body should NOT\n // count as flow refs. Without this, a def whose body contains\n // `[^x]: see [^a].` would record an extra ref to `a` in registry\n // refs — inflating `globalNumber('a')` (making `a` appear in the\n // aggregate footer even if no flow text references it), and worse,\n // inflating `getRefsForLabel('a')` so the aggregate emits a backref\n // anchor to `#fnref-a-2` that points at an id no inline `<sup>`\n // ever rendered. Trade-off: a footnoteDefinition nested INSIDE\n // another def's body (allowed by GFM but exceedingly rare) is also\n // not extracted; deferred until we see a real use case.\n return SKIP;\n } else if (n.type === 'definition') {\n const d = n as { identifier: string; url: string; title?: string };\n if (d.url === SENTINEL_LINK_URL) return;\n out.push({ kind: 'linkDef', label: normalizeId(d.identifier), url: d.url, title: d.title });\n }\n });\n for (const c of out) yield c;\n}\n","/**\n * Extract footnote-definition bodies from a chunk's POST-pipeline hast tree.\n *\n * Why not just `toHast(def.children)` in extractContributions? That call runs\n * only mdast-util-to-hast's default handlers — no rehype-katex, no rehype-raw,\n * no rehype-footer-adorn, no clobber-prefix application. Defs containing math\n * (`$x$`), inline raw HTML, or definition-list extensions would render\n * incorrectly inside the cross-chunk aggregate footer.\n *\n * Instead, we read the FINAL hast: mdast-util-to-hast's `state.footer()` has\n * already emitted `<section data-footnotes><ol><li id=\"...fn-X\">body</li>…`\n * for every def that has a real entry in `state.footnoteOrder`, the full\n * rehype chain has run on top, and the per-`<li>` body is exactly what the\n * standalone path would render. Lift those `<li>` children (minus the\n * auto-emitted backref `<a>`s, which the aggregate emits itself per\n * occurrence) and key by normalized label.\n *\n * Chunks whose only refs are phantom-injected (cross-chunk) won't have a\n * synthetic `<section>` at all — those chunks contribute no defs, and the\n * canonical-chunk handler upstream guarantees the def's body is captured\n * from the chunk that owns it.\n *\n * @module components/extractDefBodiesFromHast\n */\nimport { SKIP, visit } from 'unist-util-visit';\nimport type { Element as HastElement, Root as HastRoot, ElementContent } from 'hast';\nimport { normalizeId } from './normalizeId';\n\n// Fallback for callers that do not know the exact clobberPrefix. The main\n// renderer passes the prefix explicitly so labels containing regex metacharacters\n// or prefixes containing `user-content-fn-` are handled by string slicing.\nconst FN_LI_ID_RE = /(?:^|-)user-content-fn-(.+)$/;\n\nfunction sourceIdFromFootnoteLiId(idProp: string, clobberPrefix?: string): string | null {\n let raw: string | null = null;\n if (clobberPrefix !== undefined) {\n const exactPrefix = `${clobberPrefix}fn-`;\n if (idProp.startsWith(exactPrefix)) raw = idProp.slice(exactPrefix.length);\n }\n if (raw === null) {\n const m = idProp.match(FN_LI_ID_RE);\n raw = m ? m[1] : null;\n }\n if (raw === null) return null;\n // mdast-util-to-hast's footer emits `<li id=\"${prefix}fn-${normalizeUri(id)}\">`\n // which percent-encodes whitespace, non-ASCII characters (`中文` → `%E4%B8%AD…`),\n // and most URL-unsafe punctuation. The registry's def key (set by\n // extractContributions via `normalizeId(node.identifier)`) is the DECODED\n // form — uppercase + whitespace-collapsed but otherwise the source bytes.\n // Without decoding here, every label that triggers normalizeUri encoding\n // (CJK, accented Latin, spaces, `&`/`?` punctuation) would key-mismatch\n // between harvested body and registry def, leaving the aggregate footer's\n // `<li>` empty for those labels.\n try {\n return decodeURIComponent(raw);\n } catch {\n // Malformed percent-encoding (extremely rare — would require user-\n // supplied raw HTML in the def's id). Fall back to the raw form rather\n // than crashing the harvest.\n return raw;\n }\n}\n\nfunction isBackrefAnchor(c: ElementContent): boolean {\n if (c.type !== 'element') return false;\n const el = c as HastElement;\n if (el.tagName !== 'a') return false;\n return Boolean(el.properties && 'dataFootnoteBackref' in el.properties);\n}\n\nfunction isWhitespaceText(c: ElementContent): boolean {\n if (c.type !== 'text') return false;\n return /^\\s*$/.test((c as { value: string }).value);\n}\n\n/** Index of the last child that isn't a whitespace-only text node, or -1\n * if no such child exists. mdast-util-to-hast's `state.wrap(content, true)`\n * inserts `\\n` text nodes between (and around) block-level children of\n * `<li>`; we have to look past those to find the meaningful tail before\n * deciding which backref-strip case applies. */\nfunction lastMeaningfulIdx(children: ElementContent[]): number {\n for (let i = children.length - 1; i >= 0; i--) {\n if (!isWhitespaceText(children[i])) return i;\n }\n return -1;\n}\n\n/**\n * Drop trailing auto-emitted backref anchors and any separator whitespace\n * mdast-util-to-hast emitted before them. Operates only on the tail of\n * `children` — does NOT recurse into mid-list elements — so user content\n * elsewhere in the def that happens to look like a backref anchor survives.\n *\n * The shapes we have to undo (see `mdast-util-to-hast/lib/footer.js`):\n *\n * - **trailing wrap whitespace**: `state.wrap(content, true)` inserts\n * `\\n` text nodes between/around block-level children of `<li>`. The\n * auto-emitted backref sits BEFORE the trailing `\\n`, so we have to\n * peel past whitespace before checking for the backref. Confirmed by\n * a real-pipeline trace: an empty def produces\n * `<li>` children = `[\"\\n\", <a backref>, \"\\n\"]`.\n * - **standalone separator** between consecutive backrefs (and before\n * the first one when the trailing child is NOT a text node): a `{type:\n * 'text', value: ' '}` element pushed alongside the backref anchor.\n * - **merged separator** before the first backref when the trailing\n * child IS a text node: footer.js does `tailTail.value += ' '`, so the\n * leading space is concatenated INTO the existing text node rather\n * than pushed as a separate node. After peeling the backrefs, that\n * residual trailing space sits at the end of the last text node and\n * would visibly double when the aggregate footer prepends its own\n * separator. Trim exactly one trailing space to undo it.\n */\nfunction dropTrailingBackrefs(children: ElementContent[]): ElementContent[] {\n // Step 1: identify trailing whitespace-only text nodes. Preserve them\n // verbatim in the output — they're semantically part of mdast-util-to-\n // hast's expected shape and downstream serializers may rely on them.\n let trailingWsStart = children.length;\n while (trailingWsStart > 0 && isWhitespaceText(children[trailingWsStart - 1])) {\n trailingWsStart--;\n }\n // Step 2: scan backwards from the last non-whitespace child, peeling\n // backref anchors and their inter-backref `' '` separators.\n let scan = trailingWsStart;\n let peeledAny = false;\n while (scan > 0) {\n const t = children[scan - 1];\n if (!isBackrefAnchor(t)) break;\n peeledAny = true;\n scan -= 1;\n if (scan > 0 && children[scan - 1].type === 'text' && (children[scan - 1] as { value: string }).value === ' ') {\n scan -= 1;\n }\n }\n if (!peeledAny) return children;\n const trailing = children.slice(trailingWsStart);\n // Step 3: undo the merged-separator case. Trim exactly ONE trailing\n // space from the last surviving text node (matching footer.js's\n // `+= ' '`). Multiple trailing spaces stay intact — only the one\n // footer.js appended is ours to remove. Whitespace-only text nodes\n // (e.g. `\\n`) don't qualify for trim — they aren't merged separators.\n if (scan > 0) {\n const last = children[scan - 1];\n if (last.type === 'text') {\n const v = (last as { value: string }).value;\n if (v.endsWith(' ') && !/^\\s*$/.test(v)) {\n return [...children.slice(0, scan - 1), { ...last, value: v.slice(0, -1) } as ElementContent, ...trailing];\n }\n }\n }\n return [...children.slice(0, scan), ...trailing];\n}\n\n/**\n * Strip mdast-util-to-hast's auto-emitted backref anchors from a `<li>`\n * body. The library only ever appends backrefs in one of two locations:\n * (a) directly at the end of the `<li>`'s children (after `state.wrap`\n * interleaves whitespace nodes between block-level siblings), OR\n * (b) at the end of the last `<p>` child of the `<li>`.\n * We handle both — and nothing else — to avoid stripping any\n * `data-footnote-backref`-shaped element that happens to live in user\n * content elsewhere in the def body.\n */\nfunction stripBackrefs(liChildren: ElementContent[]): ElementContent[] {\n if (liChildren.length === 0) return liChildren;\n // Look past mdast-util-to-hast's trailing `\\n` text node(s) to find the\n // meaningful tail. That tells us which of the two cases applies.\n const lastIdx = lastMeaningfulIdx(liChildren);\n if (lastIdx < 0) return liChildren;\n const last = liChildren[lastIdx];\n\n // Direct-into-li case (case A): meaningful tail IS the backref. Peel\n // from `<li>` children; dropTrailingBackrefs handles the trailing `\\n`.\n if (isBackrefAnchor(last)) {\n return dropTrailingBackrefs(liChildren);\n }\n\n // Inside-<p> case (case B): meaningful tail is `<p>` and backrefs live\n // inside its inline children. `<p>` itself has no wrap-emitted whitespace\n // (state.wrap only fires for block-level lists), so dropTrailingBackrefs\n // can scan the `<p>`'s children directly. Preserve any trailing\n // whitespace nodes that follow the `<p>` in `<li>` exactly as-is.\n if (last.type === 'element' && (last as HastElement).tagName === 'p') {\n const p = last as HastElement;\n const newPChildren = dropTrailingBackrefs(p.children as ElementContent[]);\n if (newPChildren === p.children) return liChildren;\n return liChildren.map((c, i) => (i === lastIdx ? ({ ...p, children: newPChildren } as ElementContent) : c));\n }\n\n return liChildren;\n}\n\n/**\n * Walk `hast` and return a map from normalized footnote label to the\n * cleaned-up body hast of that label's `<li>`. The body has had any\n * `<a data-footnote-backref>` anchors removed at any nesting depth so the\n * aggregate footer can emit its own per-occurrence backrefs without\n * duplicating the locally-injected one.\n */\n/**\n * Walk a body and clear `localOccurrence` props on any `<footnote-sup>`\n * placeholders we find. NESTED footnote refs inside a def body (`[^x]: see\n * [^y]`) emit placeholders whose `localOccurrence` is keyed to the parsing\n * chunk's `state.footnoteCounts`. When the aggregate footer renders the\n * harvested body under the LAST chunk's `ChunkSymbolContext.Provider`,\n * `globalOccurrenceForRef(lastChunkSym, label, localOccurrence)` resolves\n * against the wrong chunk — returning `null` and short-circuiting the\n * inline sup to render blank.\n *\n * The fix degrades gracefully: strip `localOccurrence` from harvested\n * placeholders so `FootnoteSupNumber` falls through to the\n * \"no occurrence supplied\" path — which renders a sup with the bare\n * `fnref-${label}` href (i.e. the first-occurrence anchor). Backref\n * navigation still works (any occurrence href is valid for \"jump back\");\n * the only loss is occurrence-precision for nested footnote refs in\n * aggregate-rendered bodies, which is an edge case GFM permits but rarely\n * exercised in practice. The PRIMARY render (the originating chunk's own\n * block output) is unaffected — it still has the full localOccurrence\n * resolved against the correct chunk symbol.\n */\nfunction stripLocalOccurrenceFromFootnoteSups(children: ElementContent[]): ElementContent[] {\n let changed = false;\n const out: ElementContent[] = [];\n for (const c of children) {\n if (c.type === 'element') {\n const el = c as HastElement;\n let nextEl: HastElement = el;\n if (el.tagName === 'footnote-sup' && el.properties && 'localOccurrence' in el.properties) {\n const { localOccurrence: _drop, ...rest } = el.properties;\n nextEl = { ...el, properties: rest };\n changed = true;\n }\n // Recurse into element children to catch nested placeholders.\n const newChildren = stripLocalOccurrenceFromFootnoteSups(nextEl.children as ElementContent[]);\n if (newChildren !== nextEl.children) {\n nextEl = { ...nextEl, children: newChildren };\n changed = true;\n }\n out.push(nextEl);\n } else {\n out.push(c);\n }\n }\n return changed ? out : children;\n}\n\nexport function extractDefBodiesFromHast(hast: HastRoot, clobberPrefix?: string): Map<string, ElementContent[]> {\n const out = new Map<string, ElementContent[]>();\n visit(hast, 'element', (sectionNode) => {\n const sec = sectionNode as HastElement;\n if (sec.tagName !== 'section') return;\n if (!(sec.properties && 'dataFootnotes' in sec.properties)) return;\n visit(sec, 'element', (liNode) => {\n const li = liNode as HastElement;\n if (li.tagName !== 'li') return;\n const idProp = li.properties?.id;\n if (typeof idProp !== 'string') return;\n const sourceId = sourceIdFromFootnoteLiId(idProp, clobberPrefix);\n if (sourceId === null) return;\n const normalized = normalizeId(sourceId);\n const stripped = stripBackrefs(li.children as ElementContent[]);\n // Defuse any nested `<footnote-sup>` placeholders whose local\n // occurrence indices belong to a different chunk than where the\n // body will eventually be rendered. See the function's JSDoc.\n out.set(normalized, stripLocalOccurrenceFromFootnoteSups(stripped));\n });\n // SKIP descent into this section's children so a NESTED\n // `<section data-footnotes>` (rare — produced only via user-supplied\n // raw HTML inside a def body that survives rehype-raw + sanitize)\n // isn't double-processed by both the outer visit's recursion and the\n // inner visit's enumeration of its parent. Without the SKIP, an\n // `<li>` inside the nested section is harvested twice; `out.set` is\n // last-write-wins so a nested mutation can stomp a correctly-\n // extracted outer body. SKIP scopes harvest to the outer section\n // and leaves nested footnote sections for whatever tool authored\n // them to handle.\n return SKIP;\n });\n return out;\n}\n","/**\n * Aggregate footnote section for cross-chunk coordination.\n *\n * In standalone mode mdast-util-to-hast emits one `<section data-footnotes>`\n * per parse. In coordinated mode (multiple `<AIMarkdown>` chunks sharing a\n * documentId under `<AIMarkdownDocuments>`) each chunk's local section is\n * suppressed (`renderBlocksWithCache` skips the synthetic plan item when\n * `postOptions.registry` is set). This component takes its place: it renders\n * exactly one consolidated `<section data-footnotes>` at the end of each\n * document's LAST mounted chunk, with all defs across chunks in global\n * footnote-number order.\n *\n * Why per-chunk component instead of a sibling: each `<AIMarkdownContent>`\n * already subscribes to its registry via useSyncExternalStore. Rendering the\n * aggregate inside the same component avoids a second subscriber and keeps\n * the footer naturally positioned at the end of the markdown output. When a\n * new chunk mounts and becomes the last, the previously-last chunk's\n * aggregate disappears in the same React commit (returns null), and the new\n * last chunk's aggregate appears.\n *\n * Per-documentId scoping is implicit: registries are keyed by documentId in\n * `useDocumentRegistry`, so the \"last chunk\" check naturally partitions to\n * one footer per document.\n *\n * @module components/aggregateFootnotesIfLast\n */\nimport { memo, useMemo, type FC } from 'react';\nimport type { Element as HastElement, ElementContent as HastElementContent } from 'hast';\nimport { renderHastSubtree } from './markdown';\nimport type { Registry } from './documentRegistry';\nimport type { PostOptions } from './blockMemo';\n\ninterface AggregateFootnotesIfLastProps {\n registry: Registry;\n thisChunkSym: symbol;\n clobberPrefix: string;\n postOptions: PostOptions;\n preserveOrphanReferences?: boolean;\n}\n\ninterface OrderedDef {\n /** Uppercase-normalized label, used to query `registry.getRefsForLabel`. */\n normalizedLabel: string;\n /** mdast's case-folded identifier — used in HTML ids so the aggregate\n * footer's `<li id>` matches the inline sup's anchor href exactly. */\n sourceIdentifier: string;\n bodyHast: HastElementContent[];\n n: number | null;\n withBackref: boolean;\n}\n\nfunction cloneHast<T extends HastElementContent>(node: T): T {\n return JSON.parse(JSON.stringify(node)) as T;\n}\n\n/** Whitespace-only text node — produced by mdast-util-to-hast's\n * `state.wrap(content, true)` to interleave `\\n` between block-level\n * `<li>` children. We have to look past these to find the actual tail. */\nfunction isWhitespaceText(c: HastElementContent): boolean {\n return c.type === 'text' && /^\\s*$/.test((c as { value: string }).value);\n}\n\n/** Index of the LAST meaningful (non-whitespace-text) child of `<li>`, or\n * -1 if no such child exists. Used to decide where to append backrefs:\n * mdast-util-to-hast's contract is \"if the tail of `<li>`'s content array\n * is `<p>`, push backrefs into it; else push them directly to `<li>`'s\n * content\". The tail check must skip wrap-emitted `\\n` text nodes that\n * surround the meaningful children, otherwise we'd wrongly classify the\n * trailing `\\n` as the tail and bypass the `<p>` append path. */\nfunction lastMeaningfulIdx(children: HastElementContent[]): number {\n for (let i = children.length - 1; i >= 0; i--) {\n if (!isWhitespaceText(children[i])) return i;\n }\n return -1;\n}\n\n/**\n * Build a backref anchor for a specific occurrence of a footnote ref.\n * Matches mdast-util-to-hast's default `defaultFootnoteBackContent`:\n * - Anchor content is always the text `↩`.\n * - When occurrence > 1, a child `<sup>${N}</sup>` is appended so the\n * digit renders as a superscript (visually `↩²`, `↩³`, …) instead of\n * a flat string like `↩2`.\n * - The 1st occurrence href is bare `#fnref-${id}`; the N-th (N > 1)\n * href is `#fnref-${id}-${N}` to match `FootnoteSupNumber`'s\n * suffix-disambiguated id on the inline sup side.\n */\nfunction buildBackref(href: string, occurrence: number, globalNumber: number): HastElement {\n const children: HastElement['children'] = [{ type: 'text', value: '↩' }];\n if (occurrence > 1) {\n children.push({\n type: 'element',\n tagName: 'sup',\n properties: {},\n children: [{ type: 'text', value: String(occurrence) }],\n });\n }\n const ariaLabel =\n occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`;\n return {\n type: 'element',\n tagName: 'a',\n properties: {\n href,\n dataFootnoteBackref: '',\n className: ['data-footnote-backref'],\n ariaLabel,\n },\n children,\n };\n}\n\nfunction buildAggregateTree(\n registry: Registry,\n clobberPrefix: string,\n preserveOrphanReferences = false\n): HastElement | null {\n // Walk chunkOrder; collect first occurrence per FOOTNOTE label in source\n // order. Mirrors `registry.globalNumber`'s numbering semantics so the n\n // values match the inline `<sup>` numbers. Link/image refs share the\n // `refs` array but belong to a disjoint namespace — they must be skipped\n // here, otherwise a link-ref to a label sharing text with a footnote-def\n // would cause a duplicate `<li>` in the aggregate footer.\n const seen = new Set<string>();\n const ordered: OrderedDef[] = [];\n for (const sym of registry.chunkOrder) {\n const data = registry.chunkData.get(sym);\n if (!data) continue;\n for (const ref of data.refs) {\n if (ref.kind !== 'footnote') continue;\n if (seen.has(ref.label)) continue;\n seen.add(ref.label);\n const canonicalSym = registry.canonicalFootnoteFor(ref.label);\n if (!canonicalSym) continue;\n const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);\n if (!def) continue;\n const n = registry.globalNumber(ref.label);\n if (n === null) continue;\n // Fall back to the uppercase-normalized label when sourceIdentifier is\n // absent (older fixtures); production data always carries the field.\n const sourceIdentifier = def.sourceIdentifier ?? ref.label;\n ordered.push({\n normalizedLabel: ref.label,\n sourceIdentifier,\n bodyHast: def.bodyHast ?? [],\n n,\n withBackref: true,\n });\n }\n }\n\n if (preserveOrphanReferences) {\n for (const sym of registry.chunkOrder) {\n const data = registry.chunkData.get(sym);\n if (!data) continue;\n for (const [label, def] of data.defs) {\n if (seen.has(label)) continue;\n if (registry.canonicalFootnoteFor(label) !== sym) continue;\n seen.add(label);\n ordered.push({\n normalizedLabel: label,\n sourceIdentifier: def.sourceIdentifier ?? label,\n bodyHast: def.bodyHast ?? [],\n n: null,\n withBackref: false,\n });\n }\n }\n }\n\n if (ordered.length === 0) return null;\n\n const liElements: HastElement[] = ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {\n const liChildren = bodyHast.map((c) => cloneHast(c));\n if (withBackref) {\n // Emit one backref anchor per global occurrence of this label. The\n // first href uses the bare `fnref-${id}` (matches FootnoteSupNumber's\n // unsuffixed first ref); the Nth (N > 1) uses `fnref-${id}-${N}`\n // (matches FootnoteSupNumber's `-N` suffix on subsequent refs).\n //\n // A single space text node precedes each anchor so adjacent backrefs\n // don't run together visually (and so the first backref doesn't butt\n // up against the def body's trailing text). This mirrors what\n // mdast-util-to-hast's default footer naturally produces: the trailing\n // newline in the def's source becomes a text \" \" between body and\n // backref, plus an explicit space separator between consecutive\n // backrefs (see mdast-util-to-hast `lib/footer.js`).\n const totalRefs = registry.getRefsForLabel(normalizedLabel);\n // Match mdast-util-to-hast's append rule: if the TAIL of the def\n // body (skipping wrap-emitted `\\n`) is `<p>`, push backrefs into\n // it; otherwise push them at the end of the `<li>` directly. The\n // previous logic searched for the last `<p>` anywhere in the body,\n // which mis-placed the backref BEFORE a trailing `<pre>` /\n // `<blockquote>` / etc. for multi-block defs.\n const tailIdx = lastMeaningfulIdx(liChildren);\n const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;\n const dest =\n tail && tail.type === 'element' && (tail as HastElement).tagName === 'p' ? (tail as HastElement) : null;\n const appended: HastElementContent[] = [];\n for (let i = 1; i <= Math.max(totalRefs, 1); i++) {\n appended.push({ type: 'text', value: ' ' });\n const href =\n i === 1 ? `#${clobberPrefix}fnref-${sourceIdentifier}` : `#${clobberPrefix}fnref-${sourceIdentifier}-${i}`;\n appended.push(buildBackref(href, i, n ?? 0));\n }\n if (dest) {\n dest.children = [...dest.children, ...appended];\n } else if (tailIdx !== -1) {\n // Splice after the meaningful tail so any subsequent trailing\n // whitespace (`\\n` from state.wrap) survives at the end of the\n // <li>, matching mdast-util-to-hast's post-wrap shape:\n // [..., <tail-block>, ...backrefs, \"\\n\"]\n liChildren.splice(tailIdx + 1, 0, ...appended);\n } else {\n liChildren.push(...appended);\n }\n }\n return {\n type: 'element',\n tagName: 'li',\n properties: {\n id: `${clobberPrefix}fn-${sourceIdentifier}`,\n ...(n !== null ? { value: n } : {}),\n },\n children: liChildren,\n };\n });\n\n return {\n type: 'element',\n tagName: 'section',\n properties: {\n className: ['footnotes'],\n dataFootnotes: true,\n // a11y: name the section landmark so screen readers still announce it\n // even though the visible \"Footnotes\" h2 is omitted in coordinated mode.\n ariaLabel: 'Footnotes',\n },\n children: [\n // Conventional separator above the footnote list. The default\n // mdast-util-to-hast footer doesn't emit one (GitHub renders the\n // separation via CSS `border-top` on `.footnotes`); we render a literal\n // `<hr>` so the visual break is preserved without sanitize-friendly CSS.\n {\n type: 'element',\n tagName: 'hr',\n properties: {},\n children: [],\n },\n {\n type: 'element',\n tagName: 'ol',\n properties: {},\n children: liElements,\n },\n ],\n };\n}\n\nconst AggregateFootnotesIfLastImpl: FC<AggregateFootnotesIfLastProps> = ({\n registry,\n thisChunkSym,\n clobberPrefix,\n postOptions,\n preserveOrphanReferences = false,\n}) => {\n // Memoize the hast tree by registry.version + clobberPrefix +\n // preserveOrphanReferences. Without this, every parent re-render walks\n // `registry.chunkOrder` (O(N) per call) and rebuilds the tree even when\n // the underlying registry state is unchanged — the parent re-renders on\n // every `_notify` from any chunk, which scales as O(N) on initial mount.\n // The aggregate is content-determined by (version, prefix, orphan-flag);\n // anything else (postOptions identity changes that don't change render\n // output) is irrelevant to the tree.\n const tree = useMemo(\n () => buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [registry, registry.version, clobberPrefix, preserveOrphanReferences]\n );\n const order = registry.chunkOrder;\n if (order.length === 0) return null;\n if (order[order.length - 1] !== thisChunkSym) return null;\n if (!tree) return null;\n // `renderHastSubtree` mutates its input tree in place (see comment on\n // that function: it assumes the tree is freshly produced per render).\n // Our `tree` is memoised by registry.version, so a non-version-bumping\n // parent re-render would re-enter the same cached tree. Any non-\n // idempotent transform (a user-supplied non-idempotent `urlTransform`\n // is the realistic case) would then compound on every re-render. Clone\n // before rendering so the cached `tree` stays pristine.\n return <>{renderHastSubtree(cloneHast(tree), postOptions)}</>;\n};\n\nexport const AggregateFootnotesIfLast = memo(AggregateFootnotesIfLastImpl);\nAggregateFootnotesIfLast.displayName = 'AggregateFootnotesIfLast';\n","/**\n * Hook for referential stability of deep-equal values.\n *\n * @module hooks/useStableValue\n */\n\nimport { useRef, useLayoutEffect, useEffect } from 'react';\nimport isEqual from 'lodash-es/isEqual';\n\n// Use layout effect on the client (synchronous after commit) and fall back to\n// useEffect during SSR to avoid the \"useLayoutEffect does nothing on the server\"\n// warning. Synchronous commit is what we want — it closes the window between\n// commit and ref advancement where an intermediate synchronous re-render would\n// otherwise see a stale cached reference.\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\n/**\n * Returns a referentially stable version of `value`.\n *\n * On each render the new value is deep-compared (via `lodash/isEqual`) against\n * the previous one. If they are structurally equal the *previous* reference is\n * returned, preventing unnecessary re-renders in downstream `useMemo` / `useEffect`\n * consumers that depend on reference equality.\n *\n * The ref is updated in a layout effect (not during render) so that the cached\n * reference only advances on COMMITTED renders. In concurrent mode a render\n * may be discarded (e.g. by Suspense); writing to the ref during render would\n * let values from discarded renders pollute the cache and leak into subsequent\n * committed renders. Layout effects run synchronously right after commit, which\n * closes the window where a same-tick re-render could otherwise observe a stale\n * `ref.current` and hand back an outdated reference.\n *\n * @typeParam T - The value type.\n * @param value - The potentially new value to stabilize.\n * @returns The previous reference when deep-equal, otherwise the new value.\n *\n * @example\n * ```tsx\n * const stableConfig = useStableValue(config);\n * // stableConfig keeps the same reference as long as config is deep-equal.\n * ```\n */\nexport default function useStableValue<T>(value: T): T {\n const ref = useRef(value);\n\n // eslint-disable-next-line react-hooks/refs\n const prev = ref.current;\n const stableValue = isEqual(prev, value) ? prev : value;\n\n useIsomorphicLayoutEffect(() => {\n ref.current = stableValue;\n }, [stableValue]);\n\n return stableValue;\n}\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n","import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n","import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n","import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n","import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n","/**\n * Default typography wrapper component.\n *\n * Renders a `<div>` container that applies CSS class names for the active\n * variant and color scheme, and sets the root font-size as an inline style.\n * The corresponding CSS custom properties are defined in the SCSS variant\n * files under `typography/variants/`.\n *\n * Consumers can replace this with a custom {@link AIMarkdownTypographyComponent}\n * via the `Typography` prop on `<AIMarkdown>`.\n *\n * @module components/typography/Default\n */\n\nimport { memo, useMemo } from 'react';\nimport type { AIMarkdownTypographyProps } from '../../defs';\n\nconst DefaultTypography = memo(({ children, fontSize, variant, colorScheme, style }: AIMarkdownTypographyProps) => {\n const className = useMemo(\n () => ['aim-typography-root', variant, colorScheme].filter(Boolean).join(' '),\n [variant, colorScheme]\n );\n const mergedStyle = useMemo(() => ({ width: '100%' as const, fontSize, ...style }), [fontSize, style]);\n return (\n <div className={className} style={mergedStyle}>\n {children}\n </div>\n );\n});\n\nDefaultTypography.displayName = 'DefaultTypography';\n\nexport default DefaultTypography;\n"],"mappings":";;;AAuBA,SAAS,WAAAA,UAAS,QAAAC,OAAM,SAAAC,cAAiC;;;ACbzD,SAA4B,eAAe,YAAY,OAAO,eAAe;;;ACH7E,SAAS,iBAAiB;AACxB,OAAK,WAAW,CAAC;AACjB,OAAK,OAAO;AACd;AAEA,IAAO,yBAAQ;;;ACoBf,SAAS,GAAG,OAAO,OAAO;AACxB,SAAO,UAAU,SAAU,UAAU,SAAS,UAAU;AAC1D;AAEA,IAAO,aAAQ;;;AC1Bf,SAAS,aAAa,OAAO,KAAK;AAChC,MAAI,SAAS,MAAM;AACnB,SAAO,UAAU;AACf,QAAI,WAAG,MAAM,MAAM,EAAE,CAAC,GAAG,GAAG,GAAG;AAC7B,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAO,uBAAQ;;;ACjBf,IAAI,aAAa,MAAM;AAGvB,IAAI,SAAS,WAAW;AAWxB,SAAS,gBAAgB,KAAK;AAC5B,MAAI,OAAO,KAAK,UACZ,QAAQ,qBAAa,MAAM,GAAG;AAElC,MAAI,QAAQ,GAAG;AACb,WAAO;AAAA,EACT;AACA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sBAAsB,eAAe,aAAa;AACxD,QAAM,eAAe,eAAe,MAAM;AAC1C,QAAM,sBAAsB,eAAe,oBAAoB;AAC/D,QAAM,yBAAyB,eAAe,gBAAgB;AAG9D,QAAM,cAAcC;AAAA,IAClB,MAAO,UAAU,sBAAsB,SAAS,mBAAmB,IAAI;AAAA,IACvE,CAAC,SAAS,mBAAmB;AAAA,EAC/B;AAIA,QAAM,kBAAkBA,SAAQ,OAAO,EAAE,wBAAwB,aAAa,IAAqB,CAAC,YAAY,CAAC;AAEjH,SACE,gBAAAF,KAAC,8BAAwC,UACvC,0BAAAA;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,QAAQ;AAAA,MAER,0BAAAA;AAAA,QAAC;AAAA;AAAA,UACC,UAAU;AAAA,UACV;AAAA,UACA;AAAA,UAKA,OAAO;AAAA,UAEN,wBACC,gBAAAA,KAAC,eACC,0BAAAA,KAAC,2BAAkB,SAAS,aAAa,kBAAkB,wBAAwB,GACrF,IAEA,gBAAAA,KAAC,2BAAkB,SAAS,aAAa,kBAAkB,wBAAwB;AAAA;AAAA,MAEvF;AAAA;AAAA,EACF,GACF;AAEJ;AAyBA,IAAM,aAAaG,MAAK,mBAAmB;AAC3C,WAAW,cAAc;AAEzB,IAAO,gBAAQ;","names":["useMemo","memo","useId","Symbol","objectProto","nativeObjectToString","symToStringTag","funcProto","objectProto","funcToString","hasOwnProperty","Map","objectProto","hasOwnProperty","objectProto","hasOwnProperty","HASH_UNDEFINED","objectProto","objectProto","hasOwnProperty","freeExports","freeModule","moduleExports","Buffer","funcProto","objectProto","funcToString","hasOwnProperty","argsTag","funcTag","objectTag","freeExports","freeModule","moduleExports","objectProto","hasOwnProperty","MAX_SAFE_INTEGER","objectProto","hasOwnProperty","objectProto","hasOwnProperty","AIMarkdownRenderExtraSyntax","AIMarkdownRenderDisplayOptimizeAbility","Fragment","memo","useCallback","useId","useMemo","useRef","useSyncExternalStore","unreachable","jsx","unreachable","processor","root","jsx","visit","visit","remarkGfm","visit","visit","unified","remarkParse","visit","unified","remarkParse","visit","createContext","useContext","useMemo","global","jsx","createContext","useContext","useMemo","useContext","createContext","jsx","useContext","visit","visit","SKIP","visit","visit","SKIP","useMemo","Fragment","jsx","isWhitespaceText","lastMeaningfulIdx","useMemo","jsx","jsxs","memo","useId","useCallback","useSyncExternalStore","useMemo","useRef","Fragment","remarkGfm","useRef","useEffect","HASH_UNDEFINED","othValue","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","boolTag","dateTag","errorTag","mapTag","numberTag","regexpTag","setTag","stringTag","arrayBufferTag","dataViewTag","objectProto","propertyIsEnumerable","objectProto","hasOwnProperty","COMPARE_PARTIAL_FLAG","objectProto","hasOwnProperty","Promise","Set","mapTag","objectTag","setTag","weakMapTag","dataViewTag","COMPARE_PARTIAL_FLAG","argsTag","arrayTag","objectTag","objectProto","hasOwnProperty","useEffect","useRef","memo","useMemo","jsx","jsx","useId","useMemo","memo"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx","../src/context.tsx","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/eq.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assocIndexOf.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_listCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_ListCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_freeGlobal.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_root.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Symbol.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getRawTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_objectToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseGetTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isFunction.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_coreJsData.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isMasked.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_toSource.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsNative.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getNative.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Map.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeCreate.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_hashSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Hash.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isKeyable.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getMapData.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_MapCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_stackSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Stack.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_defineProperty.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseAssignValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assignMergeValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_createBaseFor.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseFor.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Uint8Array.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneArrayBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copyArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseCreate.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_overArg.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getPrototype.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isPrototype.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_initCloneObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isObjectLike.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsArguments.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArguments.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isLength.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArrayLike.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isArrayLikeObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/stubFalse.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isBuffer.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isPlainObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseUnary.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nodeUtil.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_safeGet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_assignValue.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copyObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseTimes.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isIndex.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayLikeKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeKeysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseKeysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/keysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/toPlainObject.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseMergeDeep.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseMerge.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/identity.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_apply.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_overRest.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/constant.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseSetToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_shortOut.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setToString.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseRest.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_isIterateeCall.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_createAssigner.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/mergeWith.js","../src/defs.ts","../src/components/shortenDocumentId.ts","../src/preprocessors/latex.ts","../src/preprocessors/index.ts","../src/components/MarkdownContent.tsx","../src/components/markdown/Markdown.tsx","../src/components/markdown/processor.ts","../src/components/markdown/transform.ts","../src/components/markdown/urlTransform.ts","../src/components/sanitizeSchema.ts","../src/components/rehypeRebaseHashLinks.ts","../src/components/rehypeFooterAdorn.ts","../src/components/blockMemo.ts","../src/components/normalizeId.ts","../src/components/collectDefLabels.ts","../src/components/AIMarkdownDocuments.tsx","../src/components/documentRegistry.ts","../src/components/remarkInjectPhantomDefs.ts","../src/components/customMdastHandlers.ts","../src/components/crossChunkPlaceholders.tsx","../src/components/chunkSymbolContext.ts","../src/components/extractContributions.ts","../src/components/extractDefBodiesFromHast.ts","../src/components/aggregateFootnotesIfLast.tsx","../src/hooks/useStableValue.ts","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setCacheAdd.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_SetCache.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arraySome.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cacheHas.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalArrays.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_mapToArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_setToArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalByTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayPush.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseGetAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayFilter.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/stubArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getSymbols.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_nativeKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/keys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_equalObjects.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_DataView.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Promise.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_Set.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_WeakMap.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsEqualDeep.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsEqual.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isEqual.js","../src/hooks/useReferenceFlipWarning.ts","../src/components/typography/Default.tsx","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayEach.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseAssign.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseAssignIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copySymbols.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getSymbolsIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_copySymbolsIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_getAllKeysIn.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_initCloneArray.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneDataView.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneRegExp.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_cloneSymbol.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_initCloneByTag.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsMap.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isMap.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/isSet.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseClone.js","../../../node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/cloneDeep.js","../src/components/extendSanitizeSchema.ts"],"sourcesContent":["/**\n * @ai-react-markdown/core\n *\n * A batteries-included React component for rendering AI-generated markdown\n * with first-class support for LaTeX math, GFM, CJK text, syntax highlighting,\n * and streaming content.\n *\n * ## Quick Start\n *\n * ```tsx\n * import AIMarkdown from '@ai-react-markdown/core';\n * import '@ai-react-markdown/core/typography/default.css';\n *\n * function App() {\n * return <AIMarkdown content=\"Hello **world**!\" />;\n * }\n * ```\n *\n * @module @ai-react-markdown/core\n */\n\n'use client';\n\nimport { useMemo, memo, useId, type CSSProperties } from 'react';\nimport AIMarkdownRenderStateProvider, {\n AIMarkdownMetadataProvider,\n AIMarkdownRenderStateProviderProps,\n AIMarkdownMetadataProviderProps,\n} from './context';\nimport { AIMDContentPreprocessor } from './preprocessors/defs';\nimport preprocessAIMDContent from './preprocessors';\nimport AIMarkdownContent from './components/MarkdownContent';\nimport {\n AIMarkdownCustomComponents,\n AIMarkdownRenderConfig,\n AIMarkdownMetadata,\n AIMarkdownTypographyComponent,\n AIMarkdownExtraStylesComponent,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n} from './defs';\nimport type { SanitizeSchema } from './components/extendSanitizeSchema';\nimport type { UrlTransform } from './components/markdown';\nimport useStableValue from './hooks/useStableValue';\nimport useReferenceFlipWarning from './hooks/useReferenceFlipWarning';\nimport DefaultTypography from './components/typography/Default';\n\n/**\n * Props for the `<AIMarkdown>` component.\n *\n * @typeParam TConfig - Custom render configuration type (extends {@link AIMarkdownRenderConfig}).\n * @typeParam TRenderData - Custom metadata type (extends {@link AIMarkdownMetadata}).\n */\nexport interface AIMarkdownProps<\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n TRenderData extends AIMarkdownMetadata = AIMarkdownMetadata,\n>\n extends\n Omit<AIMarkdownRenderStateProviderProps<TConfig>, 'streaming' | 'fontSize' | 'variant' | 'colorScheme'>,\n AIMarkdownMetadataProviderProps<TRenderData> {\n /**\n * Whether content is actively being streamed (e.g. token-by-token from an LLM).\n * When `true`, the flag is propagated via context so custom components can adapt\n * their behavior (show cursors, disable copy buttons, skip animations, etc.).\n * Defaults to `false`.\n */\n streaming?: boolean;\n /**\n * Base font size for the rendered output.\n * Accepts a CSS length string (e.g. `'14px'`, `'0.875rem'`) or a number\n * which is treated as pixels. Defaults to `'0.9375rem'`.\n */\n fontSize?: number | string;\n /** Raw markdown content to render. */\n content: string;\n /**\n * Additional preprocessors to run on the raw markdown before rendering.\n * These run *after* the built-in LaTeX preprocessor.\n */\n contentPreprocessors?: AIMDContentPreprocessor[];\n /**\n * Custom `react-markdown` component overrides.\n * Use this to replace the default renderers for specific HTML elements\n * (e.g. code blocks, links, images).\n */\n customComponents?: AIMarkdownCustomComponents;\n /**\n * Typography wrapper component. Receives `fontSize`, `variant`, and `colorScheme`.\n * Defaults to the built-in {@link DefaultTypography}.\n */\n Typography?: AIMarkdownTypographyComponent;\n /**\n * Optional extra style wrapper component rendered between the typography\n * wrapper and the markdown content. Useful for injecting additional\n * CSS scope or theme providers.\n */\n ExtraStyles?: AIMarkdownExtraStylesComponent;\n /** Typography variant name. Defaults to `'default'`. */\n variant?: AIMarkdownVariant;\n /** Color scheme name. Defaults to `'light'`. */\n colorScheme?: AIMarkdownColorScheme;\n /**\n * Stable identifier for the *logical markdown document* this `<AIMarkdown>`\n * is rendering. Used as the id namespace for all clobberable attributes\n * (`id`, hash hrefs) so two documents on the same page do not cross-link —\n * e.g. clicking a footnote `[^1]` in message A will not scroll to the\n * `[^1]` definition in message B.\n *\n * Why `documentId` and not `instanceId`: when one logical document is\n * split across multiple `<AIMarkdown>` instances (chunked / streamed\n * rendering), every chunk should share the SAME `documentId` so their\n * id-prefixes line up. The id is per-document, not per-React-instance.\n *\n * When omitted, an id is auto-generated via React's `useId()` (SSR-safe\n * and stable across re-renders). Pass an explicit value when you need\n * deterministic ids (snapshot tests, cross-component deep links) or when\n * multiple instances render the same logical document.\n *\n * Consumer-supplied values pass through `encodeURIComponent` at the prefix\n * construction site, so any string is safe — including ids with reserved\n * characters like `:`, `/`, or spaces.\n */\n documentId?: string;\n /**\n * Override the function that decides which URL protocols are allowed\n * through the FIRST sanitization gate. The default allowlist mirrors\n * `react-markdown` / GitHub: `http`, `https`, `irc`, `ircs`, `mailto`,\n * `xmpp`. Anything else is rewritten to `''`.\n *\n * **Recommended pattern**: compose with the exported\n * {@link defaultUrlTransform} so the built-in XSS protections survive,\n * and define the result at module scope so its identity is stable across\n * renders:\n *\n * ```ts\n * import AIMarkdown, { defaultUrlTransform } from '@ai-react-markdown/core';\n *\n * const ALLOWED = /^(myapp|tel):/i;\n * const URL_TRANSFORM = (url, key, node) =>\n * ALLOWED.test(url) ? url : defaultUrlTransform(url, key, node);\n *\n * function App() {\n * return <AIMarkdown urlTransform={URL_TRANSFORM} ... />;\n * }\n * ```\n *\n * **Regex-escaping**: scheme names per RFC 3986 may contain `+`, `-`, and\n * `.` (e.g. `web+app`, `coap+tcp`). All three are regex metacharacters,\n * so write `/^web\\+app:/i` rather than `/^web+app:/i`. The latter would\n * match URLs starting with `we`, `wee`, `weee`, … and silently broaden\n * the allowlist.\n *\n * **Reference stability matters.** The block-memo cache treats this prop\n * as a dependency. Defining the function inline (`urlTransform={(url) =>\n * …}`) creates a new closure on every parent render, discards the cache\n * for the entire markdown document on each render, and effectively\n * disables Phase 5 memoization. In development the library will\n * `console.warn` if it detects this pattern.\n *\n * Allowing a protocol here is necessary but **not sufficient** to render\n * a link — the second gate (`rehype-sanitize`) also enforces its own\n * protocol allowlist. See the {@link sanitizeSchema} prop and the\n * matching {@link extendSanitizeSchema} helper for the second gate.\n *\n * **API stability**: the `UrlTransform` type tracks the upstream\n * `react-markdown` shape and may change with its major versions.\n */\n urlTransform?: UrlTransform | null;\n /**\n * Override the `rehype-sanitize` schema applied to the rendered output.\n * The library default ({@link sanitizeSchema}) extends `rehype-sanitize`'s\n * own `defaultSchema` with the `<mark>` tag, KaTeX class names, and the\n * cross-chunk coordination tags (`cross-chunk-link`, `cross-chunk-image`,\n * `footnote-sup`).\n *\n * **Recommended pattern**: build the schema with {@link extendSanitizeSchema}\n * (mutate-and-return form) so those library additions stay intact, and\n * define the result at module scope:\n *\n * ```ts\n * import AIMarkdown, { extendSanitizeSchema } from '@ai-react-markdown/core';\n *\n * const SCHEMA = extendSanitizeSchema((s) => {\n * s.protocols.href.push('myapp');\n * s.protocols.src.push('myapp');\n * });\n *\n * function App() {\n * return <AIMarkdown sanitizeSchema={SCHEMA} ... />;\n * }\n * ```\n *\n * **Footgun**: hand-rolling a schema (e.g. spreading from\n * `rehype-sanitize`'s `defaultSchema` directly) silently drops the\n * cross-chunk tag allowlist — coordinated multi-chunk rendering will then\n * lose its placeholders. Prefer the helper unless you have a specific\n * reason to opt out.\n *\n * **Reference stability matters.** Inline `<AIMarkdown sanitizeSchema={{\n * ...sanitizeSchema, protocols: {...} }}>` is mitigated by an internal\n * `useStableValue` deep-equal pass, but the safer pattern is still\n * module-scope. Development builds will `console.warn` on identity flips.\n *\n * **API stability**: the `SanitizeSchema` type tracks the upstream\n * `rehype-sanitize` shape and may change with its major versions.\n */\n sanitizeSchema?: SanitizeSchema;\n}\n\n/**\n * Root component that preprocesses markdown content and renders it through\n * a configurable remark/rehype pipeline wrapped in typography and style layers.\n */\nconst AIMarkdownComponent = <\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n TRenderData extends AIMarkdownMetadata = AIMarkdownMetadata,\n>({\n streaming = false,\n content,\n fontSize,\n contentPreprocessors,\n customComponents,\n defaultConfig,\n config,\n metadata,\n Typography = DefaultTypography,\n ExtraStyles,\n variant = 'default',\n colorScheme = 'light',\n documentId,\n urlTransform,\n sanitizeSchema,\n}: AIMarkdownProps<TConfig, TRenderData>) => {\n // Normalize fontSize: number -> px string, undefined -> default rem value.\n // Branch on `undefined` (not truthiness) so `fontSize={0}` resolves to `'0px'`.\n const usedFontSize = fontSize === undefined ? '0.9375rem' : typeof fontSize === 'number' ? `${fontSize}px` : fontSize;\n\n // Auto-generate a stable id when the consumer didn't supply one. We hand\n // back React's native `useId()` value verbatim — any URI/HTML-attribute\n // safety transformation happens downstream at the prefix construction site\n // (see `MarkdownContent.tsx`), so the value exposed via context retains its\n // React identity (useful for debugging and DevTools association).\n const generatedId = useId();\n const usedDocumentId = documentId && documentId.length > 0 ? documentId : generatedId;\n\n // Dev-mode flip-rate warnings on the two cache-sensitive props. These\n // MUST run BEFORE `useStableValue` below, otherwise a deep-equal collapse\n // would mask the very anti-pattern they exist to surface (inline schema\n // re-built every render). Both hook calls become dead code in production\n // via `__DEV__` constant folding inside the hook implementation.\n useReferenceFlipWarning(urlTransform, 'urlTransform');\n useReferenceFlipWarning(sanitizeSchema, 'sanitizeSchema');\n\n // Stabilize object/array props to prevent unnecessary re-renders\n // when the consumer creates new references on each render.\n //\n // `metadata` is INTENTIONALLY excluded — its shape is opaque to the library\n // and may be arbitrarily large (e.g. full chat session, document tree). A\n // blanket lodash isEqual deep-compare here would penalize every render with\n // an unbounded scan. Stabilizing metadata is the consumer's responsibility:\n // if their custom renderers do reference-equal work on it, they should\n // useMemo their metadata at the call site.\n const stableDefaultConfig = useStableValue(defaultConfig);\n const stableConfig = useStableValue(config);\n const stablePreprocessors = useStableValue(contentPreprocessors);\n const stableCustomComponents = useStableValue(customComponents);\n // Stabilize the sanitize schema so callers who construct it inline (against\n // our recommendation) don't blow the rehypePlugins memo on every render.\n // Also covers the common case of spreading defaults to add a single\n // protocol — the deep-equal check collapses identity churn. The flip\n // warning above runs on the RAW prop (before this stabilize) so the user\n // still sees the warning even though the cache stays warm.\n const stableSanitizeSchema = useStableValue(sanitizeSchema);\n // urlTransform is intentionally NOT stabilized — useStableValue uses\n // lodash isEqual, which is not meaningful for functions (two different\n // closures over the same logic will never be equal). The JSDoc on the\n // prop already requires callers to pass a stable function reference; we\n // forward it as-is so the behavior is honest.\n\n // Run the preprocessing pipeline (LaTeX normalization + user preprocessors).\n const usedContent = useMemo(\n () => (content ? preprocessAIMDContent(content, stablePreprocessors) : content),\n [content, stablePreprocessors]\n );\n\n // Stabilize the inline style passed to Typography; otherwise its memo wrapper\n // breaks on every parent render even when the font-size hasn't changed.\n const typographyStyle = useMemo(() => ({ '--aim-font-size-root': usedFontSize }) as CSSProperties, [usedFontSize]);\n\n return (\n <AIMarkdownMetadataProvider<TRenderData> metadata={metadata}>\n <AIMarkdownRenderStateProvider<TConfig>\n streaming={streaming}\n fontSize={usedFontSize}\n variant={variant}\n colorScheme={colorScheme}\n documentId={usedDocumentId}\n defaultConfig={stableDefaultConfig}\n config={stableConfig}\n >\n <Typography\n fontSize={usedFontSize}\n variant={variant}\n colorScheme={colorScheme}\n // Inject CSS custom properties onto the Typography root element.\n // --aim-font-size-root: absolute font-size anchor so inner CSS can\n // bypass em-compounding in deeply nested markdown structures.\n // See AIMarkdownTypographyProps.style JSDoc for the full variable list.\n style={typographyStyle}\n >\n {ExtraStyles ? (\n <ExtraStyles>\n <AIMarkdownContent\n content={usedContent}\n customComponents={stableCustomComponents}\n urlTransform={urlTransform ?? undefined}\n sanitizeSchema={stableSanitizeSchema}\n />\n </ExtraStyles>\n ) : (\n <AIMarkdownContent\n content={usedContent}\n customComponents={stableCustomComponents}\n urlTransform={urlTransform ?? undefined}\n sanitizeSchema={stableSanitizeSchema}\n />\n )}\n </Typography>\n </AIMarkdownRenderStateProvider>\n </AIMarkdownMetadataProvider>\n );\n};\n\n/**\n * A React component for rendering AI-generated markdown with rich formatting support.\n *\n * Features:\n * - GFM (tables, strikethrough, task lists, autolinks)\n * - LaTeX math rendering via KaTeX\n * - Emoji shortcodes\n * - CJK-friendly line breaking and spacing\n * - Configurable syntax extensions (highlight, definition lists, super/subscript)\n * - Configurable display optimizations (SmartyPants, pangu, comment removal)\n * - Streaming-aware rendering\n * - Customizable typography, color scheme, and component overrides\n *\n * @example\n * ```tsx\n * <AIMarkdown\n * content={markdownString}\n * streaming={isStreaming}\n * colorScheme=\"dark\"\n * config={{ extraSyntaxSupported: [AIMarkdownRenderExtraSyntax.HIGHLIGHT] }}\n * />\n * ```\n */\nconst AIMarkdown = memo(AIMarkdownComponent);\nAIMarkdown.displayName = 'AIMarkdown';\n\nexport default AIMarkdown as typeof AIMarkdownComponent;\n\n// ── Public API re-exports ───────────────────────────────────────────────────\n\n// Types\nexport type { AIMDContentPreprocessor };\nexport type {\n AIMarkdownCustomComponents,\n AIMarkdownRenderConfig,\n AIMarkdownRenderState,\n AIMarkdownMetadata,\n AIMarkdownTypographyProps,\n AIMarkdownTypographyComponent,\n AIMarkdownExtraStylesProps,\n AIMarkdownExtraStylesComponent,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n} from './defs';\n\n// Enums & Constants\nexport {\n AIMarkdownRenderExtraSyntax,\n AIMarkdownRenderDisplayOptimizeAbility,\n defaultAIMarkdownRenderConfig,\n} from './defs';\n\n// Hooks -- for custom components to access render state & metadata\nexport { useAIMarkdownRenderState, useAIMarkdownMetadata } from './context';\nexport { useStableValue };\n\n// URL handling — primitives for the `urlTransform` prop and a factory\n// helper for the `sanitizeSchema` prop on `<AIMarkdown>`.\n//\n// `urlTransform` has no helper because composition with `defaultUrlTransform`\n// is already the natural JS pattern (one-line closure). `extendSanitizeSchema`\n// is provided because the library default schema includes invariants\n// (cross-chunk tag allowlist, KaTeX className allowlist, …) that hand-rolled\n// extensions tend to silently drop — the helper bakes in the safe path.\nexport { defaultUrlTransform } from './components/markdown';\nexport type { UrlTransform } from './components/markdown';\nexport { sanitizeSchema } from './components/sanitizeSchema';\nexport { extendSanitizeSchema } from './components/extendSanitizeSchema';\nexport type { SanitizeSchema } from './components/extendSanitizeSchema';\n\n// Cross-chunk coordination wrapper + hook\nexport { AIMarkdownDocuments, useDocumentRegistry } from './components/AIMarkdownDocuments';\nexport type { AIMarkdownDocumentsProps } from './components/AIMarkdownDocuments';\n// Registry types — consumers writing typed helpers around useDocumentRegistry\n// (`function helper(r: Registry)`) need these. The Registry shape itself is a\n// public contract: we maintain backwards compat across minor versions.\nexport type { Registry, ChunkData, FootnoteDef, LinkDef, RefRecord, RefKind } from './components/documentRegistry';\n\n// Utils\nexport type { PartialDeep } from './typings/partial-deep';\n","/**\n * React context for the AIMarkdown render state.\n *\n * Provides an immutable {@link AIMarkdownRenderState} object to all descendant\n * components. The provider deep-merges user-supplied partial configuration with\n * the built-in defaults so that consumers always receive a complete config.\n *\n * @module context\n */\n\nimport { PropsWithChildren, createContext, useContext, useId, useMemo } from 'react';\nimport mergeWith from 'lodash-es/mergeWith';\nimport {\n AIMarkdownRenderConfig,\n AIMarkdownMetadata,\n AIMarkdownRenderState,\n AIMarkdownVariant,\n AIMarkdownColorScheme,\n defaultAIMarkdownRenderConfig,\n} from './defs';\nimport { shortenDocumentId } from './components/shortenDocumentId';\nimport type { PartialDeep } from './typings/partial-deep';\n\nconst AIMarkdownRenderStateContext = createContext<AIMarkdownRenderState<AIMarkdownRenderConfig> | null>(null);\n\nconst AIMarkdownMetadataContext = createContext<AIMarkdownMetadata | undefined>(undefined);\n\n/**\n * Access the current {@link AIMarkdownRenderState} from within the `<AIMarkdown>` tree.\n *\n * Must be called inside a component rendered as a descendant of `<AIMarkdown>`.\n * Throws if called outside the provider boundary.\n *\n * ### `TConfig` is a caller-asserted type, not a derived one\n *\n * The generic parameter is **an assertion the caller makes about the provider\n * above it** — TypeScript cannot verify that the actual `<AIMarkdown>` in the\n * tree was configured with a matching `defaultConfig: TConfig`. If you pass a\n * wider `TConfig` than what the provider actually carries, field access at\n * compile time will look fine but resolve to `undefined` at runtime.\n *\n * The intended pattern is that extension packages (e.g. `@ai-react-markdown/mantine`)\n * ship their own narrow wrapper hook alongside a matching `defaultConfig`, so the\n * assertion is made *once* next to the provider configuration and consumers of the\n * wrapper never touch the raw generic.\n *\n * @typeParam TConfig - Caller-asserted configuration shape (defaults to\n * {@link AIMarkdownRenderConfig}). Must be aligned with the provider's\n * `defaultConfig` — the library does not check this at runtime.\n * @returns The current render state (does not include metadata — use\n * {@link useAIMarkdownMetadata} for that).\n * @throws If called outside an `<AIMarkdown>` provider tree.\n *\n * @example Base usage — no generic, always safe:\n * ```tsx\n * function CustomCodeBlock({ children }: PropsWithChildren) {\n * const { streaming, config } = useAIMarkdownRenderState();\n * // config: AIMarkdownRenderConfig — guaranteed shape\n * }\n * ```\n *\n * @example Wrapper-hook pattern — the intended way to use an extended TConfig:\n * ```tsx\n * // In your extension package (pin the assertion in one place):\n * interface ExtendedConfig extends AIMarkdownRenderConfig {\n * themeMode: 'light' | 'dark' | 'auto';\n * }\n * export const extendedDefaultConfig: ExtendedConfig = {\n * ...defaultAIMarkdownRenderConfig,\n * themeMode: 'auto',\n * };\n * export const useExtendedRenderState = () =>\n * useAIMarkdownRenderState<ExtendedConfig>();\n *\n * // Provider is always configured with the matching defaultConfig:\n * <AIMarkdown defaultConfig={extendedDefaultConfig} ...>{children}</AIMarkdown>\n *\n * // Consumers use the narrow wrapper — no raw generic anywhere:\n * const { config } = useExtendedRenderState();\n * config.themeMode; // correctly typed and present at runtime\n * ```\n *\n * @see `@ai-react-markdown/mantine` — real-world reference. Its\n * `MantineAIMarkdownRenderConfig`, `defaultMantineAIMarkdownRenderConfig`,\n * `<MantineAIMarkdown>` (which passes `defaultConfig` by default), and\n * `useMantineAIMarkdownRenderState` implement this exact pattern.\n */\nexport function useAIMarkdownRenderState<TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig>() {\n // `as` is intentional: TConfig is a caller assertion (see JSDoc). The\n // alignment with the provider's `defaultConfig` is the caller's contract.\n const context = useContext(AIMarkdownRenderStateContext) as AIMarkdownRenderState<TConfig> | null;\n\n if (!context) {\n throw new Error('useAIMarkdownRenderState must be used within an <AIMarkdown /> component.');\n }\n\n return context;\n}\n\n/**\n * Access the current metadata from within the `<AIMarkdown>` tree.\n *\n * Metadata lives in a separate React context so that changes to metadata\n * do not cause re-renders in components that only consume render state\n * (e.g. {@link MarkdownContent}).\n *\n * ### `TMetadata` is a caller-asserted type\n *\n * Same contract as {@link useAIMarkdownRenderState} — the generic is an\n * assertion about the `metadata` prop passed to the provider above, not a\n * value TypeScript can derive. Unlike render-state config, metadata has no\n * runtime fallback: if the provider received no `metadata`, the hook returns\n * `undefined` regardless of the asserted type. Prefer wrapping this hook in\n * a project-local hook that pins `TMetadata` next to the call site that\n * actually provides the metadata.\n *\n * @typeParam TMetadata - Caller-asserted metadata shape (defaults to\n * {@link AIMarkdownMetadata}). Caller is responsible for ensuring the\n * provider's `metadata` prop matches this shape.\n * @returns The current metadata, or `undefined` if none was provided.\n *\n * @see `@ai-react-markdown/mantine` — `useMantineAIMarkdownMetadata` applies\n * the wrapper pattern to this hook, pinning `MantineAIMarkdownMetadata` in\n * a single location.\n */\nexport function useAIMarkdownMetadata<TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata>() {\n // `as` is intentional: TMetadata is a caller assertion (see JSDoc).\n return useContext(AIMarkdownMetadataContext) as TMetadata | undefined;\n}\n\n/** Props for {@link AIMarkdownRenderStateProvider}. */\nexport interface AIMarkdownRenderStateProviderProps<\n TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig,\n> extends PropsWithChildren {\n streaming: boolean;\n fontSize: string;\n variant: AIMarkdownVariant;\n colorScheme: AIMarkdownColorScheme;\n /**\n * Logical-document identifier used as the id namespace for clobberable\n * attributes (id / hash hrefs). Optional — when omitted, the provider\n * auto-generates one via {@link useId} so the provider stays drop-in\n * usable for direct consumers (e.g. extension packages that don't go\n * through `<AIMarkdown>`).\n *\n * Pass the SAME value to multiple providers / `<AIMarkdown>` instances\n * when they render chunks of the same logical document — their id\n * prefixes will align so cross-chunk anchors and (once the parser sees\n * the full doc) footnote navigation work.\n */\n documentId?: string;\n /**\n * Base default config to merge against. When omitted, falls back to\n * {@link defaultAIMarkdownRenderConfig}. Sub-packages (e.g. mantine) can\n * pass their own extended defaults here.\n */\n defaultConfig?: TConfig;\n /** Partial config that will be deep-merged with the default config. */\n config?: PartialDeep<TConfig>;\n}\n\n/** Props for {@link AIMarkdownMetadataProvider}. */\nexport interface AIMarkdownMetadataProviderProps<\n TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata,\n> extends PropsWithChildren {\n metadata?: TMetadata;\n}\n\n/**\n * Custom lodash `mergeWith` handler: arrays from the source (user config)\n * fully replace the target (default config) instead of being merged by index.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst configMergeCustomizer = (\n _objValue: any,\n srcValue: any,\n _key: string,\n _object: any,\n _source: any,\n _stack: any\n) => {\n if (Array.isArray(srcValue)) {\n return srcValue;\n }\n};\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * Provider that exposes consumer-provided metadata via a dedicated React context.\n * Separated from render state so that metadata changes do not trigger\n * re-renders in components that only consume render state.\n */\nexport const AIMarkdownMetadataProvider = <RDT extends AIMarkdownMetadata = AIMarkdownMetadata>({\n metadata,\n children,\n}: AIMarkdownMetadataProviderProps<RDT>) => {\n return <AIMarkdownMetadataContext.Provider value={metadata}>{children}</AIMarkdownMetadataContext.Provider>;\n};\n\n/**\n * Internal provider that deep-merges user config with defaults and exposes\n * the resulting {@link AIMarkdownRenderState} to the component tree.\n */\nconst AIMarkdownRenderStateProvider = <RCT extends AIMarkdownRenderConfig = AIMarkdownRenderConfig>({\n streaming,\n fontSize,\n variant,\n colorScheme,\n documentId,\n defaultConfig,\n config,\n children,\n}: AIMarkdownRenderStateProviderProps<RCT>) => {\n // Deep-merge user config with defaults into a fresh `{}` so the frozen\n // default is never mutated — avoids the extra cloneDeep pass.\n const baseConfig = defaultConfig ?? defaultAIMarkdownRenderConfig;\n const mergedConfig = useMemo(\n () => (config ? (mergeWith({}, baseConfig, config, configMergeCustomizer) as RCT) : baseConfig),\n [baseConfig, config]\n );\n\n // Fallback id when the caller did not supply one. `useId()` is SSR-safe\n // and stable per component instance. We expose its raw value; HTML/URI\n // safety is applied at the `clobberPrefix` derivation below.\n const fallbackId = useId();\n const resolvedDocumentId = documentId && documentId.length > 0 ? documentId : fallbackId;\n\n // Freeze the state object to enforce immutability downstream.\n const state = useMemo(\n () =>\n Object.freeze({\n streaming,\n fontSize,\n variant,\n colorScheme,\n documentId: resolvedDocumentId,\n // URI-fragment safe per-document prefix derived once here so downstream\n // consumers (MarkdownContent, cross-chunk placeholder components) read\n // from one canonical source. `encodeURIComponent` runs at the prefix\n // construction site, not at the documentId storage site, so consumers\n // accessing `documentId` directly still see the raw React-native value\n // (e.g. `useId()`'s `_r_0_`) while id=\"...\"/href=\"#...\" bytes are safe.\n //\n // `shortenDocumentId` is applied here (NOT at the documentId storage\n // site) for the same reason: consumer-supplied UUIDs and nanoids\n // shouldn't bloat every rendered `id=\"…\"`. Registry keying — which\n // reads `state.documentId` directly — stays on the raw value, so the\n // shortening is a pure HTML-output concern and the `useDocumentRegistry`\n // API surface is unaffected. Pure function ⇒ all chunks sharing one\n // logical documentId still produce identical prefixes.\n clobberPrefix: `${encodeURIComponent(shortenDocumentId(resolvedDocumentId))}-user-content-`,\n config: mergedConfig,\n }),\n [streaming, fontSize, variant, colorScheme, resolvedDocumentId, mergedConfig]\n );\n\n return <AIMarkdownRenderStateContext.Provider value={state}>{children}</AIMarkdownRenderStateContext.Provider>;\n};\n\nexport default AIMarkdownRenderStateProvider;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n","import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n","import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n","import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignMergeValue;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n","import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n","import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n","import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n","import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n","import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n","import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nexport default baseMergeDeep;\n","import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nexport default baseMerge;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n","import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n","import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n","import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n","import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\n\n/**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\nvar mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n});\n\nexport default mergeWith;\n","/**\n * Core type definitions, enums, and default configuration for ai-react-markdown.\n *\n * This module defines the public API surface for configuring the renderer,\n * including extra markdown syntax extensions, display optimization abilities,\n * typography theming, and the shared render state shape.\n *\n * @module defs\n */\n\nimport { ComponentType, CSSProperties, PropsWithChildren } from 'react';\nimport type { Components } from './components/markdown';\n\n/**\n * Custom component overrides for the markdown renderer.\n * Alias for the local Markdown wrapper's `Components` type (a vendored fork of\n * react-markdown's), re-exported under the library's `AIMarkdown` naming\n * convention so consumers don't need a direct `react-markdown` dependency\n * for type imports.\n */\nexport type AIMarkdownCustomComponents = Components;\n\n/**\n * Extra markdown syntax extensions beyond standard GFM.\n * Enable or disable these via {@link AIMarkdownRenderConfig.extraSyntaxSupported}.\n */\nexport enum AIMarkdownRenderExtraSyntax {\n /** `==Highlight==` syntax support. */\n HIGHLIGHT = 'HIGHLIGHT',\n /** Definition list syntax. @see https://michelf.ca/projects/php-markdown/extra/#def-list */\n DEFINITION_LIST = 'DEFINITION_LIST',\n}\n\n/**\n * Display optimization abilities applied during markdown processing.\n * Enable or disable these via {@link AIMarkdownRenderConfig.displayOptimizeAbilities}.\n */\nexport enum AIMarkdownRenderDisplayOptimizeAbility {\n /** Strip HTML comments from the content. */\n REMOVE_COMMENTS = 'REMOVE_COMMENTS',\n /** Typographic enhancements via SmartyPants (curly quotes, em-dashes, etc.). @see https://www.npmjs.com/package/smartypants */\n SMARTYPANTS = 'SMARTYPANTS',\n /** Automatically insert spaces between CJK and half-width characters. */\n PANGU = 'PANGU',\n}\n\n/**\n * Configuration object controlling which markdown extensions and\n * display optimizations are active during rendering.\n *\n * Arrays are typed `readonly` so the interface is assignable from the frozen\n * {@link defaultAIMarkdownRenderConfig}. Consumers can still pass mutable\n * arrays since `readonly T[]` is assignable from `T[]`. Note: this is a\n * compile-time hint only — user-supplied configs are not deep-frozen at\n * runtime, so the library does not guarantee the object remains unchanged\n * after it is passed in.\n */\nexport interface AIMarkdownRenderConfig {\n /** Extra syntax extensions to enable. */\n readonly extraSyntaxSupported: readonly AIMarkdownRenderExtraSyntax[];\n /** Display optimization abilities to enable. */\n readonly displayOptimizeAbilities: readonly AIMarkdownRenderDisplayOptimizeAbility[];\n /**\n * Whether to enable block-level memoization across renders.\n *\n * When `true` (default), the renderer splits each rendered document into\n * per-block units and memoizes the React subtree of each block by its\n * source identity (`raw + occurrence + ctx + position`). Unchanged blocks\n * during streaming skip `toJsxRuntime` and React reconcile work, reducing\n * per-frame cost roughly proportional to the unchanged fraction of the\n * document. Output is byte-identical to the disabled path.\n *\n * When `false`, the renderer falls back to the legacy bare `<Markdown>`\n * flow — every render runs the full pipeline end-to-end with no\n * cross-frame reuse. Useful for debugging, for environments where the\n * extra `useRef`-backed cache is undesirable, or as an escape hatch if a\n * future custom rehype plugin interacts badly with the plan abstraction.\n *\n * @default true\n */\n readonly blockMemoEnabled: boolean;\n /**\n * Default `true`. Controls Direction A: whether `<AIMarkdown>` (standalone\n * mode) protects orphan `footnoteDefinition` nodes from being silently\n * dropped by `mdast-util-to-hast` when no corresponding `footnoteReference`\n * exists. Implemented via a custom `footnoteDefinition` handler that\n * proactively registers the label in `state.footnoteOrder`.\n *\n * When `<AIMarkdown>` is wrapped in `<AIMarkdownDocuments>`, this field\n * is ignored — the wrapper's `preserveOrphanReferences` prop overrides\n * unconditionally for all chunks under it.\n */\n readonly preserveOrphanReferences: boolean;\n}\n\n/**\n * Sensible default configuration with all extensions and optimizations enabled.\n * Frozen at both the top level and the inner arrays so this shared singleton\n * cannot be mutated by any consumer.\n */\nexport const defaultAIMarkdownRenderConfig = Object.freeze({\n extraSyntaxSupported: Object.freeze([\n AIMarkdownRenderExtraSyntax.HIGHLIGHT,\n AIMarkdownRenderExtraSyntax.DEFINITION_LIST,\n ]),\n displayOptimizeAbilities: Object.freeze([\n AIMarkdownRenderDisplayOptimizeAbility.REMOVE_COMMENTS,\n AIMarkdownRenderDisplayOptimizeAbility.SMARTYPANTS,\n AIMarkdownRenderDisplayOptimizeAbility.PANGU,\n ]),\n blockMemoEnabled: true,\n preserveOrphanReferences: true,\n}) satisfies AIMarkdownRenderConfig;\n\n/**\n * Arbitrary metadata that consumers can pass through a dedicated React context.\n * Custom renderers can access this via the {@link useAIMarkdownMetadata} hook.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AIMarkdownMetadata extends Record<string, any> {}\n\n/**\n * Typography variant identifier. Built-in variant is `'default'`;\n * consumers may define additional variants via custom typography components.\n */\nexport type AIMarkdownVariant = 'default' | (string & {});\n\n/**\n * Color scheme identifier. Built-in schemes are `'light'` and `'dark'`;\n * consumers may define additional schemes via custom typography CSS.\n */\nexport type AIMarkdownColorScheme = 'light' | 'dark' | (string & {});\n\n/** Props accepted by a typography wrapper component. */\nexport interface AIMarkdownTypographyProps extends PropsWithChildren {\n /** Resolved CSS font-size value (e.g. `'14px'`, `'0.875rem'`). */\n fontSize: string;\n /** Active typography variant. */\n variant?: AIMarkdownVariant;\n /** Active color scheme. */\n colorScheme?: AIMarkdownColorScheme;\n /**\n * Inline styles injected by the core renderer. Custom Typography implementations\n * **must** merge this object into their root element's `style` to ensure CSS\n * custom properties set by the core are available to all descendant nodes.\n *\n * ### Currently injected variables\n *\n * | Variable | Value | Purpose |\n * |-------------------------|----------------|----------------------------------------------------------|\n * | `--aim-font-size-root` | `fontSize` prop | Absolute font-size anchor for the component instance. |\n *\n * #### Why `--aim-font-size-root`?\n *\n * Markdown content frequently nests elements that use relative `em` units\n * (blockquotes, lists, code blocks). Each nesting level compounds the\n * effective size — a `0.875em` code span inside a `1.125em` blockquote\n * becomes `0.984375em` of the parent, not `0.875em` of the root.\n *\n * `--aim-font-size-root` provides the component-level root font-size as an\n * absolute reference so that inner CSS rules can use\n * `font-size: var(--aim-font-size-root)` to opt out of `em` compounding\n * when a stable size is needed.\n *\n * @example\n * ```tsx\n * const MyTypography: AIMarkdownTypographyComponent = ({ children, fontSize, style }) => (\n * <div className=\"my-typo\" style={{ fontSize, ...style }}>\n * {children}\n * </div>\n * );\n * ```\n */\n style?: CSSProperties;\n}\n\n/** React component type for the typography wrapper. */\nexport type AIMarkdownTypographyComponent = ComponentType<AIMarkdownTypographyProps>;\n\n/** Props accepted by an optional extra style wrapper component. */\nexport interface AIMarkdownExtraStylesProps extends PropsWithChildren {}\n\n/** React component type for an optional extra style wrapper. */\nexport type AIMarkdownExtraStylesComponent = ComponentType<AIMarkdownExtraStylesProps>;\n\n/**\n * Immutable render state exposed to all descendant components via React context.\n * Access this with the {@link useAIMarkdownRenderState} hook.\n *\n * Metadata is provided via a separate context — use {@link useAIMarkdownMetadata} instead.\n *\n * @typeParam TConfig - Render configuration type (defaults to {@link AIMarkdownRenderConfig}).\n */\nexport interface AIMarkdownRenderState<TConfig extends AIMarkdownRenderConfig = AIMarkdownRenderConfig> {\n /** Whether the content is currently being streamed (e.g. from an LLM). */\n streaming: boolean;\n /** Resolved CSS font-size value. */\n fontSize: string;\n /** Active typography variant. */\n variant: AIMarkdownVariant;\n /** Active color scheme. */\n colorScheme: AIMarkdownColorScheme;\n /**\n * Stable identifier unique to this *logical markdown document*. Used as\n * the id namespace for clobberable attributes (`id`, hash hrefs) so two\n * documents on the same page don't cross-link — e.g. clicking a footnote\n * `[^1]` in message A won't scroll to the `[^1]` definition in message B.\n *\n * Named `documentId` (not `instanceId`) intentionally: when one logical\n * markdown document is split into multiple `<AIMarkdown>` instances\n * (chunked / streamed rendering), every chunk SHOULD share the same value\n * so id-prefixes align across the chunks.\n *\n * Auto-generated via React's `useId()` (SSR-safe, stable across\n * re-renders) when not provided by the consumer; consumer-supplied values\n * always win.\n */\n documentId: string;\n /**\n * Per-document URI-safe id prefix used by all clobberable attributes\n * (`id=\"…\"` / `href=\"#…\"`). Derived once by the provider and exposed here\n * so downstream consumers (placeholder components, cross-chunk anchor\n * logic) read a single canonical source instead of recomputing locally.\n *\n * Derivation is `${encodeURIComponent(shortenDocumentId(documentId))}-user-content-`:\n * `documentId` is first run through a MurmurHash3 → Base62 shortener\n * (no-op for ids ≤16 chars, ≤6-char hash otherwise) to keep the rendered\n * HTML compact when consumers pass long UUIDs/nanoids. The shortening\n * is purely a render-output concern — `state.documentId` itself is left\n * raw, and registry keying (`useDocumentRegistry`) reads that raw value.\n * Do not reconstruct this prefix from `documentId` at call sites; always\n * read it through this field.\n */\n clobberPrefix: string;\n /** Active render configuration. */\n config: TConfig;\n}\n","/**\n * Shorten long consumer-supplied `documentId` values down to a fixed-length\n * Base62 hash so they don't bloat every rendered `id=\"…\"` / `href=\"#…\"`.\n *\n * Trade-offs:\n * - Non-cryptographic hash (MurmurHash3 x86 32-bit) — pure speed, excellent\n * avalanche on the structured inputs we actually receive (UUIDs, nanoids,\n * `useId()` outputs, opaque chat-message ids). Collision domain is 2^32;\n * at ~77,000 active document ids the birthday-paradox collision rate hits\n * ~50%, which is far beyond any realistic single-page chat workload.\n * - Only kicks in past a length threshold (default 16) so short, hand-picked\n * ids stay readable and existing test fixtures (`'tst'`, `'doc-a'`, …)\n * plus `useId()`'s `'_r_0_'`-style output (≤7 chars) pass through untouched.\n * - Pure function: same input always yields the same output. Two chunks\n * sharing one logical `documentId` therefore still produce identical\n * prefixes, so cross-chunk anchor and footnote coordination is preserved.\n *\n * Why MurmurHash3 specifically (vs the simpler FNV-1a):\n * - FNV-1a does NOT pass SMHasher's avalanche test. For *structured* inputs\n * like UUIDs (fixed hyphen positions, hex-only alphabet) its lower bits\n * show measurable bias, which translates to a higher *practical* collision\n * rate than the theoretical 2^32 figure suggests.\n * - MurmurHash3's finalizer (`fmix32`) — `h ^= h>>>16; h = imul(h, M1);\n * h ^= h>>>13; h = imul(h, M2); h ^= h>>>16` — is purpose-built to\n * flatten any local pattern that survives the body, which is what gets\n * it through SMHasher. That's the entire engineering reason for the\n * ~30-line code-size delta vs FNV-1a.\n *\n * @module components/shortenDocumentId\n */\n\nconst BASE62_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n/** Encode a non-negative 32-bit integer as a Base62 string (no padding). */\nfunction toBase62(n: number): string {\n if (n === 0) return BASE62_ALPHABET[0];\n // Treat `n` as unsigned 32-bit so the sign bit doesn't make the loop spin.\n let v = n >>> 0;\n let out = '';\n while (v > 0) {\n out = BASE62_ALPHABET[v % 62] + out;\n v = Math.floor(v / 62);\n }\n return out;\n}\n\n/** 32-bit unsigned rotate-left, in pure JS. */\nfunction rotl32(x: number, r: number): number {\n return (((x << r) | (x >>> (32 - r))) >>> 0);\n}\n\n// MurmurHash3 x86 32-bit mixing constants — from Appleby's reference impl.\n// Naming follows the spec so the code reads against the paper verbatim.\nconst C1 = 0xcc9e2d51;\nconst C2 = 0x1b873593;\n\n// Single TextEncoder reused per process — instantiation is non-trivial and\n// the hash runs once per `<AIMarkdown>` provider commit. UTF-8 bytes (not\n// JS UTF-16 code units) are the canonical Murmur3 input so the hash stays\n// portable with reference implementations in other languages.\nconst UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();\n\n/**\n * MurmurHash3 x86 32-bit. Pure function over the UTF-8 byte sequence of `s`.\n *\n * Implementation notes:\n * - `Math.imul(a, b)` performs signed 32-bit integer multiplication with\n * proper overflow truncation. Plain `a * b` would promote to IEEE-754\n * double and silently lose precision past 2^53, breaking the hash.\n * - The body processes the input in 4-byte little-endian blocks; the\n * 1–3 byte tail is folded in with the canonical Murmur3 cascade.\n * - The finalize step (the three `imul` + `xor >>> n` lines below the\n * tail) is `fmix32` — the avalanche stage that distinguishes Murmur3\n * from naive multiply-xor hashes.\n *\n * @param s - Arbitrary input string (any Unicode).\n * @param seed - Optional 32-bit seed. Defaults to `0` for deterministic\n * reproducibility across machines.\n * @returns Unsigned 32-bit integer.\n */\nfunction murmur3_32(s: string, seed: number = 0): number {\n const bytes = UTF8_ENCODER.encode(s);\n const len = bytes.length;\n let h1 = seed >>> 0;\n const nblocks = len >>> 2;\n\n // ── Body: 4-byte little-endian blocks ───────────────────────────────────\n for (let i = 0; i < nblocks; i++) {\n const b = i * 4;\n let k1 =\n bytes[b] |\n (bytes[b + 1] << 8) |\n (bytes[b + 2] << 16) |\n (bytes[b + 3] << 24);\n\n k1 = Math.imul(k1, C1);\n k1 = rotl32(k1, 15);\n k1 = Math.imul(k1, C2);\n\n h1 ^= k1;\n h1 = rotl32(h1, 13);\n h1 = (Math.imul(h1, 5) + 0xe6546b64) >>> 0;\n }\n\n // ── Tail: 1–3 leftover bytes, folded in with classic Murmur3 cascade ────\n // The three `if`s implement C-style switch fallthrough: rem==3 runs all\n // three statements; rem==2 runs the bottom two; rem==1 runs only the last\n // block (which is the one that also mixes into h1).\n const tail = nblocks * 4;\n const rem = len & 3;\n if (rem > 0) {\n let k1 = 0;\n if (rem === 3) k1 ^= bytes[tail + 2] << 16;\n if (rem >= 2) k1 ^= bytes[tail + 1] << 8;\n k1 ^= bytes[tail];\n k1 = Math.imul(k1, C1);\n k1 = rotl32(k1, 15);\n k1 = Math.imul(k1, C2);\n h1 ^= k1;\n }\n\n // ── Finalize (fmix32): the avalanche stage ──────────────────────────────\n h1 ^= len;\n h1 ^= h1 >>> 16;\n h1 = Math.imul(h1, 0x85ebca6b);\n h1 ^= h1 >>> 13;\n h1 = Math.imul(h1, 0xc2b2ae35);\n h1 ^= h1 >>> 16;\n\n return h1 >>> 0;\n}\n\n/**\n * Shorten a `documentId` for use inside an HTML id prefix.\n *\n * @param id - The raw documentId (consumer-supplied or `useId()` fallback).\n * @param threshold - Only ids strictly longer than this get hashed.\n * Defaults to `16`, which leaves short hand-picked ids and React's\n * `useId()` outputs unchanged but catches UUIDs (36 chars) and nanoids.\n * @returns Either the original `id` (when short) or a 1–6 char Base62 hash.\n */\nexport function shortenDocumentId(id: string, threshold: number = 16): string {\n if (id.length <= threshold) return id;\n return toBase62(murmur3_32(id));\n}\n","/**\n * LaTeX preprocessing pipeline.\n *\n * Normalizes raw markdown so that LaTeX expressions survive the remark/rehype\n * rendering pipeline intact. The main entry point is {@link preprocessLaTeX},\n * which splits content into protected regions (code blocks, inline code, HTML\n * tags) and applies a sequence of transformations to the unprotected text:\n *\n * 1. Escape mhchem commands (`\\ce`, `\\pu`)\n * 2. Escape currency dollar signs (e.g. `$100`, `$1,000.50`)\n * 3. Convert bracket delimiters (`\\[...\\]`, `\\(...\\)`) to dollar delimiters\n * 4. Escape pipes inside closed LaTeX blocks to prevent GFM table interference\n * 5. Escape pipes inside unclosed LaTeX blocks (streaming partial content)\n * 6. Escape underscores inside `\\text{...}` commands\n * 7. Convert single-dollar delimiters to double-dollar delimiters\n * 8. Truncate trailing unclosed LaTeX blocks (streaming protection)\n *\n * Thanks to the implementations from the following repositories:\n * - https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n * - https://github.com/danny-avila/LibreChat/blob/main/client/src/utils/latex.ts\n *\n * @module preprocessors/latex\n */\n\ninterface Segment {\n text: string;\n isCode: boolean;\n}\n\ntype FenceMarker = '`' | '~';\n\nfunction getRepeatedMarkerLength(content: string, start: number, marker: FenceMarker): number {\n let end = start;\n while (end < content.length && content[end] === marker) {\n end += 1;\n }\n return end - start;\n}\n\n/**\n * Sticky regex for matching known HTML tags at a specific position.\n * The `y` (sticky) flag anchors the match at `lastIndex`, avoiding the need\n * to create a substring for each `<` character encountered during scanning.\n */\nconst HTML_TAG_REGEX =\n /<\\/?(span|div|p|br|hr|img|a|em|strong|b|i|u|s|sub|sup|code|pre|table|tr|td|th|thead|tbody|tfoot|ul|ol|li|dl|dt|dd|h[1-6]|blockquote|details|summary|figure|figcaption|section|article|aside|nav|header|footer|main|mark|del|ins|small|abbr|cite|dfn|kbd|samp|var|ruby|rt|rp|bdo|wbr|input|button|select|textarea|label|fieldset|legend|output|iframe|video|audio|source|canvas|svg|math|time)(?:\\s[^>]*)?\\/?>/iy;\n\n/**\n * Tags whose inner text must be treated as literal (never processed as LaTeX).\n * For these, an opening tag triggers protection of the entire paired region\n * `<tag>...</tag>` rather than just the tag itself, so dollar signs and other\n * LaTeX-looking characters inside (e.g. `<code>$x^2$</code>`) survive untouched.\n */\nconst LITERAL_CONTENT_TAGS = new Set(['code', 'pre', 'kbd', 'samp', 'math', 'svg']);\nconst LITERAL_CONTENT_CLOSE_REGEX: Record<string, RegExp> = {\n code: /<\\/code\\s*>/gi,\n pre: /<\\/pre\\s*>/gi,\n kbd: /<\\/kbd\\s*>/gi,\n samp: /<\\/samp\\s*>/gi,\n math: /<\\/math\\s*>/gi,\n svg: /<\\/svg\\s*>/gi,\n};\n\n/**\n * Is `pos` the start of a line with at most 3 spaces of leading indentation?\n *\n * CommonMark requires a fence opener/closer to sit at the beginning of a\n * line (optionally indented by up to 3 spaces). A 4-space indent turns the\n * line into an indented-code-block candidate instead, which we do not treat\n * as a fence at all.\n */\nfunction isAtLineStart(content: string, pos: number): boolean {\n let i = pos - 1;\n let spaces = 0;\n while (i >= 0 && content[i] === ' ') {\n spaces++;\n if (spaces > 3) return false;\n i--;\n }\n return i < 0 || content[i] === '\\n' || content[i] === '\\r';\n}\n\n/**\n * Find the next run of *exactly* `n` consecutive backticks at or after\n * `start`. Runs of any other length are skipped over. Returns the start\n * index of the matching run, or `-1` if no such run exists.\n *\n * Used to locate the closing delimiter of a CommonMark inline code span:\n * the closer must be a backtick run of the *same* length as the opener.\n */\nfunction findClosingBacktickRun(content: string, start: number, n: number): number {\n let i = start;\n while (i < content.length) {\n if (content[i] === '`') {\n const runLen = getRepeatedMarkerLength(content, i, '`');\n if (runLen === n) return i;\n i += runLen;\n } else {\n i += 1;\n }\n }\n return -1;\n}\n\n/**\n * Split content into alternating text and protected segments.\n * Protected segments (isCode: true) are excluded from LaTeX processing:\n * - fenced multiline code blocks: 3+ backticks or tildes at the *start of a\n * line* (≤3 space indent). Mid-line runs are never fence openers.\n * - inline code spans: a run of N backticks closed by another run of exactly\n * N backticks. May span newlines. Multi-backtick forms (e.g. `` `` `x` ``)\n * are supported so literal backtick characters can appear inside.\n * - HTML tags (e.g. `<span>$</span>` where `$` should not be treated as LaTeX).\n */\nexport function splitByProtectedRegions(content: string): Segment[] {\n const segments: Segment[] = [];\n let lastIndex = 0;\n let multilineStart = -1;\n let multilineFenceMarker: FenceMarker | null = null;\n let multilineFenceLength = 0;\n\n function pushProtected(start: number, end: number) {\n if (start > lastIndex) {\n segments.push({ text: content.substring(lastIndex, start), isCode: false });\n }\n segments.push({ text: content.substring(start, end), isCode: true });\n lastIndex = end;\n }\n\n let i = 0;\n while (i < content.length) {\n const char = content[i];\n\n // Inside a fenced code block: only look for a closing fence line.\n if (multilineStart !== -1) {\n if (char === multilineFenceMarker) {\n const runLen = getRepeatedMarkerLength(content, i, multilineFenceMarker);\n if (runLen >= multilineFenceLength && isAtLineStart(content, i)) {\n pushProtected(multilineStart, i + runLen);\n multilineStart = -1;\n multilineFenceMarker = null;\n multilineFenceLength = 0;\n i += runLen;\n continue;\n }\n i += runLen;\n continue;\n }\n i += 1;\n continue;\n }\n\n // Outside code: check fence opener, inline code span, then HTML tag.\n if (char === '`' || char === '~') {\n const runLen = getRepeatedMarkerLength(content, i, char);\n\n // Fenced code block opener: ≥3 markers and at a valid line start.\n if (runLen >= 3 && isAtLineStart(content, i)) {\n multilineStart = i;\n multilineFenceMarker = char;\n multilineFenceLength = runLen;\n i += runLen;\n continue;\n }\n\n // Inline code span: only backticks (tildes are never inline delimiters).\n if (char === '`') {\n const closeIdx = findClosingBacktickRun(content, i + runLen, runLen);\n if (closeIdx !== -1) {\n pushProtected(i, closeIdx + runLen);\n i = closeIdx + runLen;\n continue;\n }\n }\n\n // Unmatched run — skip the whole run so we don't re-interpret its\n // individual backticks on subsequent iterations.\n i += runLen;\n continue;\n }\n\n if (char === '<') {\n // Only match known HTML tags to avoid false positives with angle brackets\n // in markdown links (<Slides Demo>), math comparisons ($a < b$), etc.\n // Use sticky regex to match at position i without creating a substring.\n HTML_TAG_REGEX.lastIndex = i;\n const tagMatch = HTML_TAG_REGEX.exec(content);\n if (tagMatch) {\n let endIndex = i + tagMatch[0].length;\n // For literal-content tags (code/pre/math/...), protect the paired\n // <tag>...</tag> region so inner `$` never enters LaTeX processing.\n const tagName = tagMatch[1].toLowerCase();\n const isOpeningPairedTag =\n content[i + 1] !== '/' && !tagMatch[0].endsWith('/>') && LITERAL_CONTENT_TAGS.has(tagName);\n if (isOpeningPairedTag) {\n const closeRegex = LITERAL_CONTENT_CLOSE_REGEX[tagName];\n closeRegex.lastIndex = endIndex;\n const closeMatch = closeRegex.exec(content);\n if (closeMatch) {\n endIndex = closeMatch.index + closeMatch[0].length;\n } else {\n // Streaming: closing tag hasn't arrived yet. Protect everything\n // to the end of input so inner `$` etc. aren't mutated before\n // the closer shows up in a later chunk.\n endIndex = content.length;\n }\n }\n pushProtected(i, endIndex);\n i = endIndex;\n continue;\n }\n }\n\n i += 1;\n }\n\n if (multilineStart !== -1) {\n pushProtected(multilineStart, content.length);\n }\n\n // Push remaining text\n if (lastIndex < content.length) {\n segments.push({ text: content.substring(lastIndex), isCode: false });\n }\n\n return segments;\n}\n\n/**\n * Escape mhchem commands in LaTeX expressions to ensure proper rendering.\n *\n * @param text Input string containing LaTeX expressions with mhchem commands\n * @returns String with escaped mhchem commands\n * @from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction escapeMhchemCommands(text: string) {\n return text.replaceAll('$\\\\ce{', '$\\\\\\\\ce{').replaceAll('$\\\\pu{', '$\\\\\\\\pu{');\n}\n\nconst CURRENCY_REGEX = /(?<![\\\\$])\\$(?!\\$)(?=\\d+(?:,\\d{3})*(?:\\.\\d+)?(?:[KMBkmb])?(?:\\s|$|[^a-zA-Z\\d]))/g;\nconst NO_ESCAPED_DOLLAR_REGEX = /(?<![\\\\$])\\$(?!\\$)/g;\n// Match \\[...\\] and \\(...\\) as LaTeX delimiters, but exclude:\n// - !\\[...\\] (markdown image)\n// - \\[...\\]( (markdown link)\nconst DELIMITERS_REGEX = /(?<!!)\\\\\\[([\\S\\s]*?[^\\\\])\\\\](?!\\()|\\\\\\((.*?)\\\\\\)/g;\nconst ARRAY_COL_SPEC_OR_PIPE_REGEX = /(\\\\begin\\{(?:array|tabular[x*]?)\\}\\{[^}]*\\})|(?<!\\\\)\\|/g;\n// Display $$ allows multiline; inline $ forbids newlines (consistent with SINGLE_DOLLAR_REGEX)\nconst LATEX_BLOCK_REGEX = /\\$\\$([\\S\\s]*?)\\$\\$|(?<![\\\\$])\\$(?!\\$)((?:[^$\\n]|\\\\\\$)*?)(?<![\\\\`])\\$(?!\\$)/g;\nconst TEXT_COMMAND = '\\\\text{';\nconst SINGLE_DOLLAR_REGEX = /(?<![\\\\$])\\$(?!\\$)((?:[^$\\n]|\\\\[$])+?)(?<!\\\\)(?<!`)\\$(?!\\$)/g;\n\n/**\n * Escape currency dollar signs (e.g. $100, $1,000.50) so they are not\n * misinterpreted as LaTeX delimiters.\n *\n * The tricky part: a `$` followed by digits might still be inside a LaTeX\n * expression (e.g. `$8.29 \\text{ B} \\times 4$`). We detect this by checking\n * whether there is an odd number of unescaped `$` on the same line after the\n * current match — if so, the current `$` is a LaTeX opener, not currency.\n */\nfunction escapeCurrencyDollarSigns(text: string): string {\n const parts: string[] = [];\n let lastIndex = 0;\n const currencyMatches = Array.from(text.matchAll(CURRENCY_REGEX));\n\n // Track the processed content of the current line incrementally\n // to avoid O(n²) from joining all parts on every match.\n let currentLineProcessed = '';\n\n for (let i = 0; i < currencyMatches.length; i++) {\n const match = currencyMatches[i];\n const segment = text.substring(lastIndex, match.index);\n parts.push(segment);\n\n // Update currentLineProcessed: keep only content after the last newline.\n const newlineIdx = Math.max(segment.lastIndexOf('\\n'), segment.lastIndexOf('\\r'));\n if (newlineIdx !== -1) {\n currentLineProcessed = segment.substring(newlineIdx + 1);\n } else {\n currentLineProcessed += segment;\n }\n\n let needEscape = true;\n let restBeforeNextMatchOrEnd = '';\n if (i < currencyMatches.length - 1) {\n const nextMatch = currencyMatches[i + 1];\n if (nextMatch.index - match.index > 1) {\n restBeforeNextMatchOrEnd = text.substring(match.index + 1, nextMatch.index);\n }\n } else {\n restBeforeNextMatchOrEnd = text.substring(match.index + 1);\n }\n const firstLineBeforeNextMatch = restBeforeNextMatchOrEnd.split(/\\r\\n|\\r|\\n/g)[0];\n if (Array.from(firstLineBeforeNextMatch.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {\n const wholeLineBeforeNextMatchWithoutCurrentDollar = currentLineProcessed + firstLineBeforeNextMatch;\n if (Array.from(wholeLineBeforeNextMatchWithoutCurrentDollar.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {\n needEscape = false;\n }\n }\n\n const replacement = needEscape ? '\\\\$' : '$';\n parts.push(replacement);\n // Append to currentLineProcessed so subsequent parity checks on the same\n // line see the correct count of unescaped `$` (e.g. a left-as-`$` opener\n // that the next match's check must count).\n currentLineProcessed += replacement;\n lastIndex = match.index + 1;\n }\n parts.push(text.substring(lastIndex));\n return parts.join('');\n}\n\n/**\n * Convert LaTeX bracket delimiters to dollar sign delimiters.\n * Converts \\[...\\] to $$...$$ and \\(...\\) to $...$\n *\n * @param text Input string containing LaTeX expressions\n * @returns String with LaTeX bracket delimiters converted to dollar sign delimiters\n * @modified from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction convertLatexDelimiters(text: string): string {\n return text.replaceAll(\n DELIMITERS_REGEX,\n (match: string, squareBracket: string | undefined, roundBracket: string | undefined): string => {\n if (squareBracket !== undefined) {\n return `$$${squareBracket}$$`;\n } else if (roundBracket !== undefined) {\n return `$${roundBracket}$`;\n }\n return match;\n }\n );\n}\n\n/**\n * Helper function: replace unescaped pipes with \\vert in LaTeX math fragments\n * @from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nconst replaceUnescapedPipes = (formula: string): string =>\n // Use \\vert{} so the control sequence terminates before the next token.\n // Preserve `|` inside \\begin{array}{...} / \\begin{tabular}{...} column specifiers.\n formula.replaceAll(ARRAY_COL_SPEC_OR_PIPE_REGEX, (match, colSpec: string | undefined) =>\n colSpec !== undefined ? match : '\\\\vert{}'\n );\n/**\n * Escape pipes in LaTeX expressions to prevent them from being interpreted as\n * column separators in markdown tables.\n *\n * @param text Input string containing LaTeX expressions\n * @returns String with pipes escaped in LaTeX expressions\n * @modified from https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useMarkdown/latex.ts\n */\nfunction escapeLatexPipes(text: string): string {\n return text.replaceAll(LATEX_BLOCK_REGEX, (match, display, inline) => {\n if (display !== undefined) return `$$${replaceUnescapedPipes(display)}$$`;\n if (inline !== undefined) return `$${replaceUnescapedPipes(inline)}$`;\n return match;\n });\n}\n\n/**\n * Whether the character at position `pos` is escaped by the immediately\n * preceding backslash run. An even-count run (including zero) means the\n * `$` is unescaped; an odd count means it is escaped. Example: `\\\\$` has\n * two preceding backslashes — the `\\` escapes the `\\`, leaving `$` real.\n */\nfunction isEscapedByBackslashRun(text: string, pos: number): boolean {\n let count = 0;\n let j = pos - 1;\n while (j >= 0 && text[j] === '\\\\') {\n count++;\n j--;\n }\n return count % 2 === 1;\n}\n\n/**\n * Find the start index of the trailing unclosed `$$` or `$` delimiter.\n *\n * Scans through all dollar-sign tokens tracking open/close state.\n * Returns the index of the last *opening* delimiter that was never closed,\n * or `-1` if every delimiter is paired.\n *\n * @param text Input string to scan.\n * @param mode `'both'` tracks `$$` and `$`; `'double-only'` tracks only `$$`.\n */\nfunction findUnclosedDelimiterStart(text: string, mode: 'both' | 'double-only'): number {\n let unclosedStart = -1;\n let i = 0;\n while (i < text.length) {\n if (text[i] === '$' && i + 1 < text.length && text[i + 1] === '$' && !isEscapedByBackslashRun(text, i)) {\n unclosedStart = unclosedStart === -1 ? i : -1;\n i += 2;\n } else if (\n mode === 'both' &&\n text[i] === '$' &&\n !isEscapedByBackslashRun(text, i) &&\n (i + 1 >= text.length || text[i + 1] !== '$')\n ) {\n unclosedStart = unclosedStart === -1 ? i : -1;\n i += 1;\n } else {\n i += 1;\n }\n }\n return unclosedStart;\n}\n\nfunction escapeLatexPipesInUnclosed(text: string): string {\n const unclosedStart = findUnclosedDelimiterStart(text, 'both');\n if (unclosedStart === -1) return text;\n\n // Escape pipes only in the unclosed tail\n const before = text.substring(0, unclosedStart);\n const delimLen = text[unclosedStart + 1] === '$' ? 2 : 1;\n const delim = text.substring(unclosedStart, unclosedStart + delimLen);\n const tail = text.substring(unclosedStart + delimLen);\n return before + delim + replaceUnescapedPipes(tail);\n}\n\n/**\n * Truncate trailing unclosed `$$` blocks (streaming protection).\n *\n * During streaming, an unclosed `$$` at the start of a line triggers\n * remarkMath's `mathFlow` tokenizer, which treats all subsequent content\n * as part of a display math block until a closing `$$` fence is found.\n * Since the closing fence hasn't arrived yet, the entire remainder of the\n * document is swallowed into one giant math node — producing a wall of\n * red KaTeX error text.\n *\n * This function detects the trailing unclosed `$$` and removes it\n * (including any preceding whitespace/newlines) so that remarkMath never\n * sees the incomplete delimiter. Once the closing delimiter arrives in\n * a later streaming chunk, the complete block will render normally.\n *\n * Only tracks `$$` — single `$` does not trigger mathFlow and is harmless\n * when `singleDollarTextMath` is `false`.\n */\nfunction truncateUnclosedLatexBlock(text: string): string {\n const unclosedStart = findUnclosedDelimiterStart(text, 'double-only');\n if (unclosedStart === -1) return text;\n\n // Strip the unclosed $$ block and any trailing whitespace before it.\n return text.substring(0, unclosedStart).trimEnd();\n}\n\n/**\n * Escape unescaped underscores within `\\text{...}` commands in LaTeX expressions.\n * For example, `\\text{node_domain}` becomes `\\text{node\\_domain}`, but\n * `\\text{node\\_domain}` stays unchanged.\n *\n * The body scan is brace-aware: nested groups `\\text{outer {inner}_x}`\n * are matched via a depth counter that respects `\\{` / `\\}` escapes and\n * the escape for `\\\\` itself, so the entire body (depth ≥ 0) is scanned\n * before we escape its underscores. An unclosed `\\text{` body (missing\n * closing brace, e.g. during streaming) is left untouched.\n *\n * @param text Input string that may contain LaTeX expressions\n * @returns String with unescaped underscores escaped within `\\text{...}` commands\n */\nfunction escapeTextUnderscores(text: string): string {\n let out = '';\n let i = 0;\n while (i < text.length) {\n const start = text.indexOf(TEXT_COMMAND, i);\n if (start === -1) {\n out += text.substring(i);\n return out;\n }\n\n out += text.substring(i, start);\n const bodyStart = start + TEXT_COMMAND.length;\n let depth = 1;\n let j = bodyStart;\n while (j < text.length && depth > 0) {\n const c = text[j];\n if (c === '\\\\' && j + 1 < text.length) {\n // Skip the escaped character so `\\{`, `\\}`, `\\\\` don't affect depth.\n j += 2;\n continue;\n }\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) break;\n }\n j++;\n }\n\n if (depth !== 0) {\n // Unclosed \\text{ — leave the remainder as-is so a later streaming\n // chunk can complete it.\n out += text.substring(start);\n return out;\n }\n\n const body = text.substring(bodyStart, j);\n const escapedBody = body.replaceAll(/(?<!\\\\)_/g, '\\\\_');\n out += `\\\\text{${escapedBody}}`;\n i = j + 1; // past closing `}`\n }\n return out;\n}\n\n/**\n * Convert single dollar delimiters to double dollar delimiters.\n * e.g. $x^2$ → $$x^2$$\n */\nfunction convertSingleToDoubleDollar(text: string): string {\n return text.replaceAll(SINGLE_DOLLAR_REGEX, (_match, content: string) => `$$${content}$$`);\n}\n\n/**\n * Main LaTeX preprocessor entry point.\n *\n * Splits the input into protected regions (code blocks, inline code, HTML tags)\n * and applies the full normalization pipeline to unprotected text segments.\n * Returns the input unchanged when no LaTeX-related characters (`$`, `\\[`, `\\(`)\n * are detected.\n *\n * @param str - Raw markdown string.\n * @returns The preprocessed string with normalized LaTeX delimiters.\n */\nexport function preprocessLaTeX(str: string): string {\n // Return early if no LaTeX patterns are found\n if (!str.includes('$') && !str.includes('\\\\[') && !str.includes('\\\\(')) return str;\n\n // Step 1: split by code blocks\n const segments = splitByProtectedRegions(str);\n\n // Step 2: process each non-code segment through the LaTeX pipeline\n const result = segments.map((segment) => {\n if (segment.isCode) return segment.text;\n\n let text = segment.text;\n text = escapeMhchemCommands(text);\n text = escapeCurrencyDollarSigns(text);\n text = convertLatexDelimiters(text);\n text = escapeLatexPipes(text);\n text = escapeLatexPipesInUnclosed(text);\n text = escapeTextUnderscores(text);\n text = convertSingleToDoubleDollar(text);\n text = truncateUnclosedLatexBlock(text);\n return text;\n });\n\n return result.join('');\n}\n","/**\n * Content preprocessing pipeline.\n *\n * Runs all preprocessors (built-in + user-supplied) in sequence before\n * the markdown string is handed to react-markdown. The built-in LaTeX\n * preprocessor always runs first, followed by any extra preprocessors\n * provided by the consumer.\n *\n * @module preprocessors\n */\n\nimport { AIMDContentPreprocessor } from './defs';\nimport { preprocessLaTeX } from './latex';\n\n/** Sequentially apply an array of preprocessor functions via left-fold. */\nfunction applyPreprocessors(value: string, ...fns: Array<AIMDContentPreprocessor>): string {\n return fns.reduce((result, fn) => fn(result), value);\n}\n\n/** Stable empty array to avoid re-renders when no extra preprocessors are given. */\nconst defaultExtraPreprocessors: AIMDContentPreprocessor[] = [];\n\n/**\n * Run the full preprocessing pipeline on raw markdown content.\n *\n * @param content - Raw markdown string.\n * @param extraPreprocessors - Optional user-supplied preprocessors appended after the built-in ones.\n * @returns The preprocessed markdown string ready for rendering.\n */\nexport default function preprocessAIMDContent(\n content: string,\n extraPreprocessors: AIMDContentPreprocessor[] = defaultExtraPreprocessors\n) {\n return applyPreprocessors(content, preprocessLaTeX, ...extraPreprocessors);\n}\n","/**\n * Core markdown rendering component.\n *\n * Wraps the local `Markdown` (a vendored fork of react-markdown — see\n * `./markdown/`) with a curated set of remark and rehype plugins for GFM,\n * math/LaTeX, emoji, CJK support, and configurable extra syntax extensions\n * and display optimizations. Plugin selection is driven by the\n * {@link AIMarkdownRenderConfig} from context.\n *\n * ## Render strategy\n *\n * Two render paths gated by `config.blockMemoEnabled` (default `true`):\n *\n * - **Block-memo path** (`BlockMemoizedRenderer`): the rendered hast is cut\n * into per-block units and memoized across frames by source identity\n * (`raw + occurrence + ctx + position triple`). Streaming append where\n * prior blocks are unchanged skips `toJsxRuntime` + React reconcile for\n * those blocks.\n *\n * - **Legacy path** (`LegacyRenderer`): the vendored `<Markdown>` is called\n * directly with no cache. Every render runs the full pipeline; output is\n * byte-identical to the block-memo path (locked in by\n * `byteEquivalence.test.tsx`).\n *\n * The branch is at the component-tree level: only one of the two child\n * renderers is mounted at a time, so the disabled path pays no `useRef` /\n * `useMemo` cost from block-memo's bookkeeping. Toggling the option at\n * runtime unmounts one and mounts the other (the discarded path's cache\n * is GC'd).\n *\n * ## Performance contract — block-level memoization\n *\n * For the cache to be effective, props that influence rendered output must\n * be referentially stable across renders. This component stabilizes its own\n * plugin arrays via `useMemo`. The outer `<AIMarkdown>` stabilizes\n * `customComponents` via `useStableValue`. If you wire `<AIMarkdownContent>`\n * directly, ensure `customComponents` is memoized at the call site.\n *\n * @module components/MarkdownContent\n */\n\nimport { Fragment, memo, useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport Markdown, { parseStage, transformStage, type Options as MarkdownOptions } from './markdown';\n\ntype RemarkPlugins = NonNullable<MarkdownOptions['remarkPlugins']>;\ntype RehypePlugins = NonNullable<MarkdownOptions['rehypePlugins']>;\ntype RemarkRehypeOptions = NonNullable<MarkdownOptions['remarkRehypeOptions']>;\nimport rehypeKatex from 'rehype-katex';\nimport rehypeRaw from 'rehype-raw';\nimport rehypeUnwrapImages from 'rehype-unwrap-images';\nimport rehypeSanitize from 'rehype-sanitize';\nimport { sanitizeSchema } from './sanitizeSchema';\nimport rehypeRebaseHashLinks from './rehypeRebaseHashLinks';\nimport rehypeFooterAdorn from './rehypeFooterAdorn';\nimport remarkBreaks from 'remark-breaks';\nimport remarkCjkFriendly from 'remark-cjk-friendly';\nimport remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough';\nimport remarkEmoji from 'remark-emoji';\nimport remarkGfm from 'remark-gfm';\nimport remarkMath from 'remark-math';\nimport { remarkDefinitionList, defListHastHandlers } from 'remark-definition-list';\nimport { remarkMark as remarkMarkHighlight } from 'remark-mark-highlight';\nimport remarkSqueezeParagraphs from 'remark-squeeze-paragraphs';\nimport remarkSmartypants from 'remark-smartypants';\nimport remarkPangu from 'remark-pangu';\nimport remarkRemoveComments from 'remark-remove-comments';\nimport { buildBlocks, createCache, renderBlocksWithCache, type Cache, type PostOptions } from './blockMemo';\nimport { useAIMarkdownRenderState } from '../context';\nimport {\n AIMarkdownCustomComponents,\n AIMarkdownRenderDisplayOptimizeAbility,\n AIMarkdownRenderExtraSyntax,\n} from '../defs';\nimport { collectDefLabels } from './collectDefLabels';\nimport { useDocumentRegistry, usePreserveOrphanReferences } from './AIMarkdownDocuments';\nimport type { Registry } from './documentRegistry';\nimport type { SanitizeSchema } from './extendSanitizeSchema';\nimport { augmentSourceWithPhantoms } from './remarkInjectPhantomDefs';\nimport { buildCrossChunkHandlers } from './customMdastHandlers';\nimport { normalizeForMatch } from './normalizeId';\nimport { crossChunkComponents } from './crossChunkPlaceholders';\nimport { extractContributions } from './extractContributions';\nimport { extractDefBodiesFromHast } from './extractDefBodiesFromHast';\nimport { AggregateFootnotesIfLast } from './aggregateFootnotesIfLast';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport type { ElementContent as HastElementContent } from 'hast';\n\n/** Module-level SSR snapshot constant for useSyncExternalStore. Hoisted out\n * of the component so its identity is stable across renders (a fresh `() => 0`\n * every render would defeat the snapshot-stability guarantees the hook\n * relies on). */\nconst REGISTRY_SSR_SNAPSHOT = () => 0;\n\n/** Maps display optimization abilities to their corresponding remark plugins. */\nconst DisplayOptimizeRemarkPluginMap = {\n [AIMarkdownRenderDisplayOptimizeAbility.REMOVE_COMMENTS]: remarkRemoveComments,\n [AIMarkdownRenderDisplayOptimizeAbility.SMARTYPANTS]: remarkSmartypants,\n [AIMarkdownRenderDisplayOptimizeAbility.PANGU]: remarkPangu,\n};\n\n/** Maps extra syntax extensions to their corresponding remark plugins. */\nconst ExtraSyntaxRemarkPluginMap = {\n [AIMarkdownRenderExtraSyntax.HIGHLIGHT]: remarkMarkHighlight,\n [AIMarkdownRenderExtraSyntax.DEFINITION_LIST]: remarkDefinitionList,\n};\n\n/** Stable empty object to avoid unnecessary re-renders when no custom components are given. */\nconst DefaultCustomComponents: AIMarkdownCustomComponents = {};\n\ninterface AIMarkdownContentProps {\n /** Preprocessed markdown string to render. */\n content: string;\n /** Optional react-markdown component overrides (e.g. custom code block renderer). */\n customComponents?: AIMarkdownCustomComponents;\n /**\n * Optional URL transform applied during the hast pipeline. When omitted,\n * the vendored Markdown wrapper falls back to its built-in\n * `defaultUrlTransform` (https/mailto/etc. allowlist).\n */\n urlTransform?: MarkdownOptions['urlTransform'];\n /**\n * Optional `rehype-sanitize` schema. When omitted, the library default\n * ({@link sanitizeSchema}) is used. Callers should produce this via\n * {@link extendSanitizeSchema} to avoid silently dropping the cross-chunk\n * tag allowlist.\n */\n sanitizeSchema?: SanitizeSchema;\n}\n\ninterface RendererProps {\n content: string;\n usedComponents: AIMarkdownCustomComponents;\n remarkPlugins: RemarkPlugins;\n rehypePlugins: RehypePlugins;\n remarkRehypeOptions: RemarkRehypeOptions;\n urlTransform: MarkdownOptions['urlTransform'];\n}\n\n/**\n * Block-memo render path. Mounted when `config.blockMemoEnabled === true`.\n * Encapsulates the `useRef`-backed cache, G3 sync flush, and the three-stage\n * unified pipeline (parse → transform → buildBlocks → renderBlocksWithCache).\n */\nconst BlockMemoizedRenderer = memo(\n ({ content, usedComponents, remarkPlugins, rehypePlugins, remarkRehypeOptions, urlTransform }: RendererProps) => {\n // Vendored Markdown options that AIMarkdown does not currently expose. They\n // are tracked in the G3 flush below so the cache stays correct if any of\n // these are ever surfaced upstream. `urlTransform` is now a real prop —\n // the remaining five are still internal `undefined`.\n const allowedElements: MarkdownOptions['allowedElements'] = undefined;\n const disallowedElements: MarkdownOptions['disallowedElements'] = undefined;\n const allowElement: MarkdownOptions['allowElement'] = undefined;\n const skipHtml: MarkdownOptions['skipHtml'] = undefined;\n const unwrapDisallowed: MarkdownOptions['unwrapDisallowed'] = undefined;\n\n // ─── Cross-chunk coordination wiring (Phase 11) ──────────────────────────\n // All effects below are NO-OP when `registry === null` (standalone mode\n // without `<AIMarkdownDocuments>`): the gating is on `registry` truthiness.\n const { documentId, clobberPrefix, config } = useAIMarkdownRenderState();\n const reactId = useId();\n const registry = useDocumentRegistry(documentId);\n // Allocate-and-publish state: the Symbol for THIS chunk PAIRED with the\n // registry it was allocated from. Modelling as state — instead of a\n // ref — makes both fields real deps for downstream effects, so React's\n // dep system (not microtask FIFO) enforces \"allocate before contribute\"\n // ordering.\n //\n // Why the registry is bundled with sym: a parent that re-renders with a\n // different `documentId` (read from context) causes `registry` to flip\n // to a NEW Registry instance on the next render. React retains state\n // across that render, so `sym` still holds the OLD registry's Symbol\n // until Effect 1's cleanup runs and clears it. If Effect 2 reads `sym`\n // directly during that gap, it contributes the stale Symbol into the\n // NEW registry — polluting `chunkData` with an unowned entry that\n // `onEmpty`'s `chunkData.size === 0` check never sees as gone, leaking\n // the registry. Storing the registry alongside the sym lets Effect 2\n // gate on `allocation.registry === registry` and skip the stale tick.\n const [allocation, setAllocation] = useState<{ registry: Registry; sym: symbol } | null>(null);\n const sym = allocation && allocation.registry === registry ? allocation.sym : null;\n\n // Subscribe to registry version changes. Without this, useMemo deps that\n // include `registry?.version` would never re-evaluate — useMemo only re-\n // runs when its component re-renders, and a version bump from another\n // chunk's contribute step doesn't trigger our re-render on its own.\n // useSyncExternalStore's subscribe handle does the wake-up: when any\n // chunk calls registry._notify, every subscribed renderer re-renders,\n // PASS 0.5 picks up new labelSet entries, PASS 1 augments + re-parses,\n // placeholder hast tags emerge, and the placeholder components (which\n // also useSyncExternalStore) resolve their numbers/URLs.\n // Subscribe identity must be stable across renders — useSyncExternalStore\n // resubscribes whenever `subscribe` changes identity, so an inline\n // `(cb) => ...` would trigger unsubscribe+resubscribe on every render.\n // For N coordinated chunks each waking on every notify, that's O(N²)\n // subscriber-list churn during initial mount.\n const subscribeRegistry = useCallback(\n (cb: () => void) => (registry ? registry.subscribe(cb) : () => {}),\n [registry]\n );\n const getRegistryVersion = useCallback(() => registry?.version ?? 0, [registry]);\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, REGISTRY_SSR_SNAPSHOT);\n\n // PASS 0: lightweight def-label scan, then publish to registry.labelSet.\n const ownLabels = useMemo(() => collectDefLabels(content ?? ''), [content]);\n\n useEffect(() => {\n if (!registry) return;\n const s = registry.registerChunk(reactId, ownLabels.footnoteLabels, ownLabels.linkLabels);\n setAllocation({ registry, sym: s });\n return () => {\n registry.releaseSymbol(reactId);\n setAllocation(null);\n };\n }, [reactId, registry, ownLabels]);\n\n // G3 — synchronous deps-diff flush. Discards the per-block cache when any\n // option that affects rendered output (but not parse output) changes\n // identity. The check runs synchronously at the top of render: an\n // `useEffect` would only fire after commit, by which time the current\n // render has already read from the (now stale) cache and emitted incorrect\n // output. The cache is best-effort memoization across renders, not state\n // the UI depends on for correctness — concurrent render aborts are safe\n // because (a) cache hits return identical node references, and (b) cache\n // misses always recompute from inputs that are themselves pure.\n //\n // Cache-memoization pattern documented above is an established exception\n // to the React Compiler purity check (rule renamed across react-hooks\n // plugin versions, so the previous block disable no longer suppresses\n // anything in v7+). See design `/tmp/phase5-block-memo-decisions.md` §4.\n const cacheRef = useRef<Cache>(createCache());\n const depsRef = useRef<{\n usedComponents: typeof usedComponents;\n remarkPlugins: typeof remarkPlugins;\n rehypePlugins: typeof rehypePlugins;\n remarkRehypeOptions: typeof remarkRehypeOptions;\n urlTransform: typeof urlTransform;\n allowedElements: typeof allowedElements;\n disallowedElements: typeof disallowedElements;\n allowElement: typeof allowElement;\n skipHtml: typeof skipHtml;\n unwrapDisallowed: typeof unwrapDisallowed;\n registry: Registry | null;\n symbol: symbol | null;\n }>({\n usedComponents,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n symbol: sym,\n });\n if (\n depsRef.current.usedComponents !== usedComponents ||\n depsRef.current.remarkPlugins !== remarkPlugins ||\n depsRef.current.rehypePlugins !== rehypePlugins ||\n depsRef.current.remarkRehypeOptions !== remarkRehypeOptions ||\n depsRef.current.urlTransform !== urlTransform ||\n depsRef.current.allowedElements !== allowedElements ||\n depsRef.current.disallowedElements !== disallowedElements ||\n depsRef.current.allowElement !== allowElement ||\n depsRef.current.skipHtml !== skipHtml ||\n depsRef.current.unwrapDisallowed !== unwrapDisallowed ||\n depsRef.current.registry !== registry ||\n depsRef.current.symbol !== sym\n ) {\n cacheRef.current = createCache();\n depsRef.current = {\n usedComponents,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n symbol: sym,\n };\n }\n\n // PASS 0.5: which labels does this chunk reference that are defined\n // elsewhere? Substring over-approximation: normalize content (resolve \\X +\n // ws-collapse + uppercase) and check against the registry's union labelSet.\n // labelSet entries are already normalized; any standard ref form contains\n // the label as substring after normalization. False-positive (wasted\n // reparse) acceptable; false-negative for backslash-escaped / multi-line\n // whitespace labels accepted as v1 limit.\n //\n // Stable reference: every `registry._notify` (3× per chunk on mount: alloc,\n // contributeLabels, contributeChunkData) bumps `registry.version`, which is\n // a useMemo dep here. Without ref-stability, every bump produces fresh Set\n // instances → `parsed` useMemo invalidates → full re-parse runs. With N\n // chunks coordinating, that's O(N²) parses at mount and a visible white\n // screen for 30+ chunks. We compare the freshly-computed Sets to the\n // previous result via a ref and return the previous reference when the\n // contents are identical — collapsing the cascade to one parse per chunk.\n const targetPhantomsRef = useRef<{ missingFootnotes: Set<string>; missingLinks: Set<string> }>({\n missingFootnotes: new Set<string>(),\n missingLinks: new Set<string>(),\n });\n const targetPhantoms = useMemo(() => {\n let nextFootnotes: Set<string>;\n let nextLinks: Set<string>;\n if (!registry) {\n nextFootnotes = new Set<string>();\n nextLinks = new Set<string>();\n } else {\n const normalized = normalizeForMatch(content ?? '');\n nextFootnotes = new Set<string>();\n nextLinks = new Set<string>();\n for (const label of registry.labelSet.footnoteLabels) {\n if (ownLabels.footnoteLabels.has(label)) continue;\n if (normalized.includes(label)) nextFootnotes.add(label);\n }\n for (const label of registry.labelSet.linkLabels) {\n if (ownLabels.linkLabels.has(label)) continue;\n if (normalized.includes(label)) nextLinks.add(label);\n }\n }\n const prev = targetPhantomsRef.current;\n if (\n nextFootnotes.size === prev.missingFootnotes.size &&\n nextLinks.size === prev.missingLinks.size &&\n [...nextFootnotes].every((l) => prev.missingFootnotes.has(l)) &&\n [...nextLinks].every((l) => prev.missingLinks.has(l))\n ) {\n return prev;\n }\n const next = { missingFootnotes: nextFootnotes, missingLinks: nextLinks };\n targetPhantomsRef.current = next;\n return next;\n // version is the freshness anchor (subscribe in placeholder components handles re-render)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [registry, registry?.version, content, ownLabels]);\n\n const effectivePreserveOrphan = usePreserveOrphanReferences(config.preserveOrphanReferences);\n // In coordinated client renders, def-only chunks may be referenced by\n // other chunks even when visible orphan rendering is disabled. Once this\n // chunk has a Symbol, keep real defs in the synthetic footer so\n // extractDefBodiesFromHast can harvest their post-pipeline bodyHast; the\n // aggregate footer below still uses effectivePreserveOrphan to decide\n // whether unreferenced defs are visible.\n const preserveForBodyHarvest = effectivePreserveOrphan || Boolean(registry && sym);\n\n // PASS 1: full parse on (possibly) augmented source, with custom handlers\n // wired through remarkRehypeOptions.\n //\n // Two activation conditions:\n // 1. `registry` present → coordinated mode → ALL 4 handlers (Direction A\n // orphan protection + Direction B cross-chunk ref placeholders).\n // 2. `registry` absent + `effectivePreserveOrphan` → standalone mode →\n // ONLY `footnoteDefinition` handler (Direction A orphan protection\n // via state.footnoteOrder push). The other 3 handlers must NOT run in\n // standalone, otherwise:\n // - `footnoteReference` would emit `<footnote-sup>` placeholder\n // which depends on registry for the number → renders null → all\n // standalone footnotes disappear (regression).\n // - `linkReference`/`imageReference` would emit cross-chunk-*\n // placeholders that also depend on registry → broken links.\n const handlers = useMemo(() => {\n if (registry) return buildCrossChunkHandlers();\n if (effectivePreserveOrphan) {\n const { footnoteDefinition } = buildCrossChunkHandlers();\n return { footnoteDefinition };\n }\n return undefined;\n }, [registry, effectivePreserveOrphan]);\n\n // Stage 1 + 2: parse → run remark/rehype pipeline. The `parsed.mdast` is\n // mutated in place during `transformStage`; the useMemo chain below keeps\n // ordering correct for `buildBlocks`.\n const parsed = useMemo(() => {\n const augmented = augmentSourceWithPhantoms(content ?? '', targetPhantoms);\n const baseHandlers = remarkRehypeOptions?.handlers ?? {};\n const mergedRemarkRehypeOptions = handlers\n ? {\n ...remarkRehypeOptions,\n handlers: { ...baseHandlers, ...handlers },\n // Phantom label sets are empty in standalone mode (no PASS 0.5\n // injection happened); the footnoteDefinition handler still reads\n // them via `state.options.phantomFootnoteLabels.has(id)`, which\n // returns false for every id → orphan-protect path proceeds.\n phantomFootnoteLabels: targetPhantoms.missingFootnotes,\n phantomLinkLabels: targetPhantoms.missingLinks,\n preserveOrphan: preserveForBodyHarvest,\n documentId,\n }\n : {\n ...remarkRehypeOptions,\n };\n return parseStage({\n children: augmented,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions: mergedRemarkRehypeOptions as RemarkRehypeOptions,\n });\n }, [\n content,\n targetPhantoms,\n remarkPlugins,\n rehypePlugins,\n remarkRehypeOptions,\n handlers,\n preserveForBodyHarvest,\n documentId,\n ]);\n const hast = useMemo(() => transformStage(parsed), [parsed]);\n\n // Cut hast into per-block units indexed back to mdast for cache identity,\n // and compute the document-wide ctx digest for cross-block invalidation.\n const built = useMemo(() => buildBlocks(parsed.mdast, hast, content ?? ''), [parsed.mdast, hast, content]);\n\n const postOptions = useMemo<PostOptions>(\n () => ({\n components: { ...crossChunkComponents, ...usedComponents },\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n // v6 fingerprint cache fields:\n registry: registry ?? undefined,\n thisChunkSymbol: sym ?? undefined,\n clobberPrefix,\n }),\n // `sym` is now real state (setSym after allocateSymbol), so it's a\n // proper dep and postOptions refreshes when allocation completes.\n // `registry?.version` stays in deps so the per-block fingerprint cache\n // path sees the latest registry version on every coordinated update.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n usedComponents,\n urlTransform,\n allowedElements,\n disallowedElements,\n allowElement,\n skipHtml,\n unwrapDisallowed,\n registry,\n registry?.version,\n sym,\n clobberPrefix,\n ]\n );\n\n // Post-PASS-1 contribute: walk the parsed mdast and publish refs/defs\n // back to the registry so other chunks can resolve cross-chunk labels.\n //\n // Guarded by a fingerprint to prevent an infinite re-render cascade:\n // contributeChunkData calls _notify → version++ → useSyncExternalStore\n // wakes this renderer → targetPhantoms recomputes (fresh Set instances)\n // → parsed re-runs (new mdast reference) → this effect would re-fire\n // and re-contribute the same data → loop. Comparing serialized payload\n // to last contribution breaks the cycle at the side-effect layer.\n //\n // Ordering: `sym` is in the dep array, so this effect re-fires after the\n // allocate effect commits its setSym(...). The previous microtask/flushSync\n // dance is gone; React's dep system enforces \"allocate before contribute\".\n const lastContributionRef = useRef<{\n registry: Registry;\n symbol: symbol;\n fp: string;\n } | null>(null);\n useEffect(() => {\n if (!registry || !sym) return;\n const refs: {\n label: string;\n kind: 'footnote' | 'link' | 'image';\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n }[] = [];\n // Collect def metadata first so the fingerprint compares only cheap\n // fields. bodyHast is sourced from the post-pipeline hast (not from a\n // bare mdast→hast walk) so def bodies inside the cross-chunk aggregate\n // render with full plugin output (math, raw HTML, defLists, …).\n const defMeta = new Map<string, { identifier: string; sourceIdentifier: string; contentSource: string }>();\n const linkDefs = new Map<string, { identifier: string; url: string; title?: string }>();\n for (const node of extractContributions(parsed.mdast, {\n phantomFootnoteLabels: targetPhantoms.missingFootnotes,\n })) {\n if (node.kind === 'ref') {\n refs.push({ label: node.label, kind: node.refKind, referenceType: node.referenceType });\n } else if (node.kind === 'fnDef') {\n defMeta.set(node.label, {\n identifier: node.label,\n sourceIdentifier: node.sourceIdentifier,\n contentSource: node.content,\n });\n } else if (node.kind === 'linkDef') {\n linkDefs.set(node.label, { identifier: node.label, url: node.url, title: node.title });\n }\n }\n const fp = JSON.stringify({\n r: refs,\n d: Array.from(defMeta.entries()).map(([k, v]) => [k, v.sourceIdentifier, v.contentSource]),\n l: Array.from(linkDefs.entries()).map(([k, v]) => [k, v.url, v.title ?? '']),\n ofn: Array.from(ownLabels.footnoteLabels).sort(),\n ol: Array.from(ownLabels.linkLabels).sort(),\n // Include targetPhantoms in the fingerprint: a phantom→resolved\n // transition (another chunk publishes a def for a label this chunk\n // references inside one of its OWN def bodies) changes the rendered\n // hast — the `<cross-chunk-link>` / `<cross-chunk-image>` placeholder\n // disappears and a real `<a>` / `<img>` takes its place — without\n // touching this chunk's refs / defMeta / linkDefs / ownLabels. Without\n // including the phantom snapshot in the fingerprint, the fp check\n // would short-circuit and the registry would keep stale bodyHast\n // forever, leaving the aggregate footer rendering the placeholder\n // long after the label was resolved.\n tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),\n tpl: Array.from(targetPhantoms.missingLinks).sort(),\n });\n if (\n lastContributionRef.current?.registry === registry &&\n lastContributionRef.current.symbol === sym &&\n lastContributionRef.current.fp === fp\n ) {\n return;\n }\n // Fingerprint changed → harvest bodyHast from the post-pipeline hast\n // and publish. Missing entries are defensive: after allocation,\n // preserveForBodyHarvest keeps real local defs in the synthetic footer\n // even when visible orphan rendering is disabled.\n const bodiesByLabel = extractDefBodiesFromHast(hast, clobberPrefix);\n const defs = new Map<\n string,\n { identifier: string; sourceIdentifier: string; contentSource: string; bodyHast: HastElementContent[] }\n >();\n for (const [label, meta] of defMeta) {\n defs.set(label, {\n identifier: meta.identifier,\n sourceIdentifier: meta.sourceIdentifier,\n contentSource: meta.contentSource,\n bodyHast: (bodiesByLabel.get(label) ?? []) as HastElementContent[],\n });\n }\n lastContributionRef.current = { registry, symbol: sym, fp };\n registry.contributeChunkData(sym, {\n refs,\n defs,\n linkDefs,\n ownFootnoteLabels: ownLabels.footnoteLabels,\n ownLinkLabels: ownLabels.linkLabels,\n });\n }, [parsed, ownLabels, registry, targetPhantoms, sym, hast, clobberPrefix]);\n\n // Intentional cache memoization via cacheRef; see G3 comment above.\n const rendered = renderBlocksWithCache(cacheRef, built.plan, built.globalCtx, postOptions);\n\n // React keys come from buildBlocks:\n // - `block-${hastOffset}` for cacheable blocks (the hast element's own\n // source offset, NOT the mdast offset — this is what makes multi-root\n // raw HTML produce unique keys when two hast siblings share one mdast\n // html node)\n // - `__footnote_section__` for the synthetic footnote section (fixed\n // literal lets its fiber state survive toggle T1→T2→T3)\n // - `inline-${offset}` for top-level whitespace / sanitized comments,\n // falling back to `inline-i${planIndex}` if the inline has no position\n // In coordinated mode, the per-chunk synthetic `<section data-footnotes>`\n // is suppressed by renderBlocksWithCache (postOptions.registry present).\n // Render the aggregate footer here so it sits at the end of the LAST\n // chunk's output. The component is a no-op when this chunk is not last.\n return (\n <ChunkSymbolContext.Provider value={sym}>\n {rendered.map(({ node, reactKey }) => (\n <Fragment key={reactKey}>{node}</Fragment>\n ))}\n {registry && sym ? (\n <AggregateFootnotesIfLast\n registry={registry}\n thisChunkSym={sym}\n clobberPrefix={clobberPrefix}\n postOptions={postOptions}\n preserveOrphanReferences={effectivePreserveOrphan}\n />\n ) : null}\n </ChunkSymbolContext.Provider>\n );\n }\n);\nBlockMemoizedRenderer.displayName = 'BlockMemoizedRenderer';\n\n/**\n * Legacy render path. Mounted when `config.blockMemoEnabled === false`.\n * Calls the vendored `<Markdown>` directly — every render runs the full\n * pipeline end-to-end with no cross-frame reuse. Output is byte-identical\n * to the block-memo path in standalone mode (validated by\n * `byteEquivalence.test.tsx`).\n *\n * **Cross-chunk coordination (Phase 11) is NOT wired through this path.**\n * Wrapping `<AIMarkdown>` with `<AIMarkdownDocuments>` while keeping\n * `blockMemoEnabled: false` silently runs without coordination — orphan\n * defs are not protected, refs across chunks don't resolve. If you need\n * cross-chunk behavior, keep `blockMemoEnabled: true` (the default).\n */\nconst LegacyRenderer = memo(\n ({ content, usedComponents, remarkPlugins, rehypePlugins, remarkRehypeOptions, urlTransform }: RendererProps) => (\n <Markdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={remarkRehypeOptions}\n components={usedComponents}\n urlTransform={urlTransform}\n >\n {content}\n </Markdown>\n )\n);\nLegacyRenderer.displayName = 'LegacyRenderer';\n\n/**\n * Internal component that assembles the remark/rehype plugin chain based on\n * the current render config, then dispatches to either the block-memo\n * renderer or the legacy renderer based on `config.blockMemoEnabled`.\n */\nconst AIMarkdownContent = memo(\n ({ content, customComponents, urlTransform, sanitizeSchema: customSanitizeSchema }: AIMarkdownContentProps) => {\n const { config, clobberPrefix } = useAIMarkdownRenderState();\n // Dev-mode flip warnings live in the parent `<AIMarkdown>` (`./../index.tsx`)\n // — they MUST run BEFORE `useStableValue` collapses identity churn, otherwise\n // an inline-but-deep-equal `sanitizeSchema` would be silently stabilized and\n // the warning would never fire. Don't add a duplicate call here.\n // Resolve schema: caller-provided override (from `extendSanitizeSchema(...)`\n // or a hand-rolled Schema) wins; otherwise the library default. Reference\n // identity is preserved by the parent `<AIMarkdown>`'s `useStableValue`,\n // so this picks one of two stable references rather than minting a new\n // object every render — important for the rehypePlugins memo below.\n const usedSanitizeSchema = customSanitizeSchema ?? sanitizeSchema;\n\n // Resolve extra-syntax remark plugins and check if definition list HAST handlers are needed.\n const { extraSyntaxRemarkPlugins, enableDefinitionList } = useMemo(\n () => ({\n extraSyntaxRemarkPlugins: config.extraSyntaxSupported.map((syntax) => ExtraSyntaxRemarkPluginMap[syntax]),\n enableDefinitionList: config.extraSyntaxSupported.includes(AIMarkdownRenderExtraSyntax.DEFINITION_LIST),\n }),\n [config.extraSyntaxSupported]\n );\n\n const displayOptimizeRemarkPlugins = useMemo(() => {\n return config.displayOptimizeAbilities.map((ability) => DisplayOptimizeRemarkPluginMap[ability]);\n }, [config.displayOptimizeAbilities]);\n\n const usedComponents = useMemo(() => {\n return customComponents ? { ...DefaultCustomComponents, ...customComponents } : DefaultCustomComponents;\n }, [customComponents]);\n\n // Stable plugin/options arrays so this component's React.memo wrapper can\n // skip re-renders when only the parent re-rendered. The vendored\n // `parseStage` rebuilds the unified processor on every call regardless —\n // there is no internal processor cache to feed.\n const remarkPlugins = useMemo<RemarkPlugins>(\n () => [\n // --- Core plugins (always active) ---\n remarkGfm,\n [\n remarkMath,\n {\n // Disable single-dollar inline math to avoid conflicts with currency\n // signs and other dollar usages; the preprocessor converts $...$ to $$...$$.\n singleDollarTextMath: false,\n },\n ],\n // --- Configurable extra syntax plugins ---\n ...extraSyntaxRemarkPlugins,\n // --- Formatting & normalization ---\n remarkBreaks,\n remarkEmoji,\n remarkSqueezeParagraphs,\n remarkCjkFriendly,\n remarkCjkFriendlyGfmStrikethrough,\n // --- Configurable display optimizations ---\n ...displayOptimizeRemarkPlugins,\n ],\n [extraSyntaxRemarkPlugins, displayOptimizeRemarkPlugins]\n );\n\n const rehypePlugins = useMemo<RehypePlugins>(\n () => [\n // Allow raw HTML through so rehype-sanitize can handle it.\n [rehypeRaw, { passThrough: [] }],\n // Sanitize HTML while allowing <mark> (highlight), KaTeX class names,\n // and any extra protocols the caller permitted via the `sanitizeSchema`\n // prop. Override `clobberPrefix` with the instance-scoped value so every\n // id and clobberable attribute is namespaced to this `<AIMarkdown>`\n // instance — the spread order is intentional: our prefix wins over any\n // caller-supplied prefix on the schema.\n [rehypeSanitize, { ...usedSanitizeSchema, clobberPrefix }],\n // Normalize the auto-generated `<section data-footnotes>`: strip the\n // sr-only `<h2>Footnotes</h2>` label and prepend `<hr>`. Keeps standalone\n // single-doc rendering visually consistent with the cross-chunk aggregate\n // footer (which builds the same shape from scratch).\n rehypeFooterAdorn,\n // Re-prefix intra-document hash hrefs so they match the ids that\n // rehype-sanitize just clobbered. Must use the SAME prefix as the schema\n // above — that's why both read from `clobberPrefix`.\n [rehypeRebaseHashLinks, { prefix: clobberPrefix }],\n rehypeKatex,\n rehypeUnwrapImages,\n ],\n [clobberPrefix, usedSanitizeSchema]\n );\n\n const remarkRehypeOptions = useMemo<RemarkRehypeOptions>(\n () => ({\n allowDangerousHtml: true,\n // Suppress mdast-util-to-hast's `user-content-` prefix on footnote\n // ids/hrefs; rehype-sanitize will apply the same prefix downstream\n // and `rehypeRebaseHashLinks` mirrors it onto matching hash hrefs.\n // Without this, ids would end up double-prefixed\n // (`user-content-user-content-fn-x`).\n clobberPrefix: '',\n handlers: {\n // Inject definition-list HAST handlers when the extension is active.\n ...(enableDefinitionList ? defListHastHandlers : {}),\n },\n }),\n [enableDefinitionList]\n );\n\n const Renderer = config.blockMemoEnabled ? BlockMemoizedRenderer : LegacyRenderer;\n return (\n <Renderer\n content={content}\n usedComponents={usedComponents}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={remarkRehypeOptions}\n urlTransform={urlTransform}\n />\n );\n }\n);\n\nAIMarkdownContent.displayName = 'AIMarkdownContent';\n\nexport default AIMarkdownContent;\n","/**\n * Synchronous Markdown component. Ported from react-markdown v10\n * (`Markdown` named/default export) and refactored to expose the pipeline as\n * three independently callable stages so callers can interpose between them\n * (notably the block-memo cache in `MarkdownContent`).\n *\n * Public stages:\n * - {@link parseStage} — `createProcessor` → `parse` → raw mdast\n * - {@link transformStage} — `runSync` → final hast root\n * - {@link renderHastSubtree} — visit transform + `toJsxRuntime` on a hast tree or block\n *\n * The legacy synchronous {@link Markdown} export is preserved and now delegates\n * to those three stages so behavior matches react-markdown 1:1.\n *\n * @module components/markdown/Markdown\n */\n\nimport { unreachable } from 'devlop';\nimport { toJsxRuntime } from 'hast-util-to-jsx-runtime';\nimport type { Element, Root as HastRoot, RootContent } from 'hast';\nimport type { Root as MdastRoot } from 'mdast';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport type { Processor } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { VFile } from 'vfile';\nimport { createFile, createProcessor } from './processor';\nimport { buildTransform } from './transform';\nimport type { Deprecation, Options } from './types';\nimport { defaultUrlTransform } from './urlTransform';\n\nconst changelog = 'https://github.com/remarkjs/react-markdown/blob/main/changelog.md';\n\n/** Mirrors the deprecation table react-markdown ships — kept verbatim so error\n * messages and changelog hashes match upstream. */\nconst deprecations: ReadonlyArray<Readonly<Deprecation>> = [\n { from: 'astPlugins', id: 'remove-buggy-html-in-markdown-parser' },\n { from: 'allowDangerousHtml', id: 'remove-buggy-html-in-markdown-parser' },\n {\n from: 'allowNode',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'allowElement',\n },\n {\n from: 'allowedTypes',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'allowedElements',\n },\n { from: 'className', id: 'remove-classname' },\n {\n from: 'disallowedTypes',\n id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n to: 'disallowedElements',\n },\n { from: 'escapeHtml', id: 'remove-buggy-html-in-markdown-parser' },\n { from: 'includeElementIndex', id: '#remove-includeelementindex' },\n {\n from: 'includeNodeIndex',\n id: 'change-includenodeindex-to-includeelementindex',\n },\n { from: 'linkTarget', id: 'remove-linktarget' },\n { from: 'plugins', id: 'change-plugins-to-remarkplugins', to: 'remarkPlugins' },\n { from: 'rawSourcePos', id: '#remove-rawsourcepos' },\n { from: 'renderers', id: 'change-renderers-to-components', to: 'components' },\n { from: 'source', id: 'change-source-to-children', to: 'children' },\n { from: 'sourcePos', id: '#remove-sourcepos' },\n { from: 'transformImageUri', id: '#add-urltransform', to: 'urlTransform' },\n { from: 'transformLinkUri', id: '#add-urltransform', to: 'urlTransform' },\n];\n\n/**\n * Validate options that have nothing to do with the input markdown — kept\n * separate so the block-memo wrapper can validate once per render rather than\n * once per block-render call.\n */\nfunction validateOptions(options: Readonly<Options>): void {\n for (const deprecation of deprecations) {\n if (Object.hasOwn(options, deprecation.from)) {\n unreachable(\n 'Unexpected `' +\n deprecation.from +\n '` prop, ' +\n (deprecation.to ? 'use `' + deprecation.to + '` instead' : 'remove it') +\n ' (see <' +\n changelog +\n '#' +\n deprecation.id +\n '> for more info)'\n );\n }\n }\n\n if (options.allowedElements && options.disallowedElements) {\n unreachable('Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other');\n }\n}\n\n/** Bundled processor + parsed mdast + VFile, ready to feed `transformStage`. */\nexport interface ParsedMarkdown {\n processor: Processor<MdastRoot, MdastRoot, HastRoot, undefined, undefined>;\n file: VFile;\n mdast: MdastRoot;\n}\n\n/**\n * Stage 1: validate options, build the unified processor, parse the markdown\n * source into raw (pre-transform) mdast. The returned `mdast` is mutated in\n * place by remark plugins during {@link transformStage}, but its top-level\n * `position` offsets remain valid keys for hast→mdast lookup.\n */\nexport function parseStage(options: Readonly<Options>): ParsedMarkdown {\n validateOptions(options);\n const processor = createProcessor(options);\n const file = createFile(options);\n const mdast = processor.parse(file);\n return { processor, file, mdast };\n}\n\n/**\n * Stage 2: run remark transformers, remark-rehype, and rehype plugins. Returns\n * the final hast Root. The mdast in {@link ParsedMarkdown} may be mutated\n * by remark transformers as a side effect of this call.\n */\nexport function transformStage(parsed: ParsedMarkdown): HastRoot {\n return parsed.processor.runSync(parsed.mdast, parsed.file);\n}\n\n/**\n * Stage 3: apply the hast visit transform (urlTransform, allow/disallow\n * filters, raw HTML handling) and render via `hast-util-to-jsx-runtime`.\n *\n * Accepts either the full hast Root or a single top-level child (typed as\n * `RootContent` to match hast's union of element/text/comment/etc.). When\n * given a single child, the child is wrapped in a synthetic Root so the\n * splice-based filters (`unwrapDisallowed`) have a parent context to work\n * against.\n *\n * Note: the visit transform mutates the input tree in place. For the legacy\n * `<Markdown>` flow this is harmless (the tree is freshly produced). For the\n * block-memo flow, hast is also fresh per render, so callers do not need to\n * defensively clone.\n */\nexport function renderHastSubtree(tree: HastRoot | RootContent, options: Readonly<Options>): ReactNode {\n const root: HastRoot = tree.type === 'root' ? tree : { type: 'root', children: [tree] };\n\n visit(\n root,\n buildTransform({\n allowedElements: options.allowedElements,\n allowElement: options.allowElement,\n disallowedElements: options.disallowedElements,\n skipHtml: options.skipHtml,\n unwrapDisallowed: options.unwrapDisallowed,\n urlTransform: options.urlTransform || defaultUrlTransform,\n })\n );\n\n return toJsxRuntime(root, {\n Fragment,\n components: options.components,\n ignoreInvalidStyle: true,\n jsx,\n jsxs,\n passKeys: true,\n passNode: true,\n });\n}\n\n/**\n * Render a markdown string to React elements.\n *\n * Mirrors `react-markdown`'s synchronous `<Markdown>` exactly: same prop\n * shape, same plugin pipeline (remark-parse → remarkPlugins → remark-rehype →\n * rehypePlugins → toJsxRuntime), same deprecation errors. Use this directly\n * via the local barrel; outside callers should keep using `<AIMarkdown>`.\n */\nexport function Markdown(options: Readonly<Options>): ReactElement {\n const parsed = parseStage(options);\n const tree = transformStage(parsed);\n return renderHastSubtree(tree, options) as ReactElement;\n}\n\nexport default Markdown;\n\n// Re-export for typing convenience at call sites that hold onto a single\n// top-level hast block.\nexport type { Element as HastElement, HastRoot, RootContent as HastChild };\n","/**\n * Unified processor and VFile setup. Ported 1:1 from react-markdown\n * v10 `createProcessor` and `createFile`.\n *\n * @module components/markdown/processor\n */\n\nimport { unreachable } from 'devlop';\nimport type { Root as HastRoot } from 'hast';\nimport type { Root as MdastRoot } from 'mdast';\nimport remarkParse from 'remark-parse';\nimport remarkRehype, { type Options as RemarkRehypeOptions } from 'remark-rehype';\nimport { type PluggableList, type Processor, unified } from 'unified';\nimport { VFile } from 'vfile';\nimport type { Options } from './types';\n\nconst emptyPlugins: PluggableList = [];\nconst emptyRemarkRehypeOptions: Readonly<RemarkRehypeOptions> = { allowDangerousHtml: true };\n\n/**\n * Build the unified processor: remark-parse → remarkPlugins → remark-rehype →\n * rehypePlugins. Returns an unfrozen processor — caller is expected to call\n * `.parse()` and `.runSync()` (or `.run()`) on it.\n */\nexport function createProcessor(\n options: Readonly<Options>\n): Processor<MdastRoot, MdastRoot, HastRoot, undefined, undefined> {\n const rehypePlugins = options.rehypePlugins || emptyPlugins;\n const remarkPlugins = options.remarkPlugins || emptyPlugins;\n const remarkRehypeOptions = options.remarkRehypeOptions\n ? { ...options.remarkRehypeOptions, ...emptyRemarkRehypeOptions }\n : emptyRemarkRehypeOptions;\n\n return unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, remarkRehypeOptions).use(rehypePlugins);\n}\n\n/**\n * Wrap the markdown string in a VFile so plugins that consume `file.value`\n * work. Mirrors react-markdown: in dev `unreachable` throws an AssertionError\n * for non-string `children`; in prod it silently no-ops, leaving `file.value`\n * undefined and unified treating the input as empty.\n */\nexport function createFile(options: Readonly<Options>): VFile {\n const children = options.children || '';\n const file = new VFile();\n\n if (typeof children === 'string') {\n file.value = children;\n } else {\n unreachable('Unexpected value `' + String(children) + '` for `children` prop, expected `string`');\n }\n\n return file;\n}\n","/**\n * Single-pass hast tree transform: rewrites raw HTML, runs `urlTransform` on\n * URL attributes, and applies `allowedElements` / `disallowedElements` /\n * `allowElement` filters. Ported 1:1 from react-markdown v10.\n *\n * @module components/markdown/transform\n */\n\nimport type { Element, Root } from 'hast';\nimport { urlAttributes } from 'html-url-attributes';\nimport type { BuildVisitor } from 'unist-util-visit';\nimport type { AllowElement, UrlTransform } from './types';\n\nexport interface TransformContext {\n allowedElements: ReadonlyArray<string> | null | undefined;\n allowElement: AllowElement | null | undefined;\n disallowedElements: ReadonlyArray<string> | null | undefined;\n skipHtml: boolean | null | undefined;\n unwrapDisallowed: boolean | null | undefined;\n urlTransform: UrlTransform;\n}\n\nexport function buildTransform(ctx: TransformContext): BuildVisitor<Root> {\n return function transform(node, index, parent) {\n if (node.type === 'raw' && parent && typeof index === 'number') {\n if (ctx.skipHtml) {\n parent.children.splice(index, 1);\n } else {\n parent.children[index] = { type: 'text', value: (node as { value: string }).value };\n }\n return index;\n }\n\n if (node.type === 'element') {\n const element = node as Element;\n let key: string;\n\n for (key in urlAttributes) {\n if (Object.hasOwn(urlAttributes, key) && Object.hasOwn(element.properties, key)) {\n const value = element.properties[key];\n const test = (urlAttributes as Record<string, ReadonlyArray<string> | null>)[key];\n if (test === null || test.includes(element.tagName)) {\n element.properties[key] = ctx.urlTransform(String(value || ''), key, element);\n }\n }\n }\n }\n\n if (node.type === 'element') {\n const element = node as Element;\n let remove = ctx.allowedElements\n ? !ctx.allowedElements.includes(element.tagName)\n : ctx.disallowedElements\n ? ctx.disallowedElements.includes(element.tagName)\n : false;\n\n if (!remove && ctx.allowElement && typeof index === 'number') {\n remove = !ctx.allowElement(element, index, parent);\n }\n\n if (remove && parent && typeof index === 'number') {\n if (ctx.unwrapDisallowed && element.children) {\n parent.children.splice(index, 1, ...element.children);\n } else {\n parent.children.splice(index, 1);\n }\n return index;\n }\n }\n\n return undefined;\n };\n}\n","/**\n * Default URL transform — same allowlist as react-markdown / GitHub.\n *\n * @module components/markdown/urlTransform\n */\n\nimport type { UrlTransform } from './types';\n\nconst safeProtocol = /^(https?|ircs?|mailto|xmpp)$/i;\n\n/**\n * Make a URL safe.\n *\n * Allows `http`, `https`, `irc`, `ircs`, `mailto`, and `xmpp` protocols, plus\n * URLs relative to the current protocol (e.g. `/foo`). Other protocols are\n * stripped to the empty string. Mirrors GitHub's behaviour and matches\n * `micromark-util-sanitize-uri` minus the URL-encoding pass.\n */\nexport const defaultUrlTransform: UrlTransform = (value) => {\n const colon = value.indexOf(':');\n const questionMark = value.indexOf('?');\n const numberSign = value.indexOf('#');\n const slash = value.indexOf('/');\n\n if (\n // No protocol → relative.\n colon === -1 ||\n // First colon is after `/`, `?`, or `#` → not a protocol.\n (slash !== -1 && colon > slash) ||\n (questionMark !== -1 && colon > questionMark) ||\n (numberSign !== -1 && colon > numberSign) ||\n // Allowed protocol.\n safeProtocol.test(value.slice(0, colon))\n ) {\n return value;\n }\n\n return '';\n};\n","/**\n * Builds the `rehype-sanitize` schema used by {@link MarkdownContent}.\n *\n * Extracted into its own module so the merge logic can be unit-tested in\n * isolation without pulling in React or the full markdown pipeline.\n *\n * @module components/sanitizeSchema\n */\n\nimport { defaultSchema } from 'rehype-sanitize';\n\ntype Schema = typeof defaultSchema;\ntype AttributeEntry = NonNullable<NonNullable<Schema['attributes']>[string]>[number];\n\n/**\n * Extend the allowlist for a tag's `className` attribute with extra class\n * names while preserving all other default entries.\n *\n * `findDefinition` in hast-util-sanitize returns the *first* matching entry\n * for a given property name, so appending a second `className` entry would be\n * ignored. Instead, merge the allowed values into the existing entry.\n *\n * Edge cases:\n * - `existing` is `undefined` → returns a single new `['className', ...extra]`\n * - `existing` has no `className` entry → appends one with just the extras\n * - `existing` has a bare-string `'className'` entry (hast-util-sanitize's\n * \"allow all values\" form) → would be narrowed to an allow-list. This is a\n * semantics change, but the current `defaultSchema.attributes.code` entry\n * is always tuple-form, so this branch is defensive only.\n */\nexport function mergeClassNameAllowlist(\n existing: ReadonlyArray<AttributeEntry> | undefined,\n extraClassNames: readonly string[]\n): AttributeEntry[] {\n const entries: AttributeEntry[] = existing ? [...existing] : [];\n const idx = entries.findIndex((entry) =>\n typeof entry === 'string' ? entry === 'className' : entry[0] === 'className'\n );\n if (idx === -1) {\n return [...entries, ['className', ...extraClassNames]];\n }\n const current = entries[idx];\n const merged: AttributeEntry =\n typeof current === 'string' ? ['className', ...extraClassNames] : [...current, ...extraClassNames];\n entries[idx] = merged;\n return entries;\n}\n\nconst crossChunkTags = ['cross-chunk-link', 'cross-chunk-image', 'footnote-sup'] as const;\n\n/**\n * The full sanitize schema used by the markdown renderer: extends\n * `defaultSchema` to allow `<mark>`, the KaTeX math class names, and the\n * three custom hast tags emitted by cross-chunk coordination handlers.\n */\nexport const sanitizeSchema: Schema = {\n ...defaultSchema,\n tagNames: [...(defaultSchema.tagNames || []), 'mark', ...crossChunkTags],\n attributes: {\n ...defaultSchema.attributes,\n code: mergeClassNameAllowlist(defaultSchema.attributes?.code, ['math-inline', 'math-display']),\n 'cross-chunk-link': ['label', 'referenceType', 'documentId'],\n 'cross-chunk-image': ['label', 'referenceType', 'documentId', 'alt'],\n 'footnote-sup': ['label', 'localOccurrence', 'documentId'],\n },\n};\n","/**\n * `rehypeRebaseHashLinks` — restore intra-document hash navigation after\n * `rehype-sanitize` clobbers `id` attributes.\n *\n * ### Why this exists\n *\n * `rehype-sanitize` defends against ID-clobbering attacks (e.g. a malicious\n * `<div id=\"window\">` shadowing `window.window`) by prefixing every clobberable\n * attribute (`id`, `name`, `aria-describedby`, `aria-labelledby`) with\n * `clobberPrefix` (default `'user-content-'`). It does **not** rewrite `href`\n * values, since hashes are not themselves clobbering vectors. As a result,\n * any intra-document link — `[ref](#section)`, GFM footnote anchors, or raw\n * `<a id=\"x\"><a href=\"#x\">` pairs — points at an unprefixed hash while its\n * target id has been prefixed: navigation breaks.\n *\n * Pair this plugin with `remarkRehypeOptions: { clobberPrefix: '' }` so that\n * `mdast-util-to-hast` does not also prefix (avoiding `user-content-user-content-`\n * double prefixes), and place it **after** `rehype-sanitize` in the rehype\n * pipeline. The result mirrors GitHub's rendering: a single, consistent\n * `user-content-` prefix on every id and matching hash href.\n *\n * @module components/rehypeRebaseHashLinks\n */\n\nimport type { Root } from 'hast';\nimport type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\n\nconst DEFAULT_PREFIX = 'user-content-';\n\nexport interface RehypeRebaseHashLinksOptions {\n /** Prefix to apply. Must match the `clobberPrefix` used by `rehype-sanitize`. */\n prefix?: string;\n}\n\nconst rehypeRebaseHashLinks: Plugin<[RehypeRebaseHashLinksOptions?], Root> = (options) => {\n const prefix = options?.prefix ?? DEFAULT_PREFIX;\n const hashPrefix = '#' + prefix;\n return (tree) => {\n visit(tree, 'element', (node) => {\n if (node.tagName !== 'a') return;\n const href = node.properties?.href;\n if (typeof href !== 'string' || !href.startsWith('#')) return;\n if (href.startsWith(hashPrefix)) return;\n node.properties.href = hashPrefix + href.slice(1);\n });\n };\n};\n\nexport default rehypeRebaseHashLinks;\n","/**\n * Rehype plugin that normalizes the auto-generated footnote footer so its\n * shape matches the cross-chunk aggregate footer (rendered by\n * `AggregateFootnotesIfLast`).\n *\n * mdast-util-to-hast's default `state.footer()` emits:\n *\n * <section data-footnotes class=\"footnotes\">\n * <h2 id=\"...footnote-label\" class=\"sr-only\">Footnotes</h2>\n * <ol>...</ol>\n * </section>\n *\n * The aggregate footer used in coordinated mode (and which the user prefers\n * visually) emits:\n *\n * <section data-footnotes class=\"footnotes\">\n * <hr />\n * <ol>...</ol>\n * </section>\n *\n * Running this plugin on the parsed hast lets standalone single-doc\n * rendering produce the same structure as the aggregate, so a 1-chunk doc and\n * an N-chunk coordinated doc with identical content look the same.\n *\n * Operates only on `<section data-footnotes>` and is idempotent.\n *\n * @module components/rehypeFooterAdorn\n */\nimport { visit } from 'unist-util-visit';\nimport type { Element as HastElement, Root as HastRoot, ElementContent } from 'hast';\n\nconst FOOTNOTE_LABEL_ID_RE = /(?:^|-)footnote-label$/;\n\nfunction isFootnoteLabelH2(node: ElementContent): boolean {\n if (node.type !== 'element') return false;\n const el = node as HastElement;\n if (el.tagName !== 'h2') return false;\n const id = el.properties?.id;\n return typeof id === 'string' && FOOTNOTE_LABEL_ID_RE.test(id);\n}\n\nfunction isHr(node: ElementContent): boolean {\n if (node.type !== 'element') return false;\n return (node as HastElement).tagName === 'hr';\n}\n\nexport default function rehypeFooterAdorn() {\n return (tree: HastRoot) => {\n visit(tree, 'element', (n) => {\n const el = n as HastElement;\n if (el.tagName !== 'section') return;\n if (!(el.properties && 'dataFootnotes' in el.properties)) return;\n // Strip the auto-generated <h2 id=\"...footnote-label\"> — the visible\n // \"Footnotes\" header reads awkwardly, especially in streaming AI chat\n // contexts. To keep screen-reader announcement working, set\n // `aria-label=\"Footnotes\"` on the section landmark so assistive tech\n // still names the region.\n const filtered = el.children.filter((c) => !isFootnoteLabelH2(c)) as ElementContent[];\n // Prepend <hr> as the first child, unless one is already present.\n if (!filtered.some(isHr)) {\n const hr: HastElement = {\n type: 'element',\n tagName: 'hr',\n properties: {},\n children: [],\n };\n filtered.unshift(hr);\n }\n el.children = filtered;\n if (!el.properties) el.properties = {};\n if (!('ariaLabel' in el.properties)) {\n el.properties.ariaLabel = 'Footnotes';\n }\n });\n };\n}\n","/**\n * Block-level memoization for streaming markdown.\n *\n * A single unified parse produces both an mdast (for syntax-level ctx like\n * footnote / link / image references) and a hast (the actual render input).\n * `buildBlocks` cuts the hast into per-block units 1:1 with hast top-level\n * children that have an mdast counterpart, plus an optional synthetic\n * footnote section. `renderBlocksWithCache` then memoizes each block by\n * `(raw, occurrence index, ctx, startOffset)` so cached blocks skip the\n * downstream `toJsxRuntime` + React reconcile work.\n *\n * Design contract is in `/tmp/phase5-block-memo-decisions.md`. Read it before\n * touching any of the invariants in this file.\n *\n * @module components/blockMemo\n */\n\nimport type { Element as HastElement, Root as HastRoot, RootContent as HastChild } from 'hast';\nimport type { Root as MdastRoot, RootContent as MdastContent, Nodes as MdastNodes } from 'mdast';\nimport type { ReactNode } from 'react';\nimport { visit } from 'unist-util-visit';\nimport { renderHastSubtree, type Options } from './markdown';\nimport { normalizeId } from './normalizeId';\nimport type { Registry } from './documentRegistry';\n\n/**\n * mdast types whose presence in a block makes that block dependent on\n * cross-block syntax (footnote/link/image references and definitions).\n * Tainted blocks invalidate via the document `globalCtx` digest; non-tainted\n * blocks invalidate only on raw + position change.\n */\nconst TAINT_TYPES: ReadonlySet<string> = new Set([\n 'footnoteReference',\n 'footnoteDefinition',\n 'linkReference',\n 'imageReference',\n 'definition',\n]);\n\n/**\n * mdast types that contribute to the document-wide `globalCtx` digest.\n * Currently identical to {@link TAINT_TYPES} — refs/defs are simultaneously\n * \"things that make a block tainted\" and \"things that change a tainted\n * block's render output\". Kept as a separate constant so the two roles can\n * diverge later (e.g. a future plugin that introduces a new node type which\n * is a ctx contributor but not a per-block taint source).\n */\nconst CTX_TYPES: ReadonlySet<string> = TAINT_TYPES;\n\n/**\n * Subset of {@link Options} consumed by per-block rendering — i.e. everything\n * except the pipeline plugins (those have already run by the time we reach\n * `renderHastSubtree`). Marked Readonly to discourage callers from mutating\n * the captured options reference between frames.\n */\nexport interface PostOptions extends Readonly<Options> {\n /** Required for cross-chunk coordination. Provided by AIMarkdownContent\n * when wrapped in <AIMarkdownDocuments>; undefined in standalone mode. */\n registry?: Registry;\n /** Required when registry is set. Per-chunk Symbol; used by fingerprint\n * to encode canonical-vs-this comparison. */\n thisChunkSymbol?: symbol;\n /** Required when registry is set. From useAIMarkdownRenderState; entered\n * into fingerprint so id/href prefix changes invalidate the cache. */\n clobberPrefix?: string;\n}\n\n/** Source-level identity of one renderable hast block. */\nexport interface BlockInfo {\n raw: string;\n startOffset: number;\n endOffset: number;\n /**\n * Line and column at the block's start. Tracked alongside `startOffset`\n * because two different source documents can produce the same byte offset\n * for the \"same\" content (`A\\n\\nB\\n\\nTarget` vs `ABCD\\n\\nTarget` — both\n * have `Target` starting at offset 6 but on different lines). Custom\n * components that read `node.position.start.line` would otherwise see\n * stale data from a false-positive cache hit.\n */\n startLine: number;\n startColumn: number;\n /** True if the block contains any TAINT_TYPES node — invalidate on globalCtx change. */\n hasReference: boolean;\n /** TAINT-block 专属:按节点类型分桶的 label set。Normalized 形态(uppercase)。\n * Undefined when hasReference === false. */\n taintLabels?: {\n footnoteRefLabels: string[];\n linkRefLabels: string[];\n imageRefLabels: string[];\n footnoteDefLabels: string[];\n };\n}\n\n/** Cache entry for one rendered block. */\nexport interface BlockCacheEntry {\n node: ReactNode;\n /** `globalCtx` digest if the block is tainted, '' otherwise. Sentinel collapses both code paths. */\n ctx: string;\n /** Position triple — must all match for the cached node to be valid. */\n startOffset: number;\n startLine: number;\n startColumn: number;\n}\n\n/** Cache entry for the synthesized footnote section (single slot, keyed by globalCtx). */\nexport interface FootnoteSectionEntry {\n ctx: string;\n node: ReactNode;\n}\n\n/**\n * Per-instance memo state.\n *\n * ## Memory characteristics\n *\n * The cache holds one `ReactNode` reference per live block in the current\n * document plus an optional single slot for the synthesized footnote\n * section. Memory therefore scales linearly with document size, NOT with\n * session duration: every frame's render produces a fresh `next` Cache, and\n * the previous frame's Cache is atomically replaced (orphaned for GC).\n * Blocks that disappear between frames are dropped from the cache the same\n * frame they vanish from the document.\n *\n * For typical AI chat (≤ 1000 blocks per response, individual ReactNode\n * trees in the low-KB range), per-instance memory stays comfortably below\n * ~10 MB. If you build a UI that keeps very long single-document instances\n * alive indefinitely (≥ 10k live blocks), consider mounting on a virtual\n * scroll boundary so blocks above the fold can unmount and release their\n * cached subtrees.\n */\nexport interface Cache {\n /** raw → bucket of entries indexed by occurrence within the document. */\n blocks: Map<string, BlockCacheEntry[]>;\n /** Synthesized footnote section, if the previous frame produced one. */\n footnoteSection?: FootnoteSectionEntry;\n}\n\n/** Build a fresh, empty Cache. */\nexport function createCache(): Cache {\n return { blocks: new Map() };\n}\n\n/**\n * Slice the source string for the given mdast node's position. mdast nodes\n * produced by remark-parse always carry `position`; the empty-string fallback\n * is purely defensive.\n */\nfunction extractRaw(node: MdastNodes, source: string): string {\n if (!node.position) return '';\n return source.slice(node.position.start.offset, node.position.end.offset);\n}\n\n/**\n * Detect mdast-util-to-hast's synthesized footnote `<section data-footnotes>`.\n * Position-based detection alone would be too broad — any future rehype plugin\n * that appends a position-less node would be misclassified. We assert by\n * `tagName === 'section'` AND presence of the `dataFootnotes` property.\n */\nexport function isFootnoteSection(node: HastElement): boolean {\n if (node.tagName !== 'section') return false;\n const props = node.properties as Record<string, unknown> | undefined;\n return props?.dataFootnotes !== undefined;\n}\n\n/** Dev invariant: every block hast child must retain its mdast `position`. */\nexport function hasMdastSource(node: HastElement): boolean {\n return node.position !== undefined;\n}\n\n/**\n * One step of the document render plan, in source order.\n *\n * The plan covers EVERY top-level hast child so that {@link renderBlocksWithCache}\n * can preserve react-markdown's byte-equivalent output — including the whitespace\n * `text` nodes that `mdast-util-to-hast` inserts between block elements.\n *\n * - `block`: a hast element with an mdast counterpart, eligible for caching by\n * `(raw, occurrence index, ctx, startOffset)`.\n * - `inline`: a non-element top-level child (whitespace text, comment, …) or\n * an element that has no mdast counterpart but is still safe to render.\n * These are rendered every frame without caching — they are typically\n * single whitespace characters.\n * - `synthetic`: the synthesized footnote `<section data-footnotes>`, cached\n * in a single slot keyed by `globalCtx`.\n */\nexport type RenderItem =\n | { kind: 'block'; el: HastElement; reactKey: string; info: BlockInfo }\n | { kind: 'inline'; el: HastChild; reactKey: string }\n | { kind: 'synthetic'; el: HastElement; reactKey: string };\n\n/** Result of {@link buildBlocks}. */\nexport interface BuildBlocksResult {\n /** Render plan in document order — drives {@link renderBlocksWithCache}. */\n plan: RenderItem[];\n /** JSON-stringified ordered list of TAINT-typed nodes in document order. */\n globalCtx: string;\n // ── Derived views (kept for tests and convenience) ─────────────────────\n /** Flat list of `BlockInfo` for cacheable blocks, in document order. */\n blocks: BlockInfo[];\n /** 1:1 with `blocks` — the hast Element each BlockInfo refers to. */\n blockHasts: HastElement[];\n /** Synthesized footnote section, if present. */\n synthetic?: HastElement;\n}\n\n/** A single rendered output item with its stable React key. */\nexport interface RenderedItem {\n node: ReactNode;\n reactKey: string;\n}\n\nconst FOOTNOTE_SECTION_KEY = '__footnote_section__';\n\n/**\n * Build the document render plan + ctx digest from a parsed mdast and its\n * rendered hast.\n *\n * Plan construction is driven by `hast.children` (NOT `mdast.children`):\n * pipeline transformers like `remarkSqueezeParagraphs` and\n * `remarkRemoveComments` drop blocks, so the rendered hast may have fewer\n * top-level children than the parsed mdast. Driving by hast guarantees the\n * plan covers exactly what will be rendered.\n *\n * Each hast top-level child becomes one plan item:\n * - `<section data-footnotes>` → `synthetic` (cached in a single slot)\n * - element with mdast counterpart → `block` (cacheable by raw + occurrence + ctx + offset)\n * - text / comment / element-without-counterpart → `inline` (rendered fresh every frame)\n *\n * The mdast counterpart of a block element is found by source offset using\n * a two-tier lookup: an exact-offset Map (mdast-util-to-hast's default 1:1\n * propagation), then range-containment `findLast` fallback for cases like\n * `rehype-raw` splitting one mdast `html` node into multiple hast siblings\n * (e.g. ` <div>Hi</div>` — leading spaces shift the `<div>` offset\n * inside the parent html node's source range).\n *\n * In dev, a hast block whose offset matches no mdast counterpart at all\n * throws — that means a rehype plugin synthesized positions outside the\n * source range, which is a bug worth surfacing. In production it falls\n * through to an `inline` plan item so user content is never silently lost.\n *\n * `globalCtx` walks the full mdast for footnote/link/image refs and\n * definitions in document order (no dedupe — order matters for footnote\n * numbering), then JSON-stringifies the collected tuples. That string is the\n * invalidation key for tainted blocks and the synthetic footnote section.\n */\nexport function buildBlocks(mdast: MdastRoot, hast: HastRoot, source: string): BuildBlocksResult {\n const mdastByOffset = new Map<number, MdastContent>();\n // Sorted [start, end, node] table for the range-containment fallback used\n // when a hast block's offset is INSIDE an mdast node's source range\n // (`rehype-raw` splitting one mdast `html` node into multiple hast\n // siblings is the canonical case). Pre-sorted because mdast children come\n // out of remark-parse in source order; we collect positioned ones in\n // place, preserving order. Binary search at lookup time replaces the\n // previous O(N) `findLast` — without it, M hast blocks × N mdast children\n // degrades to O(N×M) on pathological streams with many splits.\n type Range = { start: number; end: number; node: MdastContent };\n const mdastRanges: Range[] = [];\n for (const child of mdast.children) {\n const off = child.position?.start.offset;\n const endOff = child.position?.end.offset;\n if (off !== undefined) {\n mdastByOffset.set(off, child);\n }\n if (off !== undefined && endOff !== undefined) {\n mdastRanges.push({ start: off, end: endOff, node: child });\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n for (let i = 1; i < mdastRanges.length; i++) {\n if (mdastRanges[i].start < mdastRanges[i - 1].start) {\n // Should never trip: mdast.children is source-order. If it does\n // trip, the binary search below is wrong — surface it loudly so\n // we sort defensively rather than silently misroute hast blocks.\n throw new Error(\n 'block-memo: mdast.children not sorted by source offset — ' +\n 'a remark plugin is reordering top-level children.'\n );\n }\n }\n }\n function findContainingMdast(offset: number): MdastContent | undefined {\n // Upper-bound binary search: find first index where range.start > offset.\n // The candidate is the immediate predecessor (largest start <= offset).\n let lo = 0;\n let hi = mdastRanges.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (mdastRanges[mid].start <= offset) lo = mid + 1;\n else hi = mid;\n }\n const idx = lo - 1;\n if (idx < 0) return undefined;\n const r = mdastRanges[idx];\n // Top-level mdast children have non-overlapping source ranges, so the\n // single largest-start candidate is the unique container (if any).\n return offset < r.end ? r.node : undefined;\n }\n\n const ctxParts: unknown[] = [];\n visit(mdast, (n) => {\n if (!CTX_TYPES.has(n.type)) return;\n if (n.type === 'footnoteReference') ctxParts.push(['fr', n.identifier]);\n else if (n.type === 'footnoteDefinition') ctxParts.push(['fd', n.identifier, extractRaw(n, source)]);\n else if (n.type === 'linkReference') ctxParts.push(['lr', n.identifier]);\n else if (n.type === 'imageReference') ctxParts.push(['ir', n.identifier]);\n else if (n.type === 'definition') ctxParts.push(['d', n.identifier, n.url, n.title ?? null]);\n });\n const globalCtx = JSON.stringify(ctxParts);\n\n const plan: RenderItem[] = [];\n const blocks: BlockInfo[] = [];\n const blockHasts: HastElement[] = [];\n let synthetic: HastElement | undefined;\n\n for (let i = 0; i < hast.children.length; i++) {\n const hastChild = hast.children[i];\n\n if (hastChild.type !== 'element') {\n // Top-level non-element child (whitespace text inserted by\n // mdast-util-to-hast between block elements, sanitized comment, …).\n // Render inline without caching to preserve byte-equivalent output.\n const off = hastChild.position?.start.offset;\n const reactKey = off !== undefined ? `inline-${off}` : `inline-i${i}`;\n plan.push({ kind: 'inline', el: hastChild, reactKey });\n continue;\n }\n\n const el = hastChild;\n\n if (isFootnoteSection(el)) {\n synthetic = el;\n plan.push({ kind: 'synthetic', el, reactKey: FOOTNOTE_SECTION_KEY });\n continue;\n }\n const hastOffset = el.position?.start.offset;\n if (hastOffset === undefined) {\n // Element without position (synthesized by some plugin) — preserve in\n // document order, rendered as inline (no cache key available).\n plan.push({ kind: 'inline', el, reactKey: `inline-i${i}` });\n continue;\n }\n\n let mdastNode = mdastByOffset.get(hastOffset);\n\n if (!mdastNode) {\n mdastNode = findContainingMdast(hastOffset);\n }\n\n if (!mdastNode) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `block-memo: hast block at offset ${hastOffset} has no mdast counterpart. ` +\n `A rehype plugin may have synthesized positions outside source. tagName=${el.tagName}`\n );\n }\n // Production fallback: render inline, no cache.\n plan.push({ kind: 'inline', el, reactKey: `inline-${hastOffset}` });\n continue;\n }\n\n if (mdastNode.type === 'footnoteDefinition') {\n // Footnote definitions are hoisted into the synthetic section by\n // mdast-util-to-hast — they should not appear as top-level hast blocks\n // in any current plugin chain. If the range fallback ever resolves an\n // unrelated hast block to a footnoteDefinition's mdast source range,\n // preserve it as `inline` rather than silently dropping it (defensive\n // parity with the other no-counterpart fallbacks above).\n plan.push({ kind: 'inline', el, reactKey: `inline-${hastOffset}` });\n continue;\n }\n\n let hasReference = false;\n const footnoteRefLabels: string[] = [];\n const linkRefLabels: string[] = [];\n const imageRefLabels: string[] = [];\n const footnoteDefLabels: string[] = [];\n visit(mdastNode, (n) => {\n if (!TAINT_TYPES.has(n.type)) return;\n hasReference = true;\n const id = 'identifier' in n ? normalizeId(String(n.identifier)) : null;\n if (id === null) return;\n if (n.type === 'footnoteReference') footnoteRefLabels.push(id);\n else if (n.type === 'linkReference') linkRefLabels.push(id);\n else if (n.type === 'imageReference') imageRefLabels.push(id);\n else if (n.type === 'footnoteDefinition') footnoteDefLabels.push(id);\n // 'definition' nodes don't carry per-block fingerprint significance\n // (they're metadata, not visible); intentionally not bucketed.\n });\n\n const mdastPos = mdastNode.position;\n if (!mdastPos || mdastPos.start.offset === undefined || mdastPos.end.offset === undefined) {\n continue;\n }\n\n const info: BlockInfo = {\n raw: extractRaw(mdastNode, source),\n startOffset: mdastPos.start.offset,\n endOffset: mdastPos.end.offset,\n startLine: mdastPos.start.line,\n startColumn: mdastPos.start.column,\n hasReference,\n ...(hasReference\n ? {\n taintLabels: { footnoteRefLabels, linkRefLabels, imageRefLabels, footnoteDefLabels },\n }\n : {}),\n };\n blocks.push(info);\n blockHasts.push(el);\n // React key is keyed off the HAST element's source offset (not the mdast\n // node's), because multi-root raw HTML produces multiple hast siblings\n // that share one mdast `html` node — same `mdastPos.start.offset` for\n // both, which would collide as a React key. Hast positions are unique\n // per element in the rendered tree.\n plan.push({ kind: 'block', el, info, reactKey: `block-${hastOffset}` });\n }\n\n return { plan, globalCtx, blocks, blockHasts, synthetic };\n}\n\n/**\n * Compute a per-block cache fingerprint from the registry slice this block\n * actually depends on (footnote/link/image refs and footnote defs). Two blocks\n * with the same fingerprint render byte-equal output; if any encoded value\n * differs, the block must re-render.\n *\n * Encoding format (deterministic, stable across versions):\n * `<clobberPrefix>|fn:<L>=<globalNumber>|lr:<L>=<url>|<title>|ir:<L>=<url>|fd:<L>=<canonical>/<refCount>`\n *\n * @param taintLabels - Per-block label dependency footprint (from BlockInfo.taintLabels).\n * @param registry - Shared cross-chunk registry.\n * @param thisChunkSym- The Symbol of the chunk this rendering belongs to (for canonical-vs-this comparison).\n * @param clobberPrefix - The documentId-derived id prefix; included so href/id changes invalidate.\n */\nexport function computeBlockFingerprint(\n taintLabels: NonNullable<BlockInfo['taintLabels']>,\n registry: Registry,\n thisChunkSym: symbol,\n clobberPrefix: string\n): string {\n const parts: string[] = [clobberPrefix];\n for (const label of taintLabels.footnoteRefLabels) {\n parts.push(`fn:${label}=${registry.globalNumber(label) ?? 'null'}`);\n }\n for (const label of taintLabels.linkRefLabels) {\n const def = registry.resolveLinkDef(label);\n parts.push(`lr:${label}=${def?.url ?? 'null'}|${def?.title ?? ''}`);\n }\n for (const label of taintLabels.imageRefLabels) {\n const def = registry.resolveLinkDef(label);\n parts.push(`ir:${label}=${def?.url ?? 'null'}|${def?.title ?? ''}`);\n }\n for (const label of taintLabels.footnoteDefLabels) {\n const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;\n parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);\n }\n return parts.join('|');\n}\n\n/**\n * Render the document plan with cache lookup + atomic Cache replacement.\n *\n * Cache identity for a `block` item is `(raw, occurrence index within bucket,\n * ctx, startOffset)`. ctx == globalCtx for tainted blocks, '' otherwise\n * (sentinel collapses both paths into one validation).\n *\n * The synthesized footnote section is a single-slot cache keyed by globalCtx.\n * Atomic Cache replacement (`cacheRef.current = next`) ensures stale slots\n * cannot leak across frames: when synthetic disappears in frame T2,\n * `next.footnoteSection` is left undefined and the old node is orphaned with\n * the rest of the previous Cache for GC.\n *\n * `inline` items (top-level whitespace text, sanitized comments, etc.) are\n * rendered every frame without caching — they are typically a single\n * character and would not benefit from memoization.\n */\nexport function renderBlocksWithCache(\n cacheRef: { current: Cache },\n plan: RenderItem[],\n globalCtx: string,\n postOptions: PostOptions\n): RenderedItem[] {\n const prev = cacheRef.current;\n const next: Cache = { blocks: new Map() };\n const rendered: RenderedItem[] = [];\n\n if (process.env.NODE_ENV !== 'production') {\n for (const item of plan) {\n if (item.kind === 'block' && !hasMdastSource(item.el)) {\n throw new Error(\n 'block-memo: block hast child has no position. Did a rehype plugin strip it? ' +\n '(Run positionPropagation.test.ts to verify.)'\n );\n }\n }\n }\n\n for (const item of plan) {\n if (item.kind === 'inline') {\n rendered.push({\n node: renderHastSubtree(item.el, postOptions),\n reactKey: item.reactKey,\n });\n continue;\n }\n\n if (item.kind === 'synthetic') {\n // Cross-chunk coordination: in coordinated mode (registry AND this chunk's\n // Symbol registered) the per-chunk local `<section data-footnotes>` is\n // replaced by `<AggregateFootnotesIfLast>` mounted at the end of each\n // document's last chunk. Skip the local synthetic to avoid duplicate\n // footers across chunks.\n //\n // The thisChunkSymbol guard preserves SSR semantics: during\n // `renderToStaticMarkup` useEffect doesn't fire, so the chunk hasn't\n // registered with the registry yet (`thisChunkSymbol` undefined). Falling\n // back to the local footer keeps each chunk's defs visible in the static\n // output — which is what `byteEquivalence.test.tsx` exercises and what\n // users doing SSR-without-hydration expect.\n if (postOptions.registry && postOptions.thisChunkSymbol) {\n continue;\n }\n // Standalone mode (or SSR pre-registration): cache the local section by\n // globalCtx and render it.\n const cached = prev.footnoteSection;\n let node: ReactNode;\n if (cached && cached.ctx === globalCtx) {\n node = cached.node;\n } else {\n node = renderHastSubtree(item.el, postOptions);\n }\n next.footnoteSection = { ctx: globalCtx, node };\n rendered.push({ node, reactKey: item.reactKey });\n continue;\n }\n\n // kind === 'block'\n const block = item.info;\n let bucket = next.blocks.get(block.raw);\n if (!bucket) {\n bucket = [];\n next.blocks.set(block.raw, bucket);\n }\n const occ = bucket.length;\n\n if (block.hasReference) {\n const useFingerprint =\n postOptions.registry &&\n block.taintLabels &&\n postOptions.thisChunkSymbol &&\n postOptions.clobberPrefix !== undefined;\n const blockCtx = useFingerprint\n ? computeBlockFingerprint(\n block.taintLabels!,\n postOptions.registry!,\n postOptions.thisChunkSymbol!,\n postOptions.clobberPrefix!\n )\n : globalCtx; // fallback: standalone mode pre-v6 behavior\n\n const entry = prev.blocks.get(block.raw)?.[occ];\n const valid =\n entry !== undefined &&\n entry.ctx === blockCtx &&\n entry.startOffset === block.startOffset &&\n entry.startLine === block.startLine &&\n entry.startColumn === block.startColumn;\n\n let node: ReactNode;\n if (valid) {\n node = entry.node; // cache hit: skip everything\n } else {\n // Coordinated-mode hast post-transforms used to run here, but the\n // aggregate footer (AggregateFootnotesIfLast) now reconstructs the\n // footnote section from registry state, and the synthetic plan item\n // for `<section data-footnotes>` is skipped earlier in this loop.\n // Regular blocks never contain a top-level footnote section, so a\n // post-transform pass would be a no-op anyway.\n node = renderHastSubtree(item.el, postOptions);\n }\n\n bucket.push({\n node,\n ctx: blockCtx,\n startOffset: block.startOffset,\n startLine: block.startLine,\n startColumn: block.startColumn,\n });\n rendered.push({ node, reactKey: item.reactKey });\n continue;\n }\n\n // Non-TAINT block: existing cache-by-(raw, occurrence, '', position) path\n {\n const entry = prev.blocks.get(block.raw)?.[occ];\n const valid =\n entry !== undefined &&\n entry.ctx === '' &&\n entry.startOffset === block.startOffset &&\n entry.startLine === block.startLine &&\n entry.startColumn === block.startColumn;\n const node = valid ? entry.node : renderHastSubtree(item.el, postOptions);\n bucket.push({\n node,\n ctx: '',\n startOffset: block.startOffset,\n startLine: block.startLine,\n startColumn: block.startColumn,\n });\n rendered.push({ node, reactKey: item.reactKey });\n }\n }\n\n cacheRef.current = next;\n return rendered;\n}\n","/**\n * CommonMark §4.7 label normalization. Used as the single canonical form\n * for all label-keyed structures (registry maps, phantomFootnoteLabels Set,\n * labelSet, etc.) and for handler comparisons against mdast-util-to-hast's\n * internal `state.definitionById` / `state.footnoteById` keys.\n *\n * Direction is uppercase to align with mdast-util-to-hast internals\n * (`String(identifier).toUpperCase()`). Direction is irrelevant once both\n * sides agree; uppercase chosen to match the upstream library to minimize\n * adapter calls.\n *\n * @module components/normalizeId\n */\nexport function normalizeId(s: string): string {\n return s.replace(/\\s+/g, ' ').toUpperCase();\n}\n\n/**\n * Same as {@link normalizeId} plus resolution of backslash escapes.\n * Used by PASS 0.5 substring pre-check against raw chunk source text:\n * sources may write `[foo\\]bar]` but the resulting label identifier is\n * `foo]bar`, so we must unescape source before substring matching.\n */\nexport function normalizeForMatch(s: string): string {\n return s.replace(/\\\\(.)/g, '$1').replace(/\\s+/g, ' ').toUpperCase();\n}\n","/**\n * Lightweight def-only parse: runs a minimal unified pipeline\n * (remark-parse + remark-gfm) to extract identifiers of all\n * `footnoteDefinition` and `definition` nodes from a markdown source string.\n *\n * Used by PASS 0 of cross-chunk coordination to discover label sets without\n * triggering the full to-hast pipeline. Output is normalized via normalizeId\n * (uppercase, whitespace-collapsed) — same canonical form used everywhere in\n * the registry, phantomFootnoteLabels Set, and handler comparisons.\n *\n * @module components/collectDefLabels\n */\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkGfm from 'remark-gfm';\nimport { visit } from 'unist-util-visit';\nimport type { Root as MdastRoot } from 'mdast';\nimport { normalizeId } from './normalizeId';\n\nexport interface DefLabels {\n footnoteLabels: Set<string>;\n linkLabels: Set<string>;\n}\n\n// Build helper kept as its own function so the cached processor's type is\n// inferred as the FULL chained Processor (remark-parse + remark-gfm), not\n// the bare `unified()` Processor with `undefined` extension types.\nfunction buildProcessor() {\n return unified().use(remarkParse).use(remarkGfm);\n}\nlet _processor: ReturnType<typeof buildProcessor> | null = null;\nfunction processor(): ReturnType<typeof buildProcessor> {\n if (!_processor) _processor = buildProcessor();\n return _processor;\n}\n\nexport function collectDefLabels(source: string): DefLabels {\n if (!source) {\n return { footnoteLabels: new Set(), linkLabels: new Set() };\n }\n const mdast = processor().parse(source) as MdastRoot;\n const footnoteLabels = new Set<string>();\n const linkLabels = new Set<string>();\n visit(mdast, (node) => {\n if (node.type === 'footnoteDefinition' && 'identifier' in node) {\n footnoteLabels.add(normalizeId(node.identifier as string));\n } else if (node.type === 'definition' && 'identifier' in node) {\n linkLabels.add(normalizeId(node.identifier as string));\n }\n });\n return { footnoteLabels, linkLabels };\n}\n","/**\n * Optional outer wrapper enabling cross-chunk coordination for any\n * `<AIMarkdown>` instances rendered as descendants. Each unique\n * `documentId` partitions its own Registry.\n *\n * Without this wrapper, `<AIMarkdown>` instances render independently\n * (current behavior). With it, multiple chunks sharing a `documentId`\n * coordinate footnote numbering, linkReference/imageReference resolution,\n * and anchor jumps across chunks.\n *\n * @module components/AIMarkdownDocuments\n */\nimport { createContext, useContext, useMemo, useRef, type PropsWithChildren, type FC } from 'react';\nimport { createRegistry, type Registry } from './documentRegistry';\n\ninterface AIMarkdownDocumentsContextValue {\n getRegistry: (documentId: string) => Registry;\n preserveOrphanReferences: boolean;\n}\n\nconst AIMarkdownDocumentsContext = createContext<AIMarkdownDocumentsContextValue | null>(null);\n\nexport interface AIMarkdownDocumentsProps extends PropsWithChildren {\n /**\n * Default `true`. Unconditionally controls orphan-reference protection\n * for all chunks under this wrapper, overriding their individual\n * `config.preserveOrphanReferences`. Does not control cross-chunk\n * coordination itself (that's gated by wrapper presence + `documentId`).\n */\n preserveOrphanReferences?: boolean;\n}\n\nexport const AIMarkdownDocuments: FC<AIMarkdownDocumentsProps> = ({ preserveOrphanReferences = true, children }) => {\n const parent = useContext(AIMarkdownDocumentsContext);\n if (parent !== null) {\n throw new Error(\n '<AIMarkdownDocuments> must not be nested inside another <AIMarkdownDocuments>. Use a single top-level wrapper per coordinated scope.'\n );\n }\n\n // Registries are persistent across renders. Map<documentId, Registry>.\n //\n // Eviction: each registry receives an `onEmpty` callback that the\n // wrapper invokes when the registry's last chunk just released its\n // Symbol. The callback removes the registry from this Map iff the\n // entry is STILL the one we created — a fresh `getRegistry(documentId)`\n // racing the cleanup microtask would have already replaced it, in\n // which case eviction is a no-op. This keeps the Map bounded by the\n // number of `documentId` values with at least one chunk alive at any\n // given moment.\n //\n // Known edge case (acceptable v1 limitation): `getRegistry` is called\n // synchronously from `useDocumentRegistry` during render, and creates\n // the registry + writes the Map entry as a render-time side effect.\n // React 19's concurrent rendering allows aborting a render before\n // commit; if a render is aborted AFTER `getRegistry(X)` has created a\n // new registry but BEFORE any chunk's allocate effect commits, AND the\n // next render uses a different `documentId`, the aborted render's\n // registry leaks (no chunk ever attaches, so `onEmpty` never fires).\n // The leak is bounded (one empty Registry shell per aborted-render-\n // with-unique-documentId), the shell is small (a few empty Sets and a\n // version counter), and concurrent aborts on documentId-bearing\n // components are rare in practice. A proper fix would defer the Map\n // insert to chunk-subscription time, but that breaks the synchronous-\n // getter contract `useDocumentRegistry` relies on. Deferred.\n const registriesRef = useRef<Map<string, Registry>>(new Map());\n\n const value = useMemo<AIMarkdownDocumentsContextValue>(\n () => ({\n preserveOrphanReferences,\n getRegistry(documentId: string) {\n let r = registriesRef.current.get(documentId);\n if (!r) {\n // Capture `r` in the closure so the identity check below\n // compares against the exact registry instance we created.\n // A microtask-delayed onEmpty firing AFTER a subsequent\n // getRegistry replaced the entry must NOT evict the new one.\n const created = createRegistry(() => {\n if (registriesRef.current.get(documentId) === created) {\n registriesRef.current.delete(documentId);\n }\n });\n r = created;\n registriesRef.current.set(documentId, r);\n }\n return r;\n },\n }),\n [preserveOrphanReferences]\n );\n\n return <AIMarkdownDocumentsContext.Provider value={value}>{children}</AIMarkdownDocumentsContext.Provider>;\n};\n\n/**\n * Returns the registry for the given `documentId`, or `null` if:\n * - `<AIMarkdown>` is not inside an `<AIMarkdownDocuments>` wrapper, OR\n * - `documentId` is undefined / empty string.\n *\n * Callers should treat `null` as \"no coordination; run standalone path.\"\n */\nexport function useDocumentRegistry(documentId: string | undefined): Registry | null {\n const ctx = useContext(AIMarkdownDocumentsContext);\n if (!ctx || !documentId) return null;\n return ctx.getRegistry(documentId);\n}\n\n/** Returns the effective preserveOrphanReferences for this position in the tree:\n * the wrapper's prop value if inside one, otherwise the supplied fallback\n * (typically `config.preserveOrphanReferences`). */\nexport function usePreserveOrphanReferences(fallback: boolean): boolean {\n const ctx = useContext(AIMarkdownDocumentsContext);\n return ctx?.preserveOrphanReferences ?? fallback;\n}\n\n/** @internal — for tests only. */\nexport function __internalGetContext(): AIMarkdownDocumentsContextValue | null {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(AIMarkdownDocumentsContext);\n}\n","/**\n * Cross-chunk shared state. Holds per-chunk contributions (refs, defs,\n * linkDefs) keyed by Symbol identity allocated via useId reactId, with\n * refcount + microtask-deferred reclamation for React Strict Mode safety.\n *\n * @module components/documentRegistry\n */\n\nimport type { ElementContent as HastElementContent } from 'hast';\nimport { normalizeId } from './normalizeId';\n\nexport interface FootnoteDef {\n /** Already-normalized identifier (uppercase). Used as dictionary key for\n * case-insensitive cross-chunk lookups. */\n identifier: string;\n /** mdast's case-folded identifier — the exact string mdast-util-to-hast\n * emits in `<li id=\"${clobberPrefix}fn-${sourceIdentifier}\">` and that\n * `FootnoteSupNumber` mirrors in its anchor href. Needed so the aggregate\n * footer's `<li id>` and backref href match the inline `<sup>`'s href\n * exactly (otherwise hash navigation breaks). Optional so unit-test\n * fixtures don't need to fabricate it; production data always supplies it. */\n sourceIdentifier?: string;\n /** Content extracted from the source markdown footnote definition. */\n contentSource: string;\n /** Per-def hast body (the def's mdast children after mdast-util-to-hast\n * conversion). Drives AggregateFootnotesIfLast to render the consolidated\n * footer at the end of each document's last chunk. Optional so unit-test\n * fixtures can build minimal FootnoteDef objects without producing hast. */\n bodyHast?: HastElementContent[];\n}\n\nexport interface LinkDef {\n /** Already-normalized identifier (uppercase). */\n identifier: string;\n url: string;\n title?: string;\n}\n\nexport type RefKind = 'footnote' | 'link' | 'image';\n\nexport interface RefRecord {\n /** Already-normalized identifier (uppercase). */\n label: string;\n /** Which markdown reference space this entry belongs to. Footnote refs,\n * link refs, and image refs occupy disjoint namespaces in GFM, so they\n * must be filtered separately when computing footnote numbers / refcounts. */\n kind: RefKind;\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n}\n\nexport interface ChunkData {\n refs: RefRecord[];\n defs: Map<string, FootnoteDef>;\n linkDefs: Map<string, LinkDef>;\n ownFootnoteLabels: Set<string>;\n ownLinkLabels: Set<string>;\n}\n\nexport interface Registry {\n /** Chunk mount-order Symbol list. **Read-only from outside the registry.**\n * Direct mutation (`.push`, `.splice`, index assignment) corrupts\n * footnote numbering, \"last chunk\" detection, and eviction. Use the\n * `allocateSymbol` / `releaseSymbol` / `registerChunk` API instead. */\n readonly chunkOrder: readonly symbol[];\n /** Chunk Symbol → contribution payload. **Read-only from outside.**\n * Use `contributeChunkData` / `contributeLabels` / `registerChunk` to\n * publish; direct `.set` / `.delete` bypasses version bumps and\n * subscriber wake-ups. */\n readonly chunkData: ReadonlyMap<symbol, ChunkData>;\n /** Union of own-def labels across all chunks. PASS 0.5 phantom-injection\n * driver. **Read-only from outside.** The registry derives this from\n * per-chunk contributions; direct mutation breaks the derivation. */\n readonly labelSet: {\n readonly footnoteLabels: ReadonlySet<string>;\n readonly linkLabels: ReadonlySet<string>;\n };\n /** Monotonic version counter bumped by every mutation. **Read-only from\n * outside** — consumers should observe via `subscribe`, not by writing. */\n readonly version: number;\n\n // === API ===\n /** Allocate (or reuse, for Strict Mode remount) the chunk Symbol for\n * `reactId` AND publish this chunk's own def labels (footnotes + links)\n * in one call. Canonical pair API used by `MarkdownContent`'s allocate\n * effect — combining the two reduces the pair to a single registry\n * version step, which downstream consumers see as one wake-up rather\n * than two (the second was already coalesced by microtask, but this\n * keeps the version monotonic-by-1-per-mount which makes debugging\n * easier). The granular `allocateSymbol` / `contributeLabels` methods\n * remain available for tests that need to exercise each step. */\n registerChunk(reactId: string, footnotes: Set<string>, links: Set<string>): symbol;\n allocateSymbol(reactId: string): symbol;\n releaseSymbol(reactId: string): void;\n contributeLabels(symbol: symbol, footnotes: Set<string>, links: Set<string>): void;\n contributeChunkData(symbol: symbol, data: ChunkData): void;\n subscribe(cb: () => void): () => void;\n\n // Selectors (memoized internally by version).\n canonicalFootnoteFor(label: string): symbol | null;\n canonicalLinkFor(label: string): symbol | null;\n globalNumber(label: string): number | null;\n resolveLinkDef(label: string): LinkDef | null;\n getRefsForLabel(label: string): number;\n /** Map a chunk-local footnote-ref occurrence index (1-based, as emitted by\n * `customMdastHandlers`) to the corresponding document-wide occurrence\n * index across all chunks. Used by `FootnoteSupNumber` to build a unique\n * `id=\"fnref-X-N\"` for each ref instance and by `AggregateFootnotesIfLast`\n * to enumerate per-occurrence backrefs. Returns `null` if the ref isn't\n * registered yet (registry mid-flight). */\n globalOccurrenceForRef(chunkSym: symbol, label: string, localOccurrence: number): number | null;\n}\n\n/**\n * The shape actually realised inside `createRegistry`. Includes\n * implementation-private fields (reactId-keyed refcount table, subscriber\n * set, microtask-coalesce flag, `_notify` itself). Kept off the public\n * {@link Registry} interface so the dts emit doesn't leak mutable internals\n * — a consumer flipping `_notifyScheduled = true` would otherwise be able\n * to silently break the coalesce invariant.\n */\ninterface RegistryInternal extends Registry {\n _reactIdMap: Map<string, { symbol: symbol; refcount: number }>;\n _subscribers: Set<() => void>;\n _notifyScheduled: boolean;\n _notify(): void;\n}\n\n/**\n * Construct a new Registry. `onEmpty`, if supplied, is invoked once each\n * time the registry transitions to \"no chunks alive\" — i.e. the last\n * tracked chunk's deferred `releaseSymbol` cleanup just removed its\n * entry, leaving `chunkOrder` and `chunkData` both empty. The container\n * uses this to evict the registry from its `documentId → Registry` map\n * so long-lived SPAs that cycle through many `documentId` values don't\n * accumulate empty shells.\n *\n * `onEmpty` fires synchronously from inside the releaseSymbol microtask,\n * so the registry's state is guaranteed quiescent during the callback —\n * no other code can interleave between the empty-state check and the\n * caller's eviction logic.\n */\nexport function createRegistry(onEmpty?: () => void): Registry {\n const reg = {\n chunkOrder: [] as symbol[],\n chunkData: new Map<symbol, ChunkData>(),\n labelSet: { footnoteLabels: new Set<string>(), linkLabels: new Set<string>() },\n version: 0,\n _reactIdMap: new Map<string, { symbol: symbol; refcount: number }>(),\n _subscribers: new Set<() => void>(),\n _notifyScheduled: false,\n\n allocateSymbol(reactId: string): symbol {\n const existing = this._reactIdMap.get(reactId);\n if (existing) {\n existing.refcount++;\n return existing.symbol;\n }\n const sym = Symbol(reactId);\n this._reactIdMap.set(reactId, { symbol: sym, refcount: 1 });\n this.chunkOrder.push(sym);\n this._notify();\n return sym;\n },\n\n registerChunk(reactId: string, footnotes: Set<string>, links: Set<string>): symbol {\n // Composition of allocateSymbol + contributeLabels. Both `_notify`\n // calls coalesce into a single microtask wake-up, so the perf\n // shape is the same as the granular pair — the API just expresses\n // the canonical \"register one chunk\" intent.\n const sym = this.allocateSymbol(reactId);\n this.contributeLabels(sym, footnotes, links);\n return sym;\n },\n\n releaseSymbol(reactId: string): void {\n const entry = this._reactIdMap.get(reactId);\n if (!entry) return;\n entry.refcount--;\n if (entry.refcount === 0) {\n queueMicrotask(() => {\n const latest = this._reactIdMap.get(reactId);\n if (latest && latest.refcount === 0) {\n this._reactIdMap.delete(reactId);\n const idx = this.chunkOrder.indexOf(entry.symbol);\n if (idx !== -1) this.chunkOrder.splice(idx, 1);\n this.chunkData.delete(entry.symbol);\n // Rebuild labelSet from the surviving chunks. The contribute paths\n // (`contributeLabels`, `contributeChunkData`) already rebuild this\n // union on every write, but a chunk that simply UNMOUNTS would\n // otherwise leave `labelSet` referencing labels that no live chunk\n // owns. Downstream consumers (`targetPhantoms` in\n // `MarkdownContent`) read `registry.labelSet` to gate phantom\n // injection — without this rebuild, surviving chunks would keep\n // treating refs to the released chunk's labels as phantom, while\n // `canonicalFootnoteFor` (which walks live chunkData) returns\n // null, leaving inline `<sup>` anchors pointing at `<li>` ids\n // that the aggregate footer never renders.\n const nextFn = new Set<string>();\n const nextLink = new Set<string>();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) nextFn.add(l);\n for (const l of cd.ownLinkLabels) nextLink.add(l);\n }\n this.labelSet.footnoteLabels = nextFn;\n this.labelSet.linkLabels = nextLink;\n this._notify();\n // Last chunk just left: notify the container so it can drop\n // this registry from its `documentId → Registry` map. The\n // identity check on the container side prevents racing a\n // freshly-allocated registry under the same documentId.\n //\n // Ordering note: `onEmpty` fires SYNCHRONOUSLY here, after\n // `_notify` has scheduled subscriber fanout (which itself\n // runs in a later microtask, see `_notifyScheduled`). So\n // the container evicts FIRST, then subscribers wake. A\n // subscriber that re-resolves via `getRegistry(documentId)`\n // during its wake-up therefore sees a freshly-allocated\n // registry — which is the right behavior, because by then\n // the consumer is genuinely starting over.\n if (this.chunkOrder.length === 0 && this.chunkData.size === 0 && onEmpty) {\n onEmpty();\n }\n }\n });\n }\n },\n\n contributeLabels(symbol: symbol, footnotes: Set<string>, links: Set<string>): void {\n const data = this.chunkData.get(symbol);\n if (data) {\n data.ownFootnoteLabels = footnotes;\n data.ownLinkLabels = links;\n } else {\n this.chunkData.set(symbol, {\n refs: [],\n defs: new Map(),\n linkDefs: new Map(),\n ownFootnoteLabels: footnotes,\n ownLinkLabels: links,\n });\n }\n // Always notify. The prior `if (fnChanged || linkChanged)` optimization\n // skipped the wake-up when the UNION labelSet was unchanged — but\n // chunkData has ALWAYS mutated by the time we reach this line (we either\n // overwrote ownFootnoteLabels/ownLinkLabels on an existing entry, or we\n // just created a fresh chunkData entry above). A subscriber keyed on\n // `registry.version` would observe live chunkData changing under a\n // stable snapshot — a useSyncExternalStore tearing violation. With the\n // microtask-coalesced `_notify`, the per-call cost is the version++\n // plus a single subscriber fanout per batch, so the optimization's\n // savings are nil; correctness wins.\n const newFn = new Set<string>();\n const newLink = new Set<string>();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) newFn.add(l);\n for (const l of cd.ownLinkLabels) newLink.add(l);\n }\n this.labelSet.footnoteLabels = newFn;\n this.labelSet.linkLabels = newLink;\n this._notify();\n },\n\n contributeChunkData(symbol: symbol, data: ChunkData): void {\n this.chunkData.set(symbol, data);\n // Rebuild labelSet too (data may extend or shrink it)\n this.labelSet.footnoteLabels = new Set();\n this.labelSet.linkLabels = new Set();\n for (const cd of this.chunkData.values()) {\n for (const l of cd.ownFootnoteLabels) this.labelSet.footnoteLabels.add(l);\n for (const l of cd.ownLinkLabels) this.labelSet.linkLabels.add(l);\n }\n this._notify();\n },\n\n subscribe(cb: () => void): () => void {\n this._subscribers.add(cb);\n return () => {\n this._subscribers.delete(cb);\n };\n },\n\n canonicalFootnoteFor(label: string): symbol | null {\n const id = normalizeId(label);\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (data?.defs.has(id)) return sym;\n }\n return null;\n },\n\n canonicalLinkFor(label: string): symbol | null {\n const id = normalizeId(label);\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (data?.linkDefs.has(id)) return sym;\n }\n return null;\n },\n\n globalNumber(label: string): number | null {\n const id = normalizeId(label);\n let n = 0;\n const seen = new Set<string>();\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n for (const ref of data.refs) {\n // Footnote numbering is a per-space ordinal; link/image refs share\n // the `refs` array but occupy a disjoint namespace, so they must\n // NOT advance the footnote counter.\n if (ref.kind !== 'footnote') continue;\n if (!seen.has(ref.label)) {\n seen.add(ref.label);\n n++;\n if (ref.label === id) return n;\n }\n }\n }\n return null;\n },\n\n resolveLinkDef(label: string): LinkDef | null {\n const sym = this.canonicalLinkFor(label);\n if (!sym) return null;\n return this.chunkData.get(sym)?.linkDefs.get(normalizeId(label)) ?? null;\n },\n\n getRefsForLabel(label: string): number {\n const id = normalizeId(label);\n let n = 0;\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n // Only count footnote refs: the consumers (backref-strip and\n // backref-inject) decide based on whether a footnote `<li>` should\n // exist, which depends on footnote refs alone.\n for (const ref of data.refs) {\n if (ref.kind === 'footnote' && ref.label === id) n++;\n }\n }\n return n;\n },\n\n globalOccurrenceForRef(chunkSym: symbol, label: string, localOccurrence: number): number | null {\n const id = normalizeId(label);\n let global = 0;\n for (const sym of this.chunkOrder) {\n const data = this.chunkData.get(sym);\n if (!data) continue;\n let localCount = 0;\n for (const ref of data.refs) {\n if (ref.kind !== 'footnote') continue;\n if (ref.label !== id) continue;\n localCount++;\n global++;\n if (sym === chunkSym && localCount === localOccurrence) return global;\n }\n }\n return null;\n },\n\n _notify(): void {\n this.version++;\n if (this._notifyScheduled) return;\n this._notifyScheduled = true;\n queueMicrotask(() => {\n this._notifyScheduled = false;\n // Snapshot subscribers so unsubscribes during fanout don't shift the\n // iteration. New subscribers added during fanout will pick up the\n // current `version` on their next render.\n for (const cb of [...this._subscribers]) cb();\n });\n },\n };\n // Internally `reg` has both the public API and the private state.\n // The return type narrows to the public {@link Registry} so the dts\n // emit doesn't expose `_reactIdMap` / `_subscribers` / `_notifyScheduled` /\n // `_notify` — those are operational invariants, not API surface.\n return reg as unknown as RegistryInternal as Registry;\n}\n","/**\n * Direction B: source-level phantom-definition injection helpers.\n *\n * @module components/remarkInjectPhantomDefs\n */\n\nexport const SENTINEL_LINK_URL = '__aimd_sentinel_link__';\nexport const SENTINEL_FN_CONTENT = '__aimd_sentinel_fn__';\n\nexport interface PhantomLabels {\n missingFootnotes: Set<string>;\n missingLinks: Set<string>;\n}\n\n/**\n * Compute the source string to feed to the full PASS 1 parser: original\n * content + appended phantom definitions for labels not locally defined.\n *\n * Labels are expected to already be normalized via normalizeId (uppercase).\n * The output is suitable as input to remark-parse with the standard pipeline.\n */\nexport function augmentSourceWithPhantoms(source: string, phantoms: PhantomLabels): string {\n if (phantoms.missingFootnotes.size === 0 && phantoms.missingLinks.size === 0) {\n return source;\n }\n let suffix = '\\n\\n';\n for (const label of phantoms.missingLinks) {\n suffix += `[${label}]: ${SENTINEL_LINK_URL}\\n`;\n }\n for (const label of phantoms.missingFootnotes) {\n suffix += `[^${label}]: ${SENTINEL_FN_CONTENT}\\n`;\n }\n return source + suffix;\n}\n","/**\n * Custom mdast-util-to-hast handlers for cross-chunk label resolution.\n *\n * Direction A: `footnoteDefinitionHandler` mutates `state.footnoteOrder` so\n * `state.footer()` emits a `<section data-footnotes>` even when no\n * `footnoteReference` exists locally (orphan-def protection).\n *\n * Direction B: `linkReferenceHandler` / `imageReferenceHandler` /\n * `footnoteReferenceHandler` short-circuit the default to-hast output and\n * emit custom hast tags (`cross-chunk-link` / `cross-chunk-image` /\n * `footnote-sup`) carrying `label` + `referenceType` properties. These tags\n * map to React placeholder components in Phase 11. The sentinel URL is never\n * read — the handlers only need to know that the def is resolvable\n * (i.e. present in state.definitionById).\n *\n * All identifier comparisons normalize via {@link normalizeId} to match\n * mdast-util-to-hast's internal uppercase keying convention.\n *\n * @module components/customMdastHandlers\n */\nimport type { Handlers } from 'mdast-util-to-hast';\nimport type { LinkReference, ImageReference, FootnoteReference, FootnoteDefinition } from 'mdast';\nimport type { Element as HastElement } from 'hast';\nimport { normalizeId } from './normalizeId';\n\nexport interface CrossChunkHandlerOptions {\n /** Set of labels (already normalized) that this chunk phantom-injected\n * into its source for parser acceptance. Handlers use this to short-circuit\n * state writes that would otherwise leak sentinel content into the footer. */\n phantomFootnoteLabels: Set<string>;\n /** Same role for link/image defs. */\n phantomLinkLabels: Set<string>;\n /** When true, footnoteDefinitionHandler proactively registers orphan defs\n * to state.footnoteOrder (Direction A). */\n preserveOrphan: boolean;\n /** Passed through to placeholder hast properties so React components can\n * partition by document. */\n documentId: string;\n}\n\n// Type assertion helper for state shape (mdast-util-to-hast doesn't export it).\ninterface StateShape {\n options: CrossChunkHandlerOptions & Record<string, unknown>;\n footnoteOrder: string[];\n footnoteCounts: Map<string, number>;\n definitionById: Map<string, unknown>;\n all: (node: unknown) => unknown[];\n}\n\nexport function buildCrossChunkHandlers(): Handlers {\n return {\n footnoteDefinition: (state: unknown, node: FootnoteDefinition): undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n // Phantom def → noop: do not register, do not emit. Footer will skip it\n // because footnoteOrder does not contain id (unless a real ref pushed it).\n if (s.options.phantomFootnoteLabels.has(id)) {\n return undefined;\n }\n // Direction A: orphan def protection. Register so state.footer() emits <li>.\n if (s.options.preserveOrphan && !s.footnoteOrder.includes(id)) {\n s.footnoteOrder.push(id);\n // Deliberately do NOT bump footnoteCounts. transformStripBackrefs\n // (Phase 7) reads registry.getRefsForLabel to decide backref strip\n // — independent of state.footnoteCounts.\n }\n return undefined; // never emit inline hast\n },\n\n linkReference: ((state: unknown, node: LinkReference): HastElement | undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n const resolved = s.definitionById.has(id);\n if (!resolved) {\n // Unreachable in coordinated pipeline because augmentSourceWithPhantoms\n // guarantees a def for every referenced label that survives PASS 0.5.\n // Verified by experiment: remark-parse produces a `linkReference`\n // mdast node ONLY when a corresponding `[label]:` exists in the\n // source — without one, the brackets are emitted as plain text by\n // the parser, so neither this handler nor mdast's default ever\n // sees the reference. Defense-in-depth for an impossible state.\n return undefined;\n }\n return {\n type: 'element',\n tagName: 'cross-chunk-link',\n properties: {\n // `label` is the ORIGINAL source text (mdast's `label` field), NOT\n // the normalized `identifier`. The placeholder uses it to construct\n // hrefs that line up with mdast-util-to-hast's default `<li id>`\n // which also preserves source case. Registry lookups normalize\n // internally, so cross-chunk case-insensitive matching still works.\n label: node.label ?? node.identifier,\n referenceType: node.referenceType,\n documentId: s.options.documentId,\n },\n children: s.all(node) as HastElement['children'],\n };\n }) as Handlers['linkReference'],\n\n imageReference: ((state: unknown, node: ImageReference): HastElement | undefined => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n const resolved = s.definitionById.has(id);\n if (!resolved) return undefined;\n return {\n type: 'element',\n tagName: 'cross-chunk-image',\n properties: {\n label: node.label ?? node.identifier,\n referenceType: node.referenceType,\n alt: node.alt ?? '',\n documentId: s.options.documentId,\n },\n children: [],\n };\n }) as Handlers['imageReference'],\n\n footnoteReference: ((state: unknown, node: FootnoteReference): HastElement => {\n const s = state as StateShape;\n const id = normalizeId(node.identifier);\n // Bump the per-id counter for ALL refs (phantom and real). The result\n // is the chunk-local occurrence index (1, 2, 3, …) which the placeholder\n // carries so FootnoteSupNumber can disambiguate duplicate fnref-* ids\n // when the same label is referenced multiple times. For phantom refs\n // bumping is safe: state.footer() emits <li> only for ids in\n // footnoteOrder, and phantoms never get pushed there.\n const localOccurrence = (s.footnoteCounts.get(id) ?? 0) + 1;\n s.footnoteCounts.set(id, localOccurrence);\n if (s.options.phantomFootnoteLabels.has(id)) {\n return {\n type: 'element',\n tagName: 'footnote-sup',\n properties: {\n label: node.identifier,\n localOccurrence,\n documentId: s.options.documentId,\n },\n children: [],\n };\n }\n // Real local def: register in footnoteOrder so the local synthetic\n // footer can emit a <li> for it.\n if (!s.footnoteOrder.includes(id)) s.footnoteOrder.push(id);\n return {\n type: 'element',\n tagName: 'footnote-sup',\n properties: {\n label: node.identifier,\n localOccurrence,\n documentId: s.options.documentId,\n },\n children: [],\n };\n }) as Handlers['footnoteReference'],\n };\n}\n","/**\n * Placeholder React components that custom hast tags\n * (`<cross-chunk-link>` / `<cross-chunk-image>` / `<footnote-sup>`)\n * map to via react-markdown's `components` prop.\n *\n * Each subscribes to its document's Registry via useSyncExternalStore.\n * On selector miss (registry not present, label not resolved):\n * - FootnoteSupNumber renders null\n * - CrossChunkLink falls back to literal source text by referenceType\n * - CrossChunkImage falls back to literal source text by referenceType\n *\n * @module components/crossChunkPlaceholders\n */\nimport { type ReactNode, isValidElement, useCallback, useContext, useSyncExternalStore } from 'react';\nimport { useAIMarkdownRenderState } from '../context';\nimport { useDocumentRegistry } from './AIMarkdownDocuments';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport type { LinkDef } from './documentRegistry';\n\ntype RefType = 'full' | 'collapsed' | 'shortcut' | undefined;\n\n/** Module-level SSR snapshot constant. Hoisted out of components so its\n * identity is stable across renders. */\nconst SSR_NUM_SNAPSHOT = () => 0;\nconst SSR_DEF_SNAPSHOT = () => null;\n\ninterface FootnoteSupProps {\n label: string;\n /** Chunk-local occurrence index (1-based) of THIS particular `[^x]`\n * reference within the chunk's parse. Used together with the per-chunk\n * Symbol from `ChunkSymbolContext` to compute the cross-chunk *global*\n * occurrence index, which disambiguates duplicate `id=\"fnref-X\"` when\n * the same footnote is referenced multiple times. Carried on the hast\n * tag by `customMdastHandlers.footnoteReference`.\n *\n * **Type note**: customMdastHandlers emits this as a JS number, but\n * rehype-raw's parse5 round-trip stringifies it (verified in\n * `customMdastHandlers.test.ts`). The component accepts either form\n * and coerces internally so the contract is robust to the pipeline. */\n localOccurrence?: number | string;\n /** Optional — but normally the hast tag carries it. */\n documentId?: string;\n}\n\n/** Coerce the on-the-wire `localOccurrence` (which may be a JS number from\n * the handler OR a stringified attr from rehype-raw's parse5 round-trip)\n * to a finite positive integer, or null if absent / malformed. */\nfunction coerceLocalOccurrence(v: number | string | undefined): number | null {\n if (v === undefined) return null;\n if (typeof v === 'number') return Number.isFinite(v) && v >= 1 ? Math.trunc(v) : null;\n const n = Number(v);\n return Number.isFinite(n) && n >= 1 ? Math.trunc(n) : null;\n}\n\nexport function FootnoteSupNumber({ label, localOccurrence: localOccurrenceRaw }: FootnoteSupProps): ReactNode {\n const localOccurrence = coerceLocalOccurrence(localOccurrenceRaw);\n const { documentId, clobberPrefix } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const chunkSym = useContext(ChunkSymbolContext);\n // Subscribe identity stabilised across renders (see top of file).\n // useSyncExternalStore's selector must return an `Object.is`-stable value\n // across notifications when the underlying registry state is unchanged —\n // `registry.version` is just a number, so this property holds.\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.version ?? 0, [registry]);\n useSyncExternalStore(subscribe, getSnapshot, SSR_NUM_SNAPSHOT);\n const num = registry?.globalNumber(label) ?? null;\n if (num === null) return null;\n if (localOccurrence !== null && !chunkSym) return null;\n const globalOcc =\n registry && chunkSym && localOccurrence !== null\n ? registry.globalOccurrenceForRef(chunkSym, label, localOccurrence)\n : null;\n if (localOccurrence !== null && globalOcc === null) return null;\n // Append `-N` when this is the 2nd+ occurrence of the same label across\n // the document. The first occurrence keeps the bare `fnref-${id}` so a\n // ref-once-only doc renders byte-identical to the pre-multi-ref design.\n const occSuffix = globalOcc !== null && globalOcc > 1 ? `-${globalOcc}` : '';\n return (\n <sup>\n <a href={`#${clobberPrefix}fn-${label}`} id={`${clobberPrefix}fnref-${label}${occSuffix}`} data-footnote-ref>\n {num}\n </a>\n </sup>\n );\n}\n\ninterface CrossChunkLinkProps {\n label: string;\n referenceType: RefType;\n children?: ReactNode;\n}\n\n/** Recursively flatten a ReactNode tree to plain text. The fallback for\n * an unresolved CrossChunkLink renders the literal markdown source\n * (`[text][label]`); the `[text]` slot must therefore be a string, not a\n * React element tree. Rich children — e.g. `[**bold**][missing]` whose\n * `[text]` slot mdast lowered to `<strong>bold</strong>` then react-\n * markdown handed us as `<strong>bold</strong>` React element — would\n * otherwise stringify as the literal `\"[object Object]\"` via the previous\n * `children?.toString?.()` path. Walking the tree and concatenating text\n * nodes degrades the rich markup to plain text but preserves the human-\n * readable label slot, which is what the fallback aims for. */\nfunction reactNodeToText(node: ReactNode): string {\n if (node === null || node === undefined || typeof node === 'boolean') return '';\n if (typeof node === 'string') return node;\n if (typeof node === 'number' || typeof node === 'bigint') return String(node);\n if (Array.isArray(node)) return node.map(reactNodeToText).join('');\n if (isValidElement(node)) {\n return reactNodeToText((node.props as { children?: ReactNode }).children);\n }\n return '';\n}\n\nfunction literalLink(rt: RefType, label: string, children: ReactNode): string {\n const text = reactNodeToText(children);\n switch (rt) {\n case 'full':\n return `[${text}][${label}]`;\n case 'collapsed':\n return `[${label}][]`;\n case 'shortcut':\n default:\n return `[${label}]`;\n }\n}\n\nexport function CrossChunkLink({ label, referenceType, children }: CrossChunkLinkProps): ReactNode {\n const { documentId } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.resolveLinkDef(label) ?? null, [registry, label]);\n const def = useSyncExternalStore<LinkDef | null>(subscribe, getSnapshot, SSR_DEF_SNAPSHOT);\n if (!def) {\n return literalLink(referenceType, label, children);\n }\n return (\n <a href={def.url} title={def.title}>\n {children}\n </a>\n );\n}\n\ninterface CrossChunkImageProps {\n label: string;\n referenceType: RefType;\n alt?: string;\n}\n\nfunction literalImage(rt: RefType, label: string, alt: string): string {\n switch (rt) {\n case 'full':\n return `![${alt}][${label}]`;\n case 'collapsed':\n return `![${alt}][]`;\n case 'shortcut':\n default:\n return `![${label}]`;\n }\n}\n\nexport function CrossChunkImage({ label, referenceType, alt = '' }: CrossChunkImageProps): ReactNode {\n const { documentId } = useAIMarkdownRenderState();\n const registry = useDocumentRegistry(documentId);\n const subscribe = useCallback((cb: () => void) => (registry ? registry.subscribe(cb) : () => {}), [registry]);\n const getSnapshot = useCallback(() => registry?.resolveLinkDef(label) ?? null, [registry, label]);\n const def = useSyncExternalStore<LinkDef | null>(subscribe, getSnapshot, SSR_DEF_SNAPSHOT);\n if (!def) {\n return literalImage(referenceType, label, alt);\n }\n return <img src={def.url} alt={alt} title={def.title} />;\n}\n\n/**\n * Components map suitable for spreading into react-markdown's `components` prop.\n * Keys are lowercase tag names matching the custom hast tags emitted by\n * Phase 6 handlers.\n */\nexport const crossChunkComponents = {\n 'footnote-sup': FootnoteSupNumber,\n 'cross-chunk-link': CrossChunkLink,\n 'cross-chunk-image': CrossChunkImage,\n};\n","/**\n * Per-chunk Symbol identity exposed via React context.\n *\n * Each coordinated `<AIMarkdownContent>` allocates a Symbol against its\n * documentId's Registry (via `useId` + `Registry.allocateSymbol`). Inline\n * placeholder components like `FootnoteSupNumber` need to know which chunk\n * they belong to so they can ask the registry for a chunk-scoped value\n * (e.g. the *global* occurrence index of a chunk-local footnote ref).\n *\n * Modelled as a tiny standalone context so consumers can subscribe without\n * dragging the full `MarkdownContent` module into their import graph.\n *\n * Value is `null` outside of a coordinated render (standalone single-doc\n * mode, or pre-allocation paint).\n *\n * @module components/chunkSymbolContext\n */\nimport { createContext } from 'react';\n\nexport const ChunkSymbolContext = createContext<symbol | null>(null);\n","/**\n * Walk an mdast tree and yield ref/def records in source order. Used by\n * AIMarkdownContent's PASS 1 contribute step to populate Registry.chunkData.\n *\n * Phantom definitions (Direction B) carry sentinel content/url but the\n * sentinel parse may not produce exactly the sentinel string at the AST\n * level (e.g. `__aimd_sentinel_fn__` parses as <strong>aimd_sentinel_fn</strong>).\n * Therefore phantom detection is done both ways:\n * - linkDef: check `url === SENTINEL_LINK_URL` (raw string survives parsing).\n * - fnDef: skip if the def's normalized identifier is in the supplied\n * `phantomFootnoteLabels` set. The caller knows which labels it\n * injected (PASS 0.5 `targetPhantoms.missingFootnotes`).\n *\n * @module components/extractContributions\n */\nimport { SKIP, visit } from 'unist-util-visit';\nimport type { Root as MdastRoot } from 'mdast';\nimport { normalizeId } from './normalizeId';\nimport { SENTINEL_LINK_URL } from './remarkInjectPhantomDefs';\n\nexport type Contribution =\n | {\n kind: 'ref';\n refKind: 'footnote' | 'link' | 'image';\n label: string;\n referenceType?: 'full' | 'collapsed' | 'shortcut';\n }\n | { kind: 'fnDef'; label: string; sourceIdentifier: string; content: string }\n | { kind: 'linkDef'; label: string; url: string; title?: string };\n\nexport interface ExtractContributionsOptions {\n /** Already-normalized labels that were phantom-injected at PASS 0.5.\n * Defs matching these are skipped to avoid leaking sentinel rows into\n * registry.chunkData. */\n phantomFootnoteLabels?: Set<string>;\n}\n\nexport function* extractContributions(\n mdast: MdastRoot,\n options: ExtractContributionsOptions = {}\n): Generator<Contribution> {\n const phantomFn = options.phantomFootnoteLabels;\n const out: Contribution[] = [];\n visit(mdast, (n) => {\n if (n.type === 'footnoteReference') {\n out.push({\n kind: 'ref',\n refKind: 'footnote',\n label: normalizeId((n as { identifier: string }).identifier),\n });\n } else if (n.type === 'linkReference') {\n const r = n as { identifier: string; referenceType: 'full' | 'collapsed' | 'shortcut' };\n out.push({ kind: 'ref', refKind: 'link', label: normalizeId(r.identifier), referenceType: r.referenceType });\n } else if (n.type === 'imageReference') {\n const r = n as { identifier: string; referenceType: 'full' | 'collapsed' | 'shortcut' };\n out.push({ kind: 'ref', refKind: 'image', label: normalizeId(r.identifier), referenceType: r.referenceType });\n } else if (n.type === 'footnoteDefinition') {\n const d = n as { identifier: string; children: unknown[] };\n const label = normalizeId(d.identifier);\n // Skip phantom-injected (by injected-label set, since the sentinel\n // string may not survive markdown parsing intact).\n if (phantomFn?.has(label)) return SKIP;\n // Best-effort raw content snapshot: stringify the first child's\n // structure. Footnote definitions are typed `(BlockContent | DefinitionContent)[]`\n // so we serialize loosely. Used only as a coarse fingerprint string.\n const content = JSON.stringify(d.children ?? []);\n // d.identifier is mdast's already-case-folded form — the same string\n // mdast-util-to-hast uses in `<li id=\"...fn-${id}\">`. Tracked separately\n // from the uppercase-normalized `label` (used as a dictionary key) so\n // HTML ids built downstream match the inline sup's href byte-for-byte.\n //\n // bodyHast is NOT computed here — see extractDefBodiesFromHast for\n // why we source it from the post-pipeline hast instead.\n out.push({ kind: 'fnDef', label, sourceIdentifier: d.identifier, content });\n // SKIP descent into the def's children: NESTED footnoteReferences /\n // linkReferences / imageReferences inside a def body should NOT\n // count as flow refs. Without this, a def whose body contains\n // `[^x]: see [^a].` would record an extra ref to `a` in registry\n // refs — inflating `globalNumber('a')` (making `a` appear in the\n // aggregate footer even if no flow text references it), and worse,\n // inflating `getRefsForLabel('a')` so the aggregate emits a backref\n // anchor to `#fnref-a-2` that points at an id no inline `<sup>`\n // ever rendered. Trade-off: a footnoteDefinition nested INSIDE\n // another def's body (allowed by GFM but exceedingly rare) is also\n // not extracted; deferred until we see a real use case.\n return SKIP;\n } else if (n.type === 'definition') {\n const d = n as { identifier: string; url: string; title?: string };\n if (d.url === SENTINEL_LINK_URL) return;\n out.push({ kind: 'linkDef', label: normalizeId(d.identifier), url: d.url, title: d.title });\n }\n });\n for (const c of out) yield c;\n}\n","/**\n * Extract footnote-definition bodies from a chunk's POST-pipeline hast tree.\n *\n * Why not just `toHast(def.children)` in extractContributions? That call runs\n * only mdast-util-to-hast's default handlers — no rehype-katex, no rehype-raw,\n * no rehype-footer-adorn, no clobber-prefix application. Defs containing math\n * (`$x$`), inline raw HTML, or definition-list extensions would render\n * incorrectly inside the cross-chunk aggregate footer.\n *\n * Instead, we read the FINAL hast: mdast-util-to-hast's `state.footer()` has\n * already emitted `<section data-footnotes><ol><li id=\"...fn-X\">body</li>…`\n * for every def that has a real entry in `state.footnoteOrder`, the full\n * rehype chain has run on top, and the per-`<li>` body is exactly what the\n * standalone path would render. Lift those `<li>` children (minus the\n * auto-emitted backref `<a>`s, which the aggregate emits itself per\n * occurrence) and key by normalized label.\n *\n * Chunks whose only refs are phantom-injected (cross-chunk) won't have a\n * synthetic `<section>` at all — those chunks contribute no defs, and the\n * canonical-chunk handler upstream guarantees the def's body is captured\n * from the chunk that owns it.\n *\n * @module components/extractDefBodiesFromHast\n */\nimport { SKIP, visit } from 'unist-util-visit';\nimport type { Element as HastElement, Root as HastRoot, ElementContent } from 'hast';\nimport { normalizeId } from './normalizeId';\n\n// Fallback for callers that do not know the exact clobberPrefix. The main\n// renderer passes the prefix explicitly so labels containing regex metacharacters\n// or prefixes containing `user-content-fn-` are handled by string slicing.\nconst FN_LI_ID_RE = /(?:^|-)user-content-fn-(.+)$/;\n\nfunction sourceIdFromFootnoteLiId(idProp: string, clobberPrefix?: string): string | null {\n let raw: string | null = null;\n if (clobberPrefix !== undefined) {\n const exactPrefix = `${clobberPrefix}fn-`;\n if (idProp.startsWith(exactPrefix)) raw = idProp.slice(exactPrefix.length);\n }\n if (raw === null) {\n const m = idProp.match(FN_LI_ID_RE);\n raw = m ? m[1] : null;\n }\n if (raw === null) return null;\n // mdast-util-to-hast's footer emits `<li id=\"${prefix}fn-${normalizeUri(id)}\">`\n // which percent-encodes whitespace, non-ASCII characters (`中文` → `%E4%B8%AD…`),\n // and most URL-unsafe punctuation. The registry's def key (set by\n // extractContributions via `normalizeId(node.identifier)`) is the DECODED\n // form — uppercase + whitespace-collapsed but otherwise the source bytes.\n // Without decoding here, every label that triggers normalizeUri encoding\n // (CJK, accented Latin, spaces, `&`/`?` punctuation) would key-mismatch\n // between harvested body and registry def, leaving the aggregate footer's\n // `<li>` empty for those labels.\n try {\n return decodeURIComponent(raw);\n } catch {\n // Malformed percent-encoding (extremely rare — would require user-\n // supplied raw HTML in the def's id). Fall back to the raw form rather\n // than crashing the harvest.\n return raw;\n }\n}\n\nfunction isBackrefAnchor(c: ElementContent): boolean {\n if (c.type !== 'element') return false;\n const el = c as HastElement;\n if (el.tagName !== 'a') return false;\n return Boolean(el.properties && 'dataFootnoteBackref' in el.properties);\n}\n\nfunction isWhitespaceText(c: ElementContent): boolean {\n if (c.type !== 'text') return false;\n return /^\\s*$/.test((c as { value: string }).value);\n}\n\n/** Index of the last child that isn't a whitespace-only text node, or -1\n * if no such child exists. mdast-util-to-hast's `state.wrap(content, true)`\n * inserts `\\n` text nodes between (and around) block-level children of\n * `<li>`; we have to look past those to find the meaningful tail before\n * deciding which backref-strip case applies. */\nfunction lastMeaningfulIdx(children: ElementContent[]): number {\n for (let i = children.length - 1; i >= 0; i--) {\n if (!isWhitespaceText(children[i])) return i;\n }\n return -1;\n}\n\n/**\n * Drop trailing auto-emitted backref anchors and any separator whitespace\n * mdast-util-to-hast emitted before them. Operates only on the tail of\n * `children` — does NOT recurse into mid-list elements — so user content\n * elsewhere in the def that happens to look like a backref anchor survives.\n *\n * The shapes we have to undo (see `mdast-util-to-hast/lib/footer.js`):\n *\n * - **trailing wrap whitespace**: `state.wrap(content, true)` inserts\n * `\\n` text nodes between/around block-level children of `<li>`. The\n * auto-emitted backref sits BEFORE the trailing `\\n`, so we have to\n * peel past whitespace before checking for the backref. Confirmed by\n * a real-pipeline trace: an empty def produces\n * `<li>` children = `[\"\\n\", <a backref>, \"\\n\"]`.\n * - **standalone separator** between consecutive backrefs (and before\n * the first one when the trailing child is NOT a text node): a `{type:\n * 'text', value: ' '}` element pushed alongside the backref anchor.\n * - **merged separator** before the first backref when the trailing\n * child IS a text node: footer.js does `tailTail.value += ' '`, so the\n * leading space is concatenated INTO the existing text node rather\n * than pushed as a separate node. After peeling the backrefs, that\n * residual trailing space sits at the end of the last text node and\n * would visibly double when the aggregate footer prepends its own\n * separator. Trim exactly one trailing space to undo it.\n */\nfunction dropTrailingBackrefs(children: ElementContent[]): ElementContent[] {\n // Step 1: identify trailing whitespace-only text nodes. Preserve them\n // verbatim in the output — they're semantically part of mdast-util-to-\n // hast's expected shape and downstream serializers may rely on them.\n let trailingWsStart = children.length;\n while (trailingWsStart > 0 && isWhitespaceText(children[trailingWsStart - 1])) {\n trailingWsStart--;\n }\n // Step 2: scan backwards from the last non-whitespace child, peeling\n // backref anchors and their inter-backref `' '` separators.\n let scan = trailingWsStart;\n let peeledAny = false;\n while (scan > 0) {\n const t = children[scan - 1];\n if (!isBackrefAnchor(t)) break;\n peeledAny = true;\n scan -= 1;\n if (scan > 0 && children[scan - 1].type === 'text' && (children[scan - 1] as { value: string }).value === ' ') {\n scan -= 1;\n }\n }\n if (!peeledAny) return children;\n const trailing = children.slice(trailingWsStart);\n // Step 3: undo the merged-separator case. Trim exactly ONE trailing\n // space from the last surviving text node (matching footer.js's\n // `+= ' '`). Multiple trailing spaces stay intact — only the one\n // footer.js appended is ours to remove. Whitespace-only text nodes\n // (e.g. `\\n`) don't qualify for trim — they aren't merged separators.\n if (scan > 0) {\n const last = children[scan - 1];\n if (last.type === 'text') {\n const v = (last as { value: string }).value;\n if (v.endsWith(' ') && !/^\\s*$/.test(v)) {\n return [...children.slice(0, scan - 1), { ...last, value: v.slice(0, -1) } as ElementContent, ...trailing];\n }\n }\n }\n return [...children.slice(0, scan), ...trailing];\n}\n\n/**\n * Strip mdast-util-to-hast's auto-emitted backref anchors from a `<li>`\n * body. The library only ever appends backrefs in one of two locations:\n * (a) directly at the end of the `<li>`'s children (after `state.wrap`\n * interleaves whitespace nodes between block-level siblings), OR\n * (b) at the end of the last `<p>` child of the `<li>`.\n * We handle both — and nothing else — to avoid stripping any\n * `data-footnote-backref`-shaped element that happens to live in user\n * content elsewhere in the def body.\n */\nfunction stripBackrefs(liChildren: ElementContent[]): ElementContent[] {\n if (liChildren.length === 0) return liChildren;\n // Look past mdast-util-to-hast's trailing `\\n` text node(s) to find the\n // meaningful tail. That tells us which of the two cases applies.\n const lastIdx = lastMeaningfulIdx(liChildren);\n if (lastIdx < 0) return liChildren;\n const last = liChildren[lastIdx];\n\n // Direct-into-li case (case A): meaningful tail IS the backref. Peel\n // from `<li>` children; dropTrailingBackrefs handles the trailing `\\n`.\n if (isBackrefAnchor(last)) {\n return dropTrailingBackrefs(liChildren);\n }\n\n // Inside-<p> case (case B): meaningful tail is `<p>` and backrefs live\n // inside its inline children. `<p>` itself has no wrap-emitted whitespace\n // (state.wrap only fires for block-level lists), so dropTrailingBackrefs\n // can scan the `<p>`'s children directly. Preserve any trailing\n // whitespace nodes that follow the `<p>` in `<li>` exactly as-is.\n if (last.type === 'element' && (last as HastElement).tagName === 'p') {\n const p = last as HastElement;\n const newPChildren = dropTrailingBackrefs(p.children as ElementContent[]);\n if (newPChildren === p.children) return liChildren;\n return liChildren.map((c, i) => (i === lastIdx ? ({ ...p, children: newPChildren } as ElementContent) : c));\n }\n\n return liChildren;\n}\n\n/**\n * Walk `hast` and return a map from normalized footnote label to the\n * cleaned-up body hast of that label's `<li>`. The body has had any\n * `<a data-footnote-backref>` anchors removed at any nesting depth so the\n * aggregate footer can emit its own per-occurrence backrefs without\n * duplicating the locally-injected one.\n */\n/**\n * Walk a body and clear `localOccurrence` props on any `<footnote-sup>`\n * placeholders we find. NESTED footnote refs inside a def body (`[^x]: see\n * [^y]`) emit placeholders whose `localOccurrence` is keyed to the parsing\n * chunk's `state.footnoteCounts`. When the aggregate footer renders the\n * harvested body under the LAST chunk's `ChunkSymbolContext.Provider`,\n * `globalOccurrenceForRef(lastChunkSym, label, localOccurrence)` resolves\n * against the wrong chunk — returning `null` and short-circuiting the\n * inline sup to render blank.\n *\n * The fix degrades gracefully: strip `localOccurrence` from harvested\n * placeholders so `FootnoteSupNumber` falls through to the\n * \"no occurrence supplied\" path — which renders a sup with the bare\n * `fnref-${label}` href (i.e. the first-occurrence anchor). Backref\n * navigation still works (any occurrence href is valid for \"jump back\");\n * the only loss is occurrence-precision for nested footnote refs in\n * aggregate-rendered bodies, which is an edge case GFM permits but rarely\n * exercised in practice. The PRIMARY render (the originating chunk's own\n * block output) is unaffected — it still has the full localOccurrence\n * resolved against the correct chunk symbol.\n */\nfunction stripLocalOccurrenceFromFootnoteSups(children: ElementContent[]): ElementContent[] {\n let changed = false;\n const out: ElementContent[] = [];\n for (const c of children) {\n if (c.type === 'element') {\n const el = c as HastElement;\n let nextEl: HastElement = el;\n if (el.tagName === 'footnote-sup' && el.properties && 'localOccurrence' in el.properties) {\n const { localOccurrence: _drop, ...rest } = el.properties;\n nextEl = { ...el, properties: rest };\n changed = true;\n }\n // Recurse into element children to catch nested placeholders.\n const newChildren = stripLocalOccurrenceFromFootnoteSups(nextEl.children as ElementContent[]);\n if (newChildren !== nextEl.children) {\n nextEl = { ...nextEl, children: newChildren };\n changed = true;\n }\n out.push(nextEl);\n } else {\n out.push(c);\n }\n }\n return changed ? out : children;\n}\n\nexport function extractDefBodiesFromHast(hast: HastRoot, clobberPrefix?: string): Map<string, ElementContent[]> {\n const out = new Map<string, ElementContent[]>();\n visit(hast, 'element', (sectionNode) => {\n const sec = sectionNode as HastElement;\n if (sec.tagName !== 'section') return;\n if (!(sec.properties && 'dataFootnotes' in sec.properties)) return;\n visit(sec, 'element', (liNode) => {\n const li = liNode as HastElement;\n if (li.tagName !== 'li') return;\n const idProp = li.properties?.id;\n if (typeof idProp !== 'string') return;\n const sourceId = sourceIdFromFootnoteLiId(idProp, clobberPrefix);\n if (sourceId === null) return;\n const normalized = normalizeId(sourceId);\n const stripped = stripBackrefs(li.children as ElementContent[]);\n // Defuse any nested `<footnote-sup>` placeholders whose local\n // occurrence indices belong to a different chunk than where the\n // body will eventually be rendered. See the function's JSDoc.\n out.set(normalized, stripLocalOccurrenceFromFootnoteSups(stripped));\n });\n // SKIP descent into this section's children so a NESTED\n // `<section data-footnotes>` (rare — produced only via user-supplied\n // raw HTML inside a def body that survives rehype-raw + sanitize)\n // isn't double-processed by both the outer visit's recursion and the\n // inner visit's enumeration of its parent. Without the SKIP, an\n // `<li>` inside the nested section is harvested twice; `out.set` is\n // last-write-wins so a nested mutation can stomp a correctly-\n // extracted outer body. SKIP scopes harvest to the outer section\n // and leaves nested footnote sections for whatever tool authored\n // them to handle.\n return SKIP;\n });\n return out;\n}\n","/**\n * Aggregate footnote section for cross-chunk coordination.\n *\n * In standalone mode mdast-util-to-hast emits one `<section data-footnotes>`\n * per parse. In coordinated mode (multiple `<AIMarkdown>` chunks sharing a\n * documentId under `<AIMarkdownDocuments>`) each chunk's local section is\n * suppressed (`renderBlocksWithCache` skips the synthetic plan item when\n * `postOptions.registry` is set). This component takes its place: it renders\n * exactly one consolidated `<section data-footnotes>` at the end of each\n * document's LAST mounted chunk, with all defs across chunks in global\n * footnote-number order.\n *\n * Why per-chunk component instead of a sibling: each `<AIMarkdownContent>`\n * already subscribes to its registry via useSyncExternalStore. Rendering the\n * aggregate inside the same component avoids a second subscriber and keeps\n * the footer naturally positioned at the end of the markdown output. When a\n * new chunk mounts and becomes the last, the previously-last chunk's\n * aggregate disappears in the same React commit (returns null), and the new\n * last chunk's aggregate appears.\n *\n * Per-documentId scoping is implicit: registries are keyed by documentId in\n * `useDocumentRegistry`, so the \"last chunk\" check naturally partitions to\n * one footer per document.\n *\n * @module components/aggregateFootnotesIfLast\n */\nimport { memo, useMemo, type FC } from 'react';\nimport type { Element as HastElement, ElementContent as HastElementContent } from 'hast';\nimport { renderHastSubtree } from './markdown';\nimport type { Registry } from './documentRegistry';\nimport type { PostOptions } from './blockMemo';\n\ninterface AggregateFootnotesIfLastProps {\n registry: Registry;\n thisChunkSym: symbol;\n clobberPrefix: string;\n postOptions: PostOptions;\n preserveOrphanReferences?: boolean;\n}\n\ninterface OrderedDef {\n /** Uppercase-normalized label, used to query `registry.getRefsForLabel`. */\n normalizedLabel: string;\n /** mdast's case-folded identifier — used in HTML ids so the aggregate\n * footer's `<li id>` matches the inline sup's anchor href exactly. */\n sourceIdentifier: string;\n bodyHast: HastElementContent[];\n n: number | null;\n withBackref: boolean;\n}\n\nfunction cloneHast<T extends HastElementContent>(node: T): T {\n return JSON.parse(JSON.stringify(node)) as T;\n}\n\n/** Whitespace-only text node — produced by mdast-util-to-hast's\n * `state.wrap(content, true)` to interleave `\\n` between block-level\n * `<li>` children. We have to look past these to find the actual tail. */\nfunction isWhitespaceText(c: HastElementContent): boolean {\n return c.type === 'text' && /^\\s*$/.test((c as { value: string }).value);\n}\n\n/** Index of the LAST meaningful (non-whitespace-text) child of `<li>`, or\n * -1 if no such child exists. Used to decide where to append backrefs:\n * mdast-util-to-hast's contract is \"if the tail of `<li>`'s content array\n * is `<p>`, push backrefs into it; else push them directly to `<li>`'s\n * content\". The tail check must skip wrap-emitted `\\n` text nodes that\n * surround the meaningful children, otherwise we'd wrongly classify the\n * trailing `\\n` as the tail and bypass the `<p>` append path. */\nfunction lastMeaningfulIdx(children: HastElementContent[]): number {\n for (let i = children.length - 1; i >= 0; i--) {\n if (!isWhitespaceText(children[i])) return i;\n }\n return -1;\n}\n\n/**\n * Build a backref anchor for a specific occurrence of a footnote ref.\n * Matches mdast-util-to-hast's default `defaultFootnoteBackContent`:\n * - Anchor content is always the text `↩`.\n * - When occurrence > 1, a child `<sup>${N}</sup>` is appended so the\n * digit renders as a superscript (visually `↩²`, `↩³`, …) instead of\n * a flat string like `↩2`.\n * - The 1st occurrence href is bare `#fnref-${id}`; the N-th (N > 1)\n * href is `#fnref-${id}-${N}` to match `FootnoteSupNumber`'s\n * suffix-disambiguated id on the inline sup side.\n */\nfunction buildBackref(href: string, occurrence: number, globalNumber: number): HastElement {\n const children: HastElement['children'] = [{ type: 'text', value: '↩' }];\n if (occurrence > 1) {\n children.push({\n type: 'element',\n tagName: 'sup',\n properties: {},\n children: [{ type: 'text', value: String(occurrence) }],\n });\n }\n const ariaLabel =\n occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`;\n return {\n type: 'element',\n tagName: 'a',\n properties: {\n href,\n dataFootnoteBackref: '',\n className: ['data-footnote-backref'],\n ariaLabel,\n },\n children,\n };\n}\n\nfunction buildAggregateTree(\n registry: Registry,\n clobberPrefix: string,\n preserveOrphanReferences = false\n): HastElement | null {\n // Walk chunkOrder; collect first occurrence per FOOTNOTE label in source\n // order. Mirrors `registry.globalNumber`'s numbering semantics so the n\n // values match the inline `<sup>` numbers. Link/image refs share the\n // `refs` array but belong to a disjoint namespace — they must be skipped\n // here, otherwise a link-ref to a label sharing text with a footnote-def\n // would cause a duplicate `<li>` in the aggregate footer.\n const seen = new Set<string>();\n const ordered: OrderedDef[] = [];\n for (const sym of registry.chunkOrder) {\n const data = registry.chunkData.get(sym);\n if (!data) continue;\n for (const ref of data.refs) {\n if (ref.kind !== 'footnote') continue;\n if (seen.has(ref.label)) continue;\n seen.add(ref.label);\n const canonicalSym = registry.canonicalFootnoteFor(ref.label);\n if (!canonicalSym) continue;\n const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);\n if (!def) continue;\n const n = registry.globalNumber(ref.label);\n if (n === null) continue;\n // Fall back to the uppercase-normalized label when sourceIdentifier is\n // absent (older fixtures); production data always carries the field.\n const sourceIdentifier = def.sourceIdentifier ?? ref.label;\n ordered.push({\n normalizedLabel: ref.label,\n sourceIdentifier,\n bodyHast: def.bodyHast ?? [],\n n,\n withBackref: true,\n });\n }\n }\n\n if (preserveOrphanReferences) {\n for (const sym of registry.chunkOrder) {\n const data = registry.chunkData.get(sym);\n if (!data) continue;\n for (const [label, def] of data.defs) {\n if (seen.has(label)) continue;\n if (registry.canonicalFootnoteFor(label) !== sym) continue;\n seen.add(label);\n ordered.push({\n normalizedLabel: label,\n sourceIdentifier: def.sourceIdentifier ?? label,\n bodyHast: def.bodyHast ?? [],\n n: null,\n withBackref: false,\n });\n }\n }\n }\n\n if (ordered.length === 0) return null;\n\n const liElements: HastElement[] = ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {\n const liChildren = bodyHast.map((c) => cloneHast(c));\n if (withBackref) {\n // Emit one backref anchor per global occurrence of this label. The\n // first href uses the bare `fnref-${id}` (matches FootnoteSupNumber's\n // unsuffixed first ref); the Nth (N > 1) uses `fnref-${id}-${N}`\n // (matches FootnoteSupNumber's `-N` suffix on subsequent refs).\n //\n // A single space text node precedes each anchor so adjacent backrefs\n // don't run together visually (and so the first backref doesn't butt\n // up against the def body's trailing text). This mirrors what\n // mdast-util-to-hast's default footer naturally produces: the trailing\n // newline in the def's source becomes a text \" \" between body and\n // backref, plus an explicit space separator between consecutive\n // backrefs (see mdast-util-to-hast `lib/footer.js`).\n const totalRefs = registry.getRefsForLabel(normalizedLabel);\n // Match mdast-util-to-hast's append rule: if the TAIL of the def\n // body (skipping wrap-emitted `\\n`) is `<p>`, push backrefs into\n // it; otherwise push them at the end of the `<li>` directly. The\n // previous logic searched for the last `<p>` anywhere in the body,\n // which mis-placed the backref BEFORE a trailing `<pre>` /\n // `<blockquote>` / etc. for multi-block defs.\n const tailIdx = lastMeaningfulIdx(liChildren);\n const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;\n const dest =\n tail && tail.type === 'element' && (tail as HastElement).tagName === 'p' ? (tail as HastElement) : null;\n const appended: HastElementContent[] = [];\n for (let i = 1; i <= Math.max(totalRefs, 1); i++) {\n appended.push({ type: 'text', value: ' ' });\n const href =\n i === 1 ? `#${clobberPrefix}fnref-${sourceIdentifier}` : `#${clobberPrefix}fnref-${sourceIdentifier}-${i}`;\n appended.push(buildBackref(href, i, n ?? 0));\n }\n if (dest) {\n dest.children = [...dest.children, ...appended];\n } else if (tailIdx !== -1) {\n // Splice after the meaningful tail so any subsequent trailing\n // whitespace (`\\n` from state.wrap) survives at the end of the\n // <li>, matching mdast-util-to-hast's post-wrap shape:\n // [..., <tail-block>, ...backrefs, \"\\n\"]\n liChildren.splice(tailIdx + 1, 0, ...appended);\n } else {\n liChildren.push(...appended);\n }\n }\n return {\n type: 'element',\n tagName: 'li',\n properties: {\n id: `${clobberPrefix}fn-${sourceIdentifier}`,\n ...(n !== null ? { value: n } : {}),\n },\n children: liChildren,\n };\n });\n\n return {\n type: 'element',\n tagName: 'section',\n properties: {\n className: ['footnotes'],\n dataFootnotes: true,\n // a11y: name the section landmark so screen readers still announce it\n // even though the visible \"Footnotes\" h2 is omitted in coordinated mode.\n ariaLabel: 'Footnotes',\n },\n children: [\n // Conventional separator above the footnote list. The default\n // mdast-util-to-hast footer doesn't emit one (GitHub renders the\n // separation via CSS `border-top` on `.footnotes`); we render a literal\n // `<hr>` so the visual break is preserved without sanitize-friendly CSS.\n {\n type: 'element',\n tagName: 'hr',\n properties: {},\n children: [],\n },\n {\n type: 'element',\n tagName: 'ol',\n properties: {},\n children: liElements,\n },\n ],\n };\n}\n\nconst AggregateFootnotesIfLastImpl: FC<AggregateFootnotesIfLastProps> = ({\n registry,\n thisChunkSym,\n clobberPrefix,\n postOptions,\n preserveOrphanReferences = false,\n}) => {\n // Memoize the hast tree by registry.version + clobberPrefix +\n // preserveOrphanReferences. Without this, every parent re-render walks\n // `registry.chunkOrder` (O(N) per call) and rebuilds the tree even when\n // the underlying registry state is unchanged — the parent re-renders on\n // every `_notify` from any chunk, which scales as O(N) on initial mount.\n // The aggregate is content-determined by (version, prefix, orphan-flag);\n // anything else (postOptions identity changes that don't change render\n // output) is irrelevant to the tree.\n const tree = useMemo(\n () => buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [registry, registry.version, clobberPrefix, preserveOrphanReferences]\n );\n const order = registry.chunkOrder;\n if (order.length === 0) return null;\n if (order[order.length - 1] !== thisChunkSym) return null;\n if (!tree) return null;\n // `renderHastSubtree` mutates its input tree in place (see comment on\n // that function: it assumes the tree is freshly produced per render).\n // Our `tree` is memoised by registry.version, so a non-version-bumping\n // parent re-render would re-enter the same cached tree. Any non-\n // idempotent transform (a user-supplied non-idempotent `urlTransform`\n // is the realistic case) would then compound on every re-render. Clone\n // before rendering so the cached `tree` stays pristine.\n return <>{renderHastSubtree(cloneHast(tree), postOptions)}</>;\n};\n\nexport const AggregateFootnotesIfLast = memo(AggregateFootnotesIfLastImpl);\nAggregateFootnotesIfLast.displayName = 'AggregateFootnotesIfLast';\n","/**\n * Hook for referential stability of deep-equal values.\n *\n * @module hooks/useStableValue\n */\n\nimport { useRef, useLayoutEffect, useEffect } from 'react';\nimport isEqual from 'lodash-es/isEqual';\n\n// Use layout effect on the client (synchronous after commit) and fall back to\n// useEffect during SSR to avoid the \"useLayoutEffect does nothing on the server\"\n// warning. Synchronous commit is what we want — it closes the window between\n// commit and ref advancement where an intermediate synchronous re-render would\n// otherwise see a stale cached reference.\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\n/**\n * Returns a referentially stable version of `value`.\n *\n * On each render the new value is deep-compared (via `lodash/isEqual`) against\n * the previous one. If they are structurally equal the *previous* reference is\n * returned, preventing unnecessary re-renders in downstream `useMemo` / `useEffect`\n * consumers that depend on reference equality.\n *\n * The ref is updated in a layout effect (not during render) so that the cached\n * reference only advances on COMMITTED renders. In concurrent mode a render\n * may be discarded (e.g. by Suspense); writing to the ref during render would\n * let values from discarded renders pollute the cache and leak into subsequent\n * committed renders. Layout effects run synchronously right after commit, which\n * closes the window where a same-tick re-render could otherwise observe a stale\n * `ref.current` and hand back an outdated reference.\n *\n * @typeParam T - The value type.\n * @param value - The potentially new value to stabilize.\n * @returns The previous reference when deep-equal, otherwise the new value.\n *\n * @example\n * ```tsx\n * const stableConfig = useStableValue(config);\n * // stableConfig keeps the same reference as long as config is deep-equal.\n * ```\n */\nexport default function useStableValue<T>(value: T): T {\n const ref = useRef(value);\n\n // eslint-disable-next-line react-hooks/refs\n const prev = ref.current;\n const stableValue = isEqual(prev, value) ? prev : value;\n\n useIsomorphicLayoutEffect(() => {\n ref.current = stableValue;\n }, [stableValue]);\n\n return stableValue;\n}\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n","import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n","import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n","import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n","import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n","/**\n * Dev-only React hook that warns when a prop's reference identity changes\n * suspiciously often across renders — symptomatic of a caller that defined\n * the value inline instead of at module scope or behind `useMemo` /\n * `useCallback`. The wrapper of `<AIMarkdown>` uses this to flag\n * `urlTransform` and `sanitizeSchema` props that would otherwise silently\n * discard the per-block memo cache on every render.\n *\n * In production builds the entire warning logic is dead-code-eliminated:\n * the gate `typeof process !== 'undefined' && process.env.NODE_ENV !==\n * 'production'` folds to a constant `false` after bundler substitution,\n * so the body's `if (!__DEV__) return;` becomes `return undefined;` and\n * the rest is dropped. The single `useRef` allocation remains\n * (unconditional, by rules of hooks) but is harmless.\n *\n * @module hooks/useReferenceFlipWarning\n */\n\nimport { useRef } from 'react';\n\n/** Module-scope dev flag. Bundlers fold this to a constant in production. */\nconst __DEV__ =\n typeof process !== 'undefined' && process.env.NODE_ENV !== 'production';\n\n/** How many identity flips before the first warning fires. */\nconst FLIP_THRESHOLD = 3;\n\n/** Minimum delay between successive warnings, milliseconds. */\nconst WARN_COOLDOWN_MS = 5000;\n\n/** Internal state mutated by {@link trackFlip} across renders. */\nexport interface FlipState {\n prev: unknown;\n flips: number;\n lastWarnAt: number;\n}\n\n/**\n * Pure flip-counting + rate-limiting logic, exported for unit testing.\n *\n * Mutates `state` in place and emits at most one `console.warn` per call.\n * Caller supplies `now` so tests can control the clock without mocking\n * `Date.now()`.\n */\nexport function trackFlip(\n state: FlipState,\n value: unknown,\n propName: string,\n now: number\n): void {\n if (state.prev === value) return;\n state.flips++;\n state.prev = value;\n if (state.flips < FLIP_THRESHOLD) return;\n if (now - state.lastWarnAt < WARN_COOLDOWN_MS) return;\n state.lastWarnAt = now;\n console.warn(\n `[AIMarkdown] \\`${propName}\\` reference is changing on every render. ` +\n `Define it at module scope or wrap with useMemo/useCallback to avoid ` +\n `discarding the per-block memo cache on every parent re-render.`\n );\n}\n\n/**\n * Track a value across renders and emit a dev-only warning when its\n * reference identity flips frequently.\n *\n * @param value - The prop value to monitor (function, object, or any\n * reference type whose identity should be stable).\n * @param propName - Human-readable name used in the warning text.\n */\nexport default function useReferenceFlipWarning<T>(value: T, propName: string): void {\n // useRef must be called unconditionally — rules of hooks. The seed value\n // matches `value` so the first render does not count as a flip. Sentinel\n // `-Infinity` for `lastWarnAt` ensures the first warn-eligible event is\n // never blocked by the cooldown comparison.\n const stateRef = useRef<FlipState>({ prev: value, flips: 0, lastWarnAt: -Infinity });\n if (!__DEV__) return;\n // Intentional render-time `Date.now()`: this hook's whole purpose is to\n // observe wall-clock cooldowns between flip events. Routing the timestamp\n // through useMemo/useEffect would either pin it to a value-change snapshot\n // (wrong semantics for a wall-clock cooldown) or delay it by a commit\n // (loses the very render where the flip happened).\n // eslint-disable-next-line react-hooks/purity\n trackFlip(stateRef.current, value, propName, Date.now());\n}\n","/**\n * Default typography wrapper component.\n *\n * Renders a `<div>` container that applies CSS class names for the active\n * variant and color scheme, and sets the root font-size as an inline style.\n * The corresponding CSS custom properties are defined in the SCSS variant\n * files under `typography/variants/`.\n *\n * Consumers can replace this with a custom {@link AIMarkdownTypographyComponent}\n * via the `Typography` prop on `<AIMarkdown>`.\n *\n * @module components/typography/Default\n */\n\nimport { memo, useMemo } from 'react';\nimport type { AIMarkdownTypographyProps } from '../../defs';\n\nconst DefaultTypography = memo(({ children, fontSize, variant, colorScheme, style }: AIMarkdownTypographyProps) => {\n const className = useMemo(\n () => ['aim-typography-root', variant, colorScheme].filter(Boolean).join(' '),\n [variant, colorScheme]\n );\n const mergedStyle = useMemo(() => ({ width: '100%' as const, fontSize, ...style }), [fontSize, style]);\n return (\n <div className={className} style={mergedStyle}>\n {children}\n </div>\n );\n});\n\nDefaultTypography.displayName = 'DefaultTypography';\n\nexport default DefaultTypography;\n","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n","import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n","import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n","import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n","import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n","import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n","import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n","import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n","import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n","import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n","import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n","import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n","import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\n","/**\n * Builds a `rehype-sanitize` schema by handing the caller a deep clone of the\n * library default ({@link sanitizeSchema}) to mutate or replace.\n *\n * The mutate-and-return pattern matches the ergonomics of Next.js's\n * `webpack(config)` and Express middleware: a callback receives a draft,\n * either modifies it in place (returning nothing) or returns a fresh object\n * to replace it. The library guarantees the draft is a deep clone, so direct\n * mutation never leaks into the shared default singleton.\n *\n * @module components/extendSanitizeSchema\n */\n\nimport cloneDeep from 'lodash-es/cloneDeep';\nimport type { defaultSchema } from 'rehype-sanitize';\nimport { sanitizeSchema } from './sanitizeSchema';\n\n/**\n * The full `rehype-sanitize` schema type. Re-exported as the canonical\n * library-internal alias so other modules don't each redeclare\n * `typeof defaultSchema`.\n *\n * The shape is owned by `rehype-sanitize`; consumers should treat it as\n * tracking that upstream type — it may evolve across rehype-sanitize major\n * versions.\n */\nexport type SanitizeSchema = typeof defaultSchema;\n\n/**\n * Build a sanitize schema by mutating (or replacing) a deep clone of the\n * library default.\n *\n * Designed to be called ONCE at module scope so the returned object has a\n * stable identity across renders — passing it directly into\n * `<AIMarkdown sanitizeSchema={…}>` keeps the block-memo cache warm.\n *\n * @example Append a custom URL protocol via mutation:\n * ```ts\n * const SCHEMA = extendSanitizeSchema((s) => {\n * s.protocols!.href!.push('myapp');\n * s.protocols!.src!.push('myapp');\n * });\n *\n * function App() {\n * return <AIMarkdown content={…} sanitizeSchema={SCHEMA} />;\n * }\n * ```\n *\n * @example Return-style replacement for wider edits:\n * ```ts\n * const SCHEMA = extendSanitizeSchema((s) => ({\n * ...s,\n * tagNames: [...(s.tagNames ?? []), 'my-widget'],\n * }));\n * ```\n *\n * @remarks Allowing a protocol on `protocols.href` lets the URL through the\n * SECOND sanitize gate. The FIRST gate (`urlTransform`) must permit the\n * same protocol independently — see the `urlTransform` prop on\n * `<AIMarkdown>` and the exported {@link defaultUrlTransform} for\n * composition. Keep the two protocol lists in sync.\n *\n * ### Footguns\n *\n * - **Reassigning the local parameter** (`(s) => { s = { …new schema… }; }`)\n * does NOT replace the draft — JS only rebinds the local variable. Either\n * mutate the original draft or `return` the new object explicitly.\n * - **Returning `null`** is treated the same as returning nothing (the\n * modified draft is used). The TypeScript signature does not permit\n * `null`, but JS callers or `as`-casted code paths could silently hit\n * this. Prefer `return` with no value, or an explicit `return draft;`.\n * - **Throwing inside the modifier** propagates to the call site\n * uncaught — there is no try/catch. Callers usually invoke this once at\n * module load, where a thrown error surfaces as a startup-time crash and\n * is the correct failure mode.\n *\n * @param modifier - Receives a deep clone of the library default. Mutate it\n * freely; either return the (possibly different) result, or return\n * nothing to use the mutated draft. Returning `undefined` (and, by\n * convention, `null`) is treated the same as a mutate-only call.\n * @returns A new `Schema` object — never the library default singleton.\n */\nexport function extendSanitizeSchema(\n modifier: (draft: SanitizeSchema) => SanitizeSchema | void\n): SanitizeSchema {\n // lodash-es `cloneDeep` over the native `structuredClone` because the\n // latter is unavailable on iOS Safari < 15.4 (March 2022) and on older\n // Android WebViews that are still common on mid-tier devices. lodash-es\n // is already pulled in transitively (useStableValue + context use it),\n // so the marginal bundle cost of importing one more named export is tiny;\n // the helper is called once at module scope, so the speed difference\n // versus the native API is irrelevant. Importantly, lodash `cloneDeep`\n // preserves RegExp — a JSON-based deep clone would silently turn the\n // math/language className regexes into `{}` and corrupt sanitize\n // semantics.\n const draft = cloneDeep(sanitizeSchema);\n const result = modifier(draft);\n return result ?? draft;\n}\n"],"mappings":";;;AAuBA,SAAS,WAAAA,UAAS,QAAAC,OAAM,SAAAC,cAAiC;;;ACbzD,SAA4B,eAAe,YAAY,OAAO,eAAe;;;ACH7E,SAAS,iBAAiB;AACxB,OAAK,WAAW,CAAC;AACjB,OAAK,OAAO;AACd;AAEA,IAAO,yBAAQ;;;ACoBf,SAAS,GAAG,OAAO,OAAO;AACxB,SAAO,UAAU,SAAU,UAAU,SAAS,UAAU;AAC1D;AAEA,IAAO,aAAQ;;;AC1Bf,SAAS,aAAa,OAAO,KAAK;AAChC,MAAI,SAAS,MAAM;AACnB,SAAO,UAAU;AACf,QAAI,WAAG,MAAM,MAAM,EAAE,CAAC,GAAG,GAAG,GAAG;AAC7B,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAO,uBAAQ;;;ACjBf,IAAI,aAAa,MAAM;AAGvB,IAAI,SAAS,WAAW;AAWxB,SAAS,gBAAgB,KAAK;AAC5B,MAAI,OAAO,KAAK,UACZ,QAAQ,qBAAa,MAAM,GAAG;AAElC,MAAI,QAAQ,GAAG;AACb,WAAO;AAAA,EACT;AACA,MAAI,YAAY,KAAK,SAAS;AAC9B,MAAI,SAAS,WAAW;AACtB,SAAK,IAAI;AAAA,EACX,OAAO;AACL,WAAO,KAAK,MAAM,OAAO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AAM,sBAAsB,eAAe,oBAAoB;AAC/D,QAAM,yBAAyB,eAAe,gBAAgB;AAO9D,QAAM,uBAAuB,eAAeA,eAAc;AAQ1D,QAAM,cAAcE;AAAA,IAClB,MAAO,UAAU,sBAAsB,SAAS,mBAAmB,IAAI;AAAA,IACvE,CAAC,SAAS,mBAAmB;AAAA,EAC/B;AAIA,QAAM,kBAAkBA,SAAQ,OAAO,EAAE,wBAAwB,aAAa,IAAqB,CAAC,YAAY,CAAC;AAEjH,SACE,gBAAAH,KAAC,8BAAwC,UACvC,0BAAAA;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,QAAQ;AAAA,MAER,0BAAAA;AAAA,QAAC;AAAA;AAAA,UACC,UAAU;AAAA,UACV;AAAA,UACA;AAAA,UAKA,OAAO;AAAA,UAEN,wBACC,gBAAAA,KAAC,eACC,0BAAAA;AAAA,YAAC;AAAA;AAAA,cACC,SAAS;AAAA,cACT,kBAAkB;AAAA,cAClB,cAAc,gBAAgB;AAAA,cAC9B,gBAAgB;AAAA;AAAA,UAClB,GACF,IAEA,gBAAAA;AAAA,YAAC;AAAA;AAAA,cACC,SAAS;AAAA,cACT,kBAAkB;AAAA,cAClB,cAAc,gBAAgB;AAAA,cAC9B,gBAAgB;AAAA;AAAA,UAClB;AAAA;AAAA,MAEJ;AAAA;AAAA,EACF,GACF;AAEJ;AAyBA,IAAM,aAAaI,MAAK,mBAAmB;AAC3C,WAAW,cAAc;AAEzB,IAAO,gBAAQ;","names":["useMemo","memo","useId","Symbol","objectProto","nativeObjectToString","symToStringTag","funcProto","objectProto","funcToString","hasOwnProperty","Map","objectProto","hasOwnProperty","objectProto","hasOwnProperty","HASH_UNDEFINED","objectProto","objectProto","hasOwnProperty","freeExports","freeModule","moduleExports","Buffer","funcProto","objectProto","funcToString","hasOwnProperty","argsTag","funcTag","objectTag","freeExports","freeModule","moduleExports","objectProto","hasOwnProperty","MAX_SAFE_INTEGER","objectProto","hasOwnProperty","objectProto","hasOwnProperty","AIMarkdownRenderExtraSyntax","AIMarkdownRenderDisplayOptimizeAbility","Fragment","memo","useCallback","useId","useMemo","useRef","useSyncExternalStore","unreachable","jsx","unreachable","processor","root","jsx","visit","visit","remarkGfm","visit","visit","unified","remarkParse","visit","unified","remarkParse","visit","createContext","useContext","useMemo","global","jsx","createContext","useContext","useMemo","useContext","createContext","jsx","useContext","visit","visit","SKIP","visit","visit","SKIP","useMemo","Fragment","jsx","isWhitespaceText","lastMeaningfulIdx","useMemo","jsx","jsxs","memo","useId","useCallback","useSyncExternalStore","useMemo","useRef","Fragment","remarkGfm","useRef","useEffect","HASH_UNDEFINED","othValue","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","boolTag","dateTag","errorTag","mapTag","numberTag","regexpTag","setTag","stringTag","arrayBufferTag","dataViewTag","objectProto","propertyIsEnumerable","objectProto","hasOwnProperty","COMPARE_PARTIAL_FLAG","objectProto","hasOwnProperty","Promise","Set","mapTag","objectTag","setTag","weakMapTag","dataViewTag","COMPARE_PARTIAL_FLAG","argsTag","arrayTag","objectTag","objectProto","hasOwnProperty","useEffect","useRef","useRef","memo","useMemo","jsx","nativeGetSymbols","objectProto","hasOwnProperty","symbolProto","symbolValueOf","boolTag","dateTag","mapTag","numberTag","regexpTag","setTag","stringTag","symbolTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","mapTag","setTag","argsTag","arrayTag","boolTag","dateTag","errorTag","funcTag","genTag","mapTag","numberTag","objectTag","regexpTag","setTag","stringTag","symbolTag","weakMapTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","key","CLONE_DEEP_FLAG","CLONE_SYMBOLS_FLAG","jsx","sanitizeSchema","useId","useMemo","memo"]}
|