{"version":3,"sources":["../src/index.tsx","../src/context.tsx","../src/resolveFlatProps.ts","../src/hooks/useReferenceFlipWarning.ts","../src/hooks/useStableValue.ts","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_listCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/eq.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_assocIndexOf.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_listCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_listCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_listCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_listCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_ListCache.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_stackClear.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_stackDelete.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_stackGet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_stackHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_freeGlobal.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_root.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Symbol.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getRawTag.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_objectToString.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseGetTag.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isObject.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isFunction.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_coreJsData.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_isMasked.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_toSource.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseIsNative.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getValue.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getNative.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Map.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_nativeCreate.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_hashClear.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_hashDelete.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_hashGet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_hashHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_hashSet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Hash.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapCacheClear.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_isKeyable.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getMapData.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapCacheDelete.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapCacheGet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapCacheSet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_MapCache.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_stackSet.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Stack.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_setCacheAdd.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_setCacheHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_SetCache.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_arraySome.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_cacheHas.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_equalArrays.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Uint8Array.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_mapToArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_setToArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_equalByTag.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_arrayPush.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseGetAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_arrayFilter.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/stubArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getSymbols.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseTimes.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isObjectLike.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseIsArguments.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isArguments.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/stubFalse.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isBuffer.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_isIndex.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isLength.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseIsTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseUnary.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_nodeUtil.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isTypedArray.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_arrayLikeKeys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_isPrototype.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_overArg.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_nativeKeys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseKeys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isArrayLike.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/keys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getAllKeys.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_equalObjects.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_DataView.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Promise.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_Set.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_WeakMap.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_getTag.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseIsEqualDeep.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/_baseIsEqual.js","../../../node_modules/.pnpm/lodash-es@4.18.1/node_modules/lodash-es/isEqual.js","../src/components/MarkdownContent.tsx","../src/components/markdown/Markdown.tsx","../../runtime/src/blockPlan.ts","../../runtime/src/blockPlanner.ts","../../runtime/src/contribution.ts","../../runtime/src/smoothCoordinator.ts","../../runtime/src/tailSignal.ts","../../runtime/src/aggregateFootnotes.ts","../../runtime/src/cloneHastForRender.ts","../../runtime/src/pipelineSession.ts","../../runtime/src/coordinationPreparation.ts","../src/components/markdown/index.ts","../src/components/blockMemo.ts","../src/components/provenance.ts","../src/components/AIMarkdownDocuments.tsx","../src/components/documentScopeCache.ts","../src/components/smoothStream/coordinator.ts","../src/components/crossChunkPlaceholders.tsx","../src/components/chunkSymbolContext.ts","../src/components/crossChunkUrlContext.ts","../src/components/aggregateFootnotesIfLast.tsx","../src/components/useRegistryContribution.ts","../src/hooks/useStableRecord.ts","../src/components/typography/Default.tsx","../src/components/smoothStream/useDocumentSmoothStream.ts","../src/components/smoothStream/useSmoothStream.ts","../src/define.ts","../src/components/streamingCursor/index.tsx","../src/components/streamingCursor/detectAnchor.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, useState, memo, type ComponentType, type CSSProperties } from 'react';\nimport AIMarkdownProvider, { AIMarkdownMetadataProvider } from './context';\nimport { AIMDContentPreprocessor } from '@ai-react-markdown/engine';\nimport useStableValue from './hooks/useStableValue';\nimport { preprocessAIMDContent } from '@ai-react-markdown/engine';\nimport { createIncrementalLatexPreprocessor } from '@ai-react-markdown/engine';\nimport AIMarkdownContent from './components/MarkdownContent';\nimport {\n  AIMarkdownCustomComponents,\n  AIMarkdownMetadata,\n  AIMarkdownTypographyComponent,\n  AIMarkdownExtraStylesComponent,\n  AIMarkdownVariant,\n  AIMarkdownColorScheme,\n} from './defs';\nimport type { SanitizeSchema } from '@ai-react-markdown/engine';\nimport type { UrlTransform } from './components/markdown';\nimport useStableRecord, { AIMarkdownStabilityPolicy, type AIMarkdownStabilityTable } from './hooks/useStableRecord';\nimport { resolveEngineValues } from './resolveFlatProps';\nimport type { AIMarkdownEnginePlugin } from '@ai-react-markdown/engine';\nimport DefaultTypography from './components/typography/Default';\nimport { useDocumentSmoothStream } from './components/smoothStream/useDocumentSmoothStream';\nimport type { SmoothStreamPacing } from '@ai-react-markdown/engine';\n\n/**\n * Props for the `<AIMarkdown>` component.\n *\n * @typeParam TMetadata - Custom metadata type (extends {@link AIMarkdownMetadata}).\n */\nexport interface AIMarkdownProps<TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata> {\n  /**\n   * Arbitrary consumer data delivered to custom components through the\n   * metadata context (`useAIMarkdownMetadata`). Deliberately never\n   * stabilized by the library — see the firewall table (`PASS_THROUGH`).\n   */\n  metadata?: TMetadata;\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`. `null` (from untyped/serialized callers) counts as absent.\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'`. `null` (from\n   * untyped/serialized callers) and `''` count as absent.\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. The package ships an\n   * optional streaming tail-repair factory for this slot —\n   * {@link createRemendPreprocessor} (see docs/content-preprocessors.md).\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}; `null` counts as absent.\n   *\n   * `children` may be a Fragment (the rendered content plus the optional\n   * `streamingCursor` slot) — implementations must render `children`\n   * verbatim; `Children.only` / `cloneElement`-style handling will break.\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   * Same `children` contract as `Typography`: may be a Fragment; render it\n   * verbatim.\n   */\n  ExtraStyles?: AIMarkdownExtraStylesComponent;\n  /** Typography variant name. Defaults to `'default'`; `null` counts as absent. */\n  variant?: AIMarkdownVariant;\n  /** Color scheme name. Defaults to `'light'`; `null` counts as absent. */\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). `null` and the empty string `''` both\n   * count as omitted — they fall to the auto-generated id AND opt the\n   * instance out of cross-chunk coordination (an auto id never opens a\n   * registry), so `documentId={maybeEmpty}` silently renders standalone.\n   * Pass an explicit value when you need deterministic ids (snapshot\n   * tests, cross-component deep links) or when multiple instances render\n   * 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. Even ill-formed UTF-16 (an unpaired\n   * surrogate from a string truncated mid-emoji upstream) is accepted: such\n   * ids are hashed into the prefix, keeping distinct ids on distinct\n   * prefixes (up to the same 2^32 hash bound long ids always had).\n   * Dev builds log a warning when this happens, since\n   * the corruption usually indicates an upstream bug worth fixing.\n   */\n  documentId?: string;\n  /**\n   * This chunk's position in the DOCUMENT, when several `<AIMarkdown>`\n   * instances share a `documentId` inside `<AIMarkdownDocuments>`.\n   *\n   * Cross-chunk state (footnote numbering, which chunk renders the\n   * aggregate footer) follows the order chunks register in. Without this\n   * prop that is MOUNT order, which is correct as long as chunks mount once\n   * in document order — the common case, so the prop is optional and the\n   * default behaviour is unchanged.\n   *\n   * Pass it when chunks can mount out of order or remount: a **virtualized\n   * transcript** that unmounts messages scrolled out of view re-registers\n   * them at the end when they scroll back, which renumbers footnotes and\n   * moves the aggregate footer under whichever chunk registered last. Any\n   * stable per-chunk ordinal works (the message's index in your list).\n   *\n   * Ignored outside `<AIMarkdownDocuments>` (a standalone document is its\n   * own chunk 0).\n   */\n  documentIndex?: number;\n  /**\n   * Override the per-attribute URL rewriter (Gate 2 of the two-gate model).\n   * Runs at render time during the hast traversal in `renderHastSubtree`,\n   * after Gate 1 (`rehype-sanitize` schema) has already filtered URLs by\n   * protocol allowlist in the rehype plugin chain.\n   *\n   * The default allowlist mirrors `react-markdown` / GitHub: `http`,\n   * `https`, `irc`, `ircs`, `mailto`, `xmpp`. Anything else is rewritten\n   * 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 block-level 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 — Gate 1 (`rehype-sanitize` schema) also enforces its own\n   * protocol allowlist and runs first. See the `sanitizeSchema` prop on\n   * this component and the {@link extendSanitizeSchema} helper for Gate 1.\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 extends `rehype-sanitize`'s own `defaultSchema`\n   * with the `<mark>` tag, the `math-inline` / `math-display` className\n   * markers `remark-math` emits on `<code>` (KaTeX's own output classes\n   * survive separately because `rehype-katex` runs after `rehype-sanitize`),\n   * and the cross-chunk coordination tags (`cross-chunk-link`,\n   * `cross-chunk-image`, `footnote-sup`). The default is not exported as a\n   * value — see {@link extendSanitizeSchema} for how to inspect or extend\n   * it safely.\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.** An inline call\n   * (`sanitizeSchema={extendSanitizeSchema((s) => { … })}`) is mitigated by\n   * the stability firewall's `DEEP_EQUAL` policy (`useStableRecord` +\n   * `CORE_STABILITY_TABLE`: an equal-but-new object is replaced by the\n   * previous reference), but the safer pattern is still module-scope.\n   * Development builds will `console.warn` on repeated 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   * Streaming cursor slot. While `streaming === true`, the given component\n   * is rendered after the markdown content — inside the typography wrapper\n   * and both providers — and unmounted when `streaming` is `false` or the\n   * prop is omitted. No props are injected; the slot only controls WHEN and\n   * WHERE the component renders.\n   *\n   * Pass the exported {@link AIMarkdownStreamingCursor} for the built-in\n   * inline self-positioning cursor (optionally wrapped at module scope to\n   * bind a custom `indicator`):\n   *\n   * ```tsx\n   * import AIMarkdown, { AIMarkdownStreamingCursor } from '@ai-react-markdown/core';\n   *\n   * <AIMarkdown content={content} streaming={!done} streamingCursor={AIMarkdownStreamingCursor} />\n   * ```\n   *\n   * **Reference stability matters.** Like `Typography`, this is compared by\n   * identity in the memo wrapper — define the component at module scope, not\n   * inline.\n   */\n  streamingCursor?: ComponentType;\n  /**\n   * Sealed engine plugin selection (v2 input surface; Engine-plugins system).\n   * Accepts core-exported sealed plugins only — import them from\n   * `@ai-react-markdown/core/plugins`. Third-party content extension goes\n   * through `contentPreprocessors` + `customComponents`.\n   *\n   * - Absent → `defaultEnginePlugins` (all five, parity with the shipped\n   *   config defaults). Passing an array replaces the set wholesale\n   *   (array-atomic semantics).\n   * - Each plugin's position in the produced chain comes from canonical\n   *   per-stage tables keyed by name; the order of this array is\n   *   irrelevant. Duplicates are deduplicated with a dev warning.\n   * - Turn one off: `enginePlugins={defaultEnginePlugins.filter((p) => p !== pangu)}`.\n   *\n   * \"Explicit\" is `v != null` — passing `null` counts as absent (guards\n   * serialization boundaries materializing \"not passed\" as `null`).\n   */\n  enginePlugins?: readonly AIMarkdownEnginePlugin[];\n  /**\n   * Behaviors system: block-level memoization. Output-invariant in\n   * standalone rendering — flipping it changes no rendered byte (orphan\n   * protection included). When `true` (default), the renderer splits the\n   * document into per-block units and memoizes each block's subtree by\n   * source identity, so unchanged blocks skip render work during streaming.\n   * When `false`, the legacy bare flow runs the full pipeline every render.\n   * Cross-chunk coordination (`<AIMarkdownDocuments>`) is wired through the\n   * block-memo path only — with `false`, refs across chunks do not resolve.\n   *\n   * `null` counts as absent (falls to the default). @default true\n   */\n  blockMemo?: boolean;\n  /**\n   * Behaviors system: incremental (prefix-freeze) parsing for streaming\n   * content. Output-invariant (enforced by the splice-equivalence suites).\n   * When the content grows by appends, the engine freezes the verified\n   * prefix and re-parses only the tail; a per-frame gate chain silently\n   * falls back to the full parse whenever splicing is not provably safe.\n   * Effective only while `blockMemo` is `true`; SSR always full-parses.\n   *\n   * `null` counts as absent (falls to the default). @default true\n   */\n  incrementalParse?: boolean;\n  /**\n   * Behaviors system: protect orphan reference definitions (footnote/link\n   * defs with no matching reference yet) in incomplete/streaming documents.\n   * Affects output. Override chain: an `<AIMarkdownDocuments>` wrapper's\n   * same-named prop (omission ≡ explicit `true`) unconditionally wins for\n   * all chunks under it > this prop > the shipped default.\n   *\n   * `null` counts as absent (falls to the default). @default true\n   */\n  preserveOrphanReferences?: boolean;\n}\n\n/**\n * The record of object-valued props that crosses the stability firewall.\n * `metadata` is generic at the component level; the firewall treats it as\n * opaque (`PASS_THROUGH`), so the base type is used here.\n */\ninterface CoreStabilizedProps {\n  enginePlugins: readonly AIMarkdownEnginePlugin[] | undefined;\n  sanitizeSchema: SanitizeSchema | undefined;\n  customComponents: AIMarkdownCustomComponents | undefined;\n  contentPreprocessors: AIMDContentPreprocessor[] | undefined;\n  urlTransform: UrlTransform | null | undefined;\n  Typography: AIMarkdownTypographyComponent;\n  ExtraStyles: AIMarkdownExtraStylesComponent | undefined;\n  streamingCursor: ComponentType | undefined;\n  metadata: AIMarkdownMetadata | undefined;\n}\n\n/**\n * The stability firewall's policy table — the complete roster of\n * object-valued props (EXECUTION-PLAN §3.9). `Required<Record<…>>` makes a\n * missing row a compile error, so exemption (`PASS_THROUGH`) and omission\n * are distinguishable. Each prop is stabilized exactly once, here at its\n * terminus; below this wall internal code trusts reference equality\n * outright.\n */\nconst CORE_STABILITY_TABLE: AIMarkdownStabilityTable<CoreStabilizedProps> = {\n  // Elements are module singletons; per-element === short-circuits the deep compare.\n  enginePlugins: AIMarkdownStabilityPolicy.DEEP_EQUAL,\n  sanitizeSchema: AIMarkdownStabilityPolicy.DEEP_EQUAL,\n  customComponents: AIMarkdownStabilityPolicy.DEEP_EQUAL,\n  // Function array — deep-comparing closures is meaningless; contract requires stable refs.\n  contentPreprocessors: AIMarkdownStabilityPolicy.WARN_ONLY,\n  urlTransform: AIMarkdownStabilityPolicy.WARN_ONLY,\n  // Component values: carrier-tier enforcement unified here.\n  Typography: AIMarkdownStabilityPolicy.WARN_ONLY,\n  ExtraStyles: AIMarkdownStabilityPolicy.WARN_ONLY,\n  streamingCursor: AIMarkdownStabilityPolicy.WARN_ONLY,\n  // Deliberate exemption: opaque shape, potentially huge, unbounded\n  // comparison cost — stabilization is the consumer's responsibility.\n  metadata: AIMarkdownStabilityPolicy.PASS_THROUGH,\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 = <TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata>({\n  streaming,\n  content,\n  fontSize,\n  contentPreprocessors,\n  customComponents,\n  metadata,\n  Typography,\n  ExtraStyles,\n  variant,\n  colorScheme,\n  documentId,\n  documentIndex,\n  urlTransform,\n  sanitizeSchema,\n  streamingCursor,\n  enginePlugins,\n  blockMemo,\n  incrementalParse,\n  preserveOrphanReferences,\n}: AIMarkdownProps<TMetadata>) => {\n  // ── Library-wide explicitness guard (EXECUTION-PLAN §3.7) ──\n  // \"Explicit\" is `v != null` for EVERY prop, not just the engine slice:\n  // serialization boundaries (RSC, persistence) materialize \"not passed\" as\n  // `null`, and JS destructure defaults only cover `undefined`. `??` (not a\n  // destructure default) is therefore the only correct default site. The\n  // TS prop types still exclude `null` — this guard is runtime\n  // defense-in-depth for untyped/serialized callers.\n  const usedStreaming = streaming ?? false;\n  const usedVariant = variant ?? 'default';\n  const usedColorScheme = colorScheme ?? 'light';\n  // Normalize fontSize: number -> px string, null/undefined/'' -> default rem\n  // value. Branch on `== null` (not truthiness) so `fontSize={0}` resolves\n  // to `'0px'`; `''` is excluded by an explicit check because it is not a CSS\n  // length. It would reach the Typography root as an empty\n  // `--aim-font-size-root`, i.e. the guaranteed-invalid value, and every\n  // variable chained off it — core's `--aim-*` scale and the Mantine\n  // wrapper's `--mantine-*` overrides — would collapse to browser defaults.\n  const usedFontSize =\n    fontSize == null || fontSize === '' ? '0.9375rem' : typeof fontSize === 'number' ? `${fontSize}px` : fontSize;\n\n  // documentId is forwarded RAW (possibly undefined) to the render-state\n  // provider, which is the single point that resolves the useId() fallback\n  // and derives `documentIdExplicit`. Defaulting here too would (a) duplicate\n  // the fallback the provider already performs and (b) erase the \"consumer\n  // supplied an id?\" signal before it reaches `useDocumentRegistry` — an\n  // auto-generated id would then wrongly opt a standalone chunk into\n  // cross-chunk coordination when nested under `<AIMarkdownDocuments>`.\n\n  // ── Stability firewall (EXECUTION-PLAN §3.9) ──\n  // Single table-driven boundary for all object-valued props. Per-key policy\n  // lives in CORE_STABILITY_TABLE next to the roster type; the dev probes\n  // (flip-rate for WARN_ONLY keys, deep-equal-restore for DEEP_EQUAL keys)\n  // live inside the hook, replacing the old pre-stabilization\n  // useReferenceFlipWarning calls. `metadata` crosses as PASS_THROUGH — the\n  // deliberate exemption (opaque, potentially huge, unbounded comparison\n  // cost) is now a declared policy row instead of an absence.\n  // `?? undefined` collapses `null` from untyped callers to `undefined` so\n  // the record matches its declared types and downstream `??`/conditional\n  // sites see exactly one absent value. `urlTransform` rides through as-is —\n  // its public type admits `null` (same null≡absent semantics), and its\n  // single consumption site below already normalizes with `?? undefined`.\n  const stable = useStableRecord<CoreStabilizedProps>(\n    {\n      enginePlugins: enginePlugins ?? undefined,\n      sanitizeSchema: sanitizeSchema ?? undefined,\n      customComponents: customComponents ?? undefined,\n      contentPreprocessors: contentPreprocessors ?? undefined,\n      urlTransform,\n      Typography: Typography ?? DefaultTypography,\n      ExtraStyles: ExtraStyles ?? undefined,\n      streamingCursor: streamingCursor ?? undefined,\n      metadata: metadata ?? undefined,\n    },\n    CORE_STABILITY_TABLE\n  );\n  const { Typography: TypographySlot, ExtraStyles: ExtraStylesSlot, streamingCursor: StreamingCursor } = stable;\n\n  // Single-point resolution of the engine-consumed fields: explicit prop\n  // (`v != null`) over shipped default. Both the internal pipeline props and\n  // the behaviors-context payload derive from this one resolution.\n  const resolvedEngine = useMemo(\n    () =>\n      resolveEngineValues({\n        blockMemo,\n        incrementalParse,\n        preserveOrphanReferences,\n        enginePlugins: stable.enginePlugins,\n      }),\n    [blockMemo, incrementalParse, preserveOrphanReferences, stable.enginePlugins]\n  );\n\n  // Run the preprocessing pipeline (LaTeX normalization + user preprocessors).\n  // The LaTeX stage is a per-instance append-aware wrapper: byte-identical\n  // to the stateless preprocessLaTeX, but streaming appends re-process only\n  // the active tail instead of the whole document (relevant at per-frame\n  // reveal rates under smooth streaming). Identity-stable across renders,\n  // so the memo deps stay clean; same-source calls replay a cached output\n  // (StrictMode-safe), non-append content resets its state.\n  const [latexPreprocessor] = useState(() => createIncrementalLatexPreprocessor());\n  const usedContent = useMemo(\n    () => (content ? preprocessAIMDContent(content, stable.contentPreprocessors, latexPreprocessor) : content),\n    [content, stable.contentPreprocessors, latexPreprocessor]\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  // The streaming-cursor slot must be a DOM sibling of the rendered blocks\n  // (its shell finds the content root via `parentElement`), so it renders\n  // inside the same JSX parent as the content — the ExtraStyles wrapper when\n  // present, the typography root otherwise.\n  const contentBody = (\n    <>\n      <AIMarkdownContent\n        content={usedContent}\n        customComponents={stable.customComponents}\n        urlTransform={stable.urlTransform ?? undefined}\n        sanitizeSchema={stable.sanitizeSchema}\n        blockMemo={resolvedEngine.blockMemo}\n        incrementalParse={resolvedEngine.incrementalParse}\n        preserveOrphanReferences={resolvedEngine.preserveOrphanReferences}\n        enginePlugins={resolvedEngine.enginePlugins}\n        documentIndex={documentIndex}\n      />\n      {usedStreaming && StreamingCursor ? <StreamingCursor /> : null}\n    </>\n  );\n\n  return (\n    <AIMarkdownMetadataProvider<TMetadata> metadata={stable.metadata as TMetadata | undefined}>\n      <AIMarkdownProvider\n        streaming={usedStreaming}\n        fontSize={usedFontSize}\n        variant={usedVariant}\n        colorScheme={usedColorScheme}\n        documentId={documentId}\n        blockMemo={resolvedEngine.blockMemo}\n        incrementalParse={resolvedEngine.incrementalParse}\n        preserveOrphanReferences={resolvedEngine.preserveOrphanReferences}\n      >\n        <TypographySlot\n          fontSize={usedFontSize}\n          variant={usedVariant}\n          colorScheme={usedColorScheme}\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          {ExtraStylesSlot ? <ExtraStylesSlot>{contentBody}</ExtraStylesSlot> : contentBody}\n        </TypographySlot>\n      </AIMarkdownProvider>\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 * import { highlight, definitionList } from '@ai-react-markdown/core/plugins';\n *\n * <AIMarkdown\n *   content={markdownString}\n *   streaming={isStreaming}\n *   colorScheme=\"dark\"\n *   enginePlugins={[highlight, definitionList]}\n * />\n * ```\n */\nconst AIMarkdown = memo(AIMarkdownComponent);\nAIMarkdown.displayName = 'AIMarkdown';\n\nexport default AIMarkdown as typeof AIMarkdownComponent;\n\n// ── Smooth-stream shell ─────────────────────────────────────────────────────\n// Lives here (not in components/smoothStream/) because it renders\n// <AIMarkdown>: a separate module importing from this index would form an\n// import cycle. The controller/hook layers stay framework-free/React-only\n// respectively so the future engine split can lift them wholesale.\n\n/**\n * Props for {@link AIMarkdownSmoothStream}: the full `<AIMarkdown>`\n * surface plus `smooth*`-prefixed pacing knobs (prefixed so future base\n * props can never collide with the shell's additions).\n */\nexport interface AIMarkdownSmoothStreamProps<\n  TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata,\n> extends AIMarkdownProps<TMetadata> {\n  /**\n   * Pacing preset — the whole tuning surface at this level: `'smooth'`\n   * (extra buffer, almost never runs dry between server flushes),\n   * `'balanced'` (default: minimal lag that still bridges typical\n   * bursts), `'responsive'` (lowest lag, accepts occasional pauses).\n   * The reveal rate itself is adaptive — it tracks the source's measured\n   * arrival cadence — so there are no numeric speed props here; advanced\n   * numeric overrides live on `createSmoothStreamController`.\n   */\n  smoothPacing?: SmoothStreamPacing;\n  /**\n   * Fires when the post-stream drain completes (once per stream round);\n   * content replacement never fires it. Correctness is identity-insensitive\n   * (read through a latest-ref), but an inline closure still defeats this\n   * shell's `memo` — prefer a stable reference.\n   *\n   * Under document turn-taking, a gated chunk drains only after its turn:\n   * this can fire long after the source stream ended — and a regeneration\n   * that happened entirely while the chunk was still gated is invisible to\n   * the reveal, so the eventual drain DOES fire it (the finally-revealed\n   * message did complete).\n   */\n  onSmoothDrained?: () => void;\n  /**\n   * Default `true`. Inside `<AIMarkdownDocuments>`, chunks sharing a\n   * `documentId` take turns revealing (one typewriter, one cursor); see\n   * {@link useDocumentSmoothStream}. Set `false` to keep this chunk's\n   * reveal independent — it neither waits for predecessors nor blocks\n   * successors (the escape hatch for chunks inserted out of mount order,\n   * e.g. a regenerated middle message). Coordination also requires an\n   * explicit `documentId` prop; without one this flag is moot.\n   */\n  smoothCoordination?: boolean;\n  /** Reserve the document queue slot while awaiting input; clear on start\n   * or completion of an empty result. Does not display a streaming cursor. */\n  smoothWaiting?: boolean;\n}\n\n/**\n * `<AIMarkdown>` with built-in typewriter pacing: the incoming `content`\n * is revealed grapheme-by-grapheme at a backlog-adaptive rate, and the\n * revealed prefix is what actually renders. Because the prefix grows\n * append-only, every frame rides the incremental-parse fast path.\n *\n * `streaming` semantics shift one step: the value you pass marks the\n * SOURCE stream's liveness; the inner component (and so the cursor slot\n * and context consumers) sees `streaming === true` until the reveal has\n * also drained — the cursor must not unmount while pixels still move.\n *\n * Footgun: `blockMemo={false}` also disables incremental parsing, which\n * turns per-frame reveals into per-frame full reparses. Leave block-memo\n * on (the default) when smoothing.\n *\n * For custom composition (mantine wrapper, skip-animation buttons), use\n * {@link useDocumentSmoothStream} (coordinated) or {@link useSmoothStream}\n * (standalone) directly — either result spreads into any wrapper.\n *\n * @example\n * ```tsx\n * <AIMarkdownSmoothStream\n *   content={accumulated}\n *   streaming={!done}\n *   streamingCursor={AIMarkdownStreamingCursor}\n * />\n * ```\n */\nconst AIMarkdownSmoothStreamComponent = <TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata>({\n  smoothPacing,\n  onSmoothDrained,\n  smoothCoordination,\n  smoothWaiting,\n  content,\n  streaming,\n  ...rest\n}: AIMarkdownSmoothStreamProps<TMetadata>) => {\n  // §3.7: `??` is the only correct default site — a destructuring default\n  // leaves an explicit `null` (RSC / serialization boundaries materialize\n  // \"not passed\" as null) in place, and `null ? … : …` then silently turned\n  // coordination OFF, the opposite of the documented default (2026-08\n  // project review, core-api-01).\n  const coordinate = smoothCoordination ?? true;\n  const smooth = useDocumentSmoothStream({\n    // The same documentId the inner <AIMarkdown> receives below — the only\n    // public supply path for the id, so shell auto-wiring cannot drift.\n    // Withholding it (opt-out, or no id at all) degrades the hook to plain\n    // useSmoothStream behavior.\n    documentId: coordinate ? rest.documentId : undefined,\n    content,\n    streaming,\n    pacing: smoothPacing,\n    onDrained: onSmoothDrained,\n    waiting: smoothWaiting,\n  });\n  return <AIMarkdown {...rest} content={smooth.content} streaming={smooth.streaming} />;\n};\n\nconst AIMarkdownSmoothStreamMemo = memo(AIMarkdownSmoothStreamComponent);\nAIMarkdownSmoothStreamMemo.displayName = 'AIMarkdownSmoothStream';\nexport const AIMarkdownSmoothStream = AIMarkdownSmoothStreamMemo as typeof AIMarkdownSmoothStreamComponent;\n\n// ── Public API re-exports ───────────────────────────────────────────────────\n\n// Types\nexport type { AIMDContentPreprocessor };\nexport type { RemendPreprocessorOptions } from '@ai-react-markdown/engine';\nexport type {\n  AIMarkdownCustomComponents,\n  AIMarkdownMetadata,\n  AIMarkdownTypographyProps,\n  AIMarkdownTypographyComponent,\n  AIMarkdownExtraStylesProps,\n  AIMarkdownExtraStylesComponent,\n  AIMarkdownVariant,\n  AIMarkdownColorScheme,\n} from './defs';\n\n// Hooks -- for custom components to access metadata\nexport { useAIMarkdownMetadata } from './context';\nexport { useStableValue };\n\n// ── v2 output surface (EXECUTION-PLAN props-api v2) ─────────────────────────\n\n// Five narrow hooks + the aggregate. `useAIMarkdownMetadata` (above) is the\n// fifth narrow hook — it predates v2 and keeps its generic.\nexport {\n  useAIMarkdownDocument,\n  useAIMarkdownTheme,\n  useAIMarkdownState,\n  useAIMarkdownBehaviors,\n  useAIMarkdown,\n} from './context';\n\n// Additive (stackable) Providers — extension-group transport for wrappers\n// and applications. Stack OUTSIDE <AIMarkdown>; see each Provider's JSDoc.\nexport { AIMarkdownBehaviorsProvider, AIMarkdownStateProvider } from './context';\nexport type {\n  AIMarkdownDocumentInfo,\n  AIMarkdownThemeInfo,\n  AIMarkdownStateCore,\n  AIMarkdownBehaviorsCore,\n  AIMarkdownStateGroups,\n  AIMarkdownBehaviorGroups,\n  AIMarkdownExtensionGroups,\n  AIMarkdownAggregate,\n} from './context';\n\n// ── v2 input surface (EXECUTION-PLAN props-api v2) ──────────────────────────\n\n// Sealed engine plugin type. The plugin VALUES live in the\n// `@ai-react-markdown/core/plugins` subpath (see `enginePlugins` prop JSDoc);\n// only the type travels through the root entry.\nexport type { AIMarkdownEnginePlugin, AIMarkdownEnginePluginName } from '@ai-react-markdown/engine';\n\n// `define*` factories — frozen, typed, reference-stable flat prop fragments.\nexport { defineTheme, defineBehaviors, definePipeline } from './define';\nexport type { AIMarkdownThemeProps, AIMarkdownBehaviorProps, AIMarkdownPipelineProps } from './define';\n\n// Stability firewall — exported for wrapper reuse: a wrapper builds a table\n// only for object props it terminates (e.g. mantine's `codeBlock`);\n// forwarded props ride core's firewall untouched.\nexport { AIMarkdownStabilityPolicy, default as useStableRecord } from './hooks/useStableRecord';\nexport type { AIMarkdownStabilityTable } from './hooks/useStableRecord';\n\n// Content preprocessors — opt-in factories for the `contentPreprocessors`\n// prop. Tree-shakeable: `remend` only enters a consumer bundle when this\n// factory is imported.\nexport { createRemendPreprocessor } from '@ai-react-markdown/engine';\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 the ONLY supported way to build a custom sanitize schema — it hands the\n// caller a deep clone of the library default (which itself includes invariants\n// like the cross-chunk tag allowlist and KaTeX className allowlist), so direct\n// mutation is safe and the invariants are preserved automatically. The library\n// default schema is intentionally NOT exported as a value to prevent the\n// classic shallow-spread footgun (`{ ...sanitizeSchema }` aliases nested\n// arrays). Consumers who want to read default values can invoke the helper\n// with a logging modifier — see `extendSanitizeSchema`'s JSDoc for the\n// recipe. Only the `SanitizeSchema` type is exported, for callers building\n// typed helpers around the prop.\nexport { defaultUrlTransform } from './components/markdown';\nexport type { UrlTransform } from './components/markdown';\nexport { extendSanitizeSchema } from '@ai-react-markdown/engine';\nexport type { SanitizeSchema } from '@ai-react-markdown/engine';\n\n// Streaming cursor — positioner shell for the `streamingCursor` slot, plus\n// the indicator contract for custom visuals.\nexport { AIMarkdownStreamingCursor } from './components/streamingCursor';\nexport type {\n  AIMarkdownStreamingCursorProps,\n  AIMarkdownStreamingIndicatorProps,\n  AIMarkdownStreamingIndicatorComponent,\n} from './components/streamingCursor';\n\n// Smooth streaming — the shell component is defined above; these are the\n// composable layers beneath it (framework-free controller + React hook).\nexport { createSmoothStreamController, SMOOTH_STREAM_PACING_PRESETS } from '@ai-react-markdown/engine';\nexport type {\n  SmoothStreamController,\n  SmoothStreamOptions,\n  SmoothStreamPacing,\n  SmoothStreamPacingParams,\n} from '@ai-react-markdown/engine';\nexport { useSmoothStream } from './components/smoothStream/useSmoothStream';\nexport type { UseSmoothStreamOptions, UseSmoothStreamResult } from './components/smoothStream/useSmoothStream';\nexport { useDocumentSmoothStream } from './components/smoothStream/useDocumentSmoothStream';\nexport type { UseDocumentSmoothStreamOptions } from './components/smoothStream/useDocumentSmoothStream';\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 '@ai-react-markdown/engine';\n","/**\n * The AIMarkdown context layer: five per-system contexts (document, metadata,\n * state, theme, behaviors), five narrow hooks, the aggregate hook, and the\n * two additive Providers. `AIMarkdownProvider` receives already-resolved\n * values from `<AIMarkdown>` — resolution happens exactly once, in the\n * component (see `resolveFlatProps.ts`).\n *\n * @module context\n */\n\nimport { PropsWithChildren, createContext, useContext, useId, useMemo, useRef, type Context, type FC } from 'react';\nimport { AIMarkdownMetadata, AIMarkdownVariant, AIMarkdownColorScheme } from './defs';\nimport { hasLoneSurrogate, shortenDocumentId } from '@ai-react-markdown/engine';\nimport { SHIPPED_BEHAVIOR_DEFAULTS } from './resolveFlatProps';\nimport useReferenceFlipWarning from './hooks/useReferenceFlipWarning';\n\nconst AIMarkdownMetadataContext = createContext<AIMarkdownMetadata | undefined>(undefined);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The context layer (EXECUTION-PLAN §3.4): five contexts, five narrow\n// hooks, one aggregate hook, two additive Providers.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Module-scope dev flag — resolved at build time (see `useReferenceFlipWarning`'s docblock). */\nconst __DEV__ = process.env.NODE_ENV !== 'production';\n\n/** Payload of the document context — entirely derived invariants (closed to extension). */\nexport interface AIMarkdownDocumentInfo {\n  /** Resolved logical-document id (consumer-supplied or `useId()` fallback). */\n  documentId: string;\n  /** Whether `documentId` was explicitly supplied — the cross-chunk coordination signal. */\n  documentIdExplicit: boolean;\n  /** Canonical URI-safe id prefix for clobberable attributes; never reconstruct locally. */\n  clobberPrefix: string;\n}\n\n/** Payload of the theme context (value tier of the Theme system). */\nexport interface AIMarkdownThemeInfo {\n  /** Resolved CSS font-size value (number props already normalized to `px`). */\n  fontSize: string;\n  variant: AIMarkdownVariant;\n  colorScheme: AIMarkdownColorScheme;\n}\n\n/** Core (locked) keys of the state context. */\nexport interface AIMarkdownStateCore {\n  streaming: boolean;\n}\n\n/** Core (locked) keys of the behaviors context — the three engine switches. */\nexport interface AIMarkdownBehaviorsCore {\n  /** Output-invariant engine strategy: block-level memoization. */\n  blockMemo: boolean;\n  /** Output-invariant engine strategy: incremental (prefix-freeze) parsing. */\n  incrementalParse: boolean;\n  /** Orphan-reference policy for incomplete/streaming documents (affects output). */\n  preserveOrphanReferences: boolean;\n}\n\n/**\n * Extension groups accepted by {@link AIMarkdownStateProvider}. Core keys are\n * type-forbidden (`never`) — they are owned by `<AIMarkdown>`'s resolution\n * and would be overwritten at the innermost merge anyway.\n *\n * **Frequency contract**: group members must change at message-lifecycle\n * frequency (aborted, reasoning, tool-call-in-progress, …). Frame-rate data\n * (per-token progress etc.) goes through metadata's stable-container\n * pattern instead — one context, every subscriber re-renders per change.\n */\nexport type AIMarkdownStateGroups = { [group: string]: object } & { streaming?: never };\n\n/**\n * Extension groups accepted by {@link AIMarkdownBehaviorsProvider} —\n * wrapper component-behavior parameter groups (e.g. mantine's `codeBlock`).\n * Core keys are type-forbidden (`never`).\n */\nexport type AIMarkdownBehaviorGroups = { [group: string]: object } & {\n  blockMemo?: never;\n  incrementalParse?: never;\n  preserveOrphanReferences?: never;\n};\n\n/**\n * Opaque extension-group record seen by consumers. Values are typed\n * `object | undefined` so a mistyped group key does not type as present;\n * wrapper narrow hooks perform the single type assertion.\n */\nexport type AIMarkdownExtensionGroups = Record<string, object | undefined>;\n\n/**\n * Internal additive-context factory shared by the state and behaviors\n * cells (the factory itself is NOT exported — only the two named Providers\n * are public API).\n *\n * Transport model: a wrapper or application stacks its groups *outside*\n * `<AIMarkdown>` via the public `Provider`; core's innermost `CoreProvider`\n * reads the outer same-named context and provides\n * `{ ...outer, ...coreResolved }` downward, so consumers see exactly one\n * context. Multi-level wrappers stack naturally — the public Provider also\n * merges its own outer context, and for a duplicated group key the inner\n * layer wins.\n *\n * Three locks keep outer layers off the core keys (otherwise hook reads\n * would diverge from actual behavior):\n * 1. Type level — the group types forbid core keys with `never`.\n * 2. Runtime — `CoreProvider` spreads the core-resolved values LAST, so\n *    they unconditionally overwrite anything an outer layer carried.\n * 3. Dev — the public Provider warns when its value carries a core key.\n *\n * Known cost (accepted): within one context, group invalidation is not\n * isolated — one group change leaf-re-renders all subscribers of that\n * context. A party needing isolation may run a private context instead.\n */\nfunction createAdditiveContext<TCore extends object, TGroups extends object>(\n  coreKeys: readonly string[],\n  providerName: string\n): {\n  Ctx: Context<(TCore & AIMarkdownExtensionGroups) | null>;\n  Provider: FC<PropsWithChildren<{ value: TGroups }>>;\n  CoreProvider: FC<PropsWithChildren<{ coreValue: TCore }>>;\n} {\n  const Ctx = createContext<(TCore & AIMarkdownExtensionGroups) | null>(null);\n\n  const Provider: FC<PropsWithChildren<{ value: TGroups }>> = ({ value, children }) => {\n    const outer = useContext(Ctx);\n    // Dev flip-rate probe (WARN_ONLY tier of the firewall, applied to the\n    // one object input that does not pass through `useStableRecord`): an\n    // inline `value` re-minted every parent render re-mints the merged\n    // context value and wakes EVERY subscriber of this context on every\n    // unrelated re-render — the exact storm the prop-side firewall guards\n    // against.\n    useReferenceFlipWarning(value, `${providerName} value`);\n    // Warn once per provider instance — core-key misuse is a static coding\n    // error, not a per-render condition worth spamming about. State lives as\n    // a property of a lazily-initialized ref object (same discipline as\n    // `useReferenceFlipWarning`'s FlipState).\n    const warnStateRef = useRef<{ warned: boolean } | null>(null);\n    const warnState = (warnStateRef.current ??= { warned: false });\n    if (__DEV__ && !warnState.warned) {\n      for (const key of coreKeys) {\n        if (key in (value as Record<string, unknown>)) {\n          warnState.warned = true;\n          console.warn(\n            `[AIMarkdown] <${providerName}> received the core key \\`${key}\\` in its value. ` +\n              `Core keys are resolved by <AIMarkdown> itself and unconditionally overwrite ` +\n              `outer values — remove the key from the provider value.`\n          );\n        }\n      }\n    }\n    const merged = useMemo(\n      () => Object.freeze({ ...outer, ...value }) as TCore & AIMarkdownExtensionGroups,\n      [outer, value]\n    );\n    return <Ctx.Provider value={merged}>{children}</Ctx.Provider>;\n  };\n  Provider.displayName = providerName;\n\n  /**\n   * Internal innermost provider rendered by `AIMarkdownProvider`.\n   * Merge is memoized on `[outer, coreValue]` so the context value keeps a\n   * stable identity across unrelated re-renders; core values spread LAST\n   * (runtime lock #2).\n   */\n  const CoreProvider: FC<PropsWithChildren<{ coreValue: TCore }>> = ({ coreValue, children }) => {\n    const outer = useContext(Ctx);\n    const merged = useMemo(\n      () => Object.freeze({ ...outer, ...coreValue }) as TCore & AIMarkdownExtensionGroups,\n      [outer, coreValue]\n    );\n    return <Ctx.Provider value={merged}>{children}</Ctx.Provider>;\n  };\n  CoreProvider.displayName = `${providerName}.Core`;\n\n  return { Ctx, Provider, CoreProvider };\n}\n\nconst documentCell = createContext<AIMarkdownDocumentInfo | null>(null);\nconst themeCell = createContext<AIMarkdownThemeInfo | null>(null);\nconst stateCell = createAdditiveContext<AIMarkdownStateCore, AIMarkdownStateGroups>(\n  ['streaming'],\n  'AIMarkdownStateProvider'\n);\nconst behaviorsCell = createAdditiveContext<AIMarkdownBehaviorsCore, AIMarkdownBehaviorGroups>(\n  ['blockMemo', 'incrementalParse', 'preserveOrphanReferences'],\n  'AIMarkdownBehaviorsProvider'\n);\n\n/**\n * Additive (stackable) Provider for state extension groups. Stack it\n * *outside* `<AIMarkdown>`; the value should be firewall output (or any\n * reference-stable record) used directly:\n *\n * ```tsx\n * <AIMarkdownStateProvider value={lifecycleGroups}>\n *   <AIMarkdown … />\n * </AIMarkdownStateProvider>\n * ```\n *\n * Group members obey the message-lifecycle frequency contract — see\n * {@link AIMarkdownStateGroups}. `streaming` is core-locked.\n */\nexport const AIMarkdownStateProvider = stateCell.Provider;\n\n/**\n * Additive (stackable) Provider for behavior extension groups (wrapper\n * component parameters, e.g. mantine's `codeBlock`). Stack it *outside*\n * `<AIMarkdown>`. The three core switches are core-locked; group defaults\n * are applied inside the wrapper's narrow hook, never at read sites.\n */\nexport const AIMarkdownBehaviorsProvider = behaviorsCell.Provider;\n\n/** Shared throw-guard for narrow hooks. */\nfunction requireContext<T>(value: T | null, hookName: string): T {\n  if (value == null) {\n    throw new Error(`${hookName} must be used within an <AIMarkdown /> component.`);\n  }\n  return value;\n}\n\n/**\n * Throw-guard for the ADDITIVE contexts: a stacked public Provider outside\n * `<AIMarkdown>` makes the context value non-null without the core keys\n * (only `CoreProvider` supplies them), so presence of a core key — not\n * non-nullness — is the \"under <AIMarkdown>\" signal. Without this check the\n * hook would silently return `undefined` for fields its type declares as\n * present.\n */\nfunction requireCoreContext<T extends object>(value: T | null, coreKey: string, hookName: string): T {\n  if (value == null || !(coreKey in value)) {\n    throw new Error(`${hookName} must be used within an <AIMarkdown /> component.`);\n  }\n  return value;\n}\n\n/**\n * Document-system narrow hook: resolved `documentId`, the\n * `documentIdExplicit` coordination signal, and the canonical\n * `clobberPrefix`. Payload is derived invariants — this context is closed\n * to extension (a forgeable `clobberPrefix` would break the anchor system).\n *\n * @throws When called outside an `<AIMarkdown>` tree.\n */\nexport function useAIMarkdownDocument(): AIMarkdownDocumentInfo {\n  return requireContext(useContext(documentCell), 'useAIMarkdownDocument');\n}\n\n/**\n * Theme-system narrow hook: `fontSize`, `variant`, `colorScheme`.\n * @throws When called outside an `<AIMarkdown>` tree.\n */\nexport function useAIMarkdownTheme(): AIMarkdownThemeInfo {\n  return requireContext(useContext(themeCell), 'useAIMarkdownTheme');\n}\n\n/**\n * State-system narrow hook. `streaming` is the most frequently flipping\n * field in the library — this hook's subscribers are the ONLY components\n * that re-render on a flip.\n * Extension state groups contributed via {@link AIMarkdownStateProvider}\n * appear as additional keys, typed `object | undefined`.\n *\n * @throws When called outside an `<AIMarkdown>` tree — a stacked additive\n *   Provider alone does not satisfy the guard (core keys come only from\n *   `<AIMarkdown>`'s internal provider).\n */\nexport function useAIMarkdownState(): AIMarkdownStateCore & AIMarkdownExtensionGroups {\n  return requireCoreContext(useContext(stateCell.Ctx), 'streaming', 'useAIMarkdownState');\n}\n\n/**\n * Behaviors-system narrow hook: the three core engine switches plus an\n * opaque extension record. Non-generic by design — the caller-asserted\n * `TConfig` generic is retired; wrapper narrow hooks (e.g.\n * `useMantineCodeBlockOptions()`) perform the single type assertion and\n * apply group defaults inside.\n *\n * @throws When called outside an `<AIMarkdown>` tree — a stacked additive\n *   Provider alone does not satisfy the guard (core keys come only from\n *   `<AIMarkdown>`'s internal provider).\n */\nexport function useAIMarkdownBehaviors(): AIMarkdownBehaviorsCore & AIMarkdownExtensionGroups {\n  return requireCoreContext(useContext(behaviorsCell.Ctx), 'blockMemo', 'useAIMarkdownBehaviors');\n}\n\n/** Aggregate payload returned by {@link useAIMarkdown}. */\nexport interface AIMarkdownAggregate<TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata> {\n  document: AIMarkdownDocumentInfo;\n  metadata: TMetadata | undefined;\n  state: AIMarkdownStateCore & AIMarkdownExtensionGroups;\n  theme: AIMarkdownThemeInfo;\n  behaviors: AIMarkdownBehaviorsCore & AIMarkdownExtensionGroups;\n}\n\n/**\n * Aggregate hook over all five systems:\n *\n * ```ts\n * const { document, metadata, state, theme, behaviors } = useAIMarkdown();\n * ```\n *\n * **Price**: subscribes to all five contexts and re-renders on ANY change\n * (including every `streaming` flip). Performance-sensitive components\n * should use the narrow hooks; the aggregate serves teaching and\n * low-frequency components.\n */\nexport function useAIMarkdown<\n  TMetadata extends AIMarkdownMetadata = AIMarkdownMetadata,\n>(): AIMarkdownAggregate<TMetadata> {\n  const document = useAIMarkdownDocument();\n  const metadata = useAIMarkdownMetadata<TMetadata>();\n  const state = useAIMarkdownState();\n  const theme = useAIMarkdownTheme();\n  const behaviors = useAIMarkdownBehaviors();\n  return useMemo(\n    () => ({ document, metadata, state, theme, behaviors }),\n    [document, metadata, state, theme, behaviors]\n  );\n}\n\n/**\n * Access the current metadata from within the `<AIMarkdown>` tree.\n *\n * Metadata lives in its own React context so that changes to metadata do\n * not cause re-renders in components that only consume the other systems\n * (e.g. the internal `MarkdownContent` renderer).\n *\n * ### `TMetadata` is a caller-asserted type\n *\n * The generic is an assertion about the `metadata` prop passed to the\n * provider above, not a value TypeScript can derive. 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 AIMarkdownProvider}. All values arrive already resolved. */\nexport interface AIMarkdownProviderProps 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 in-repo consumers (stories / test harnesses that\n   * don't go 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  /** Resolved behaviors switch; defaults to the shipped default for direct-provider consumers. */\n  blockMemo?: boolean;\n  /** Resolved behaviors switch; defaults to the shipped default for direct-provider consumers. */\n  incrementalParse?: boolean;\n  /** Resolved behaviors switch; defaults to the shipped default for direct-provider consumers. */\n  preserveOrphanReferences?: boolean;\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 * 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 feeds the five per-system contexts from the\n * already-resolved values `<AIMarkdown>` passes in (single resolution\n * point). NOT part of the public export surface (the openness table keeps\n * the document system closed) — direct composition is an in-repo\n * convenience for stories and test harnesses; the behaviors switches then\n * default to the shipped defaults.\n */\nconst AIMarkdownProvider = ({\n  streaming,\n  fontSize,\n  variant,\n  colorScheme,\n  documentId,\n  blockMemo = SHIPPED_BEHAVIOR_DEFAULTS.blockMemo,\n  incrementalParse = SHIPPED_BEHAVIOR_DEFAULTS.incrementalParse,\n  preserveOrphanReferences = SHIPPED_BEHAVIOR_DEFAULTS.preserveOrphanReferences,\n  children,\n}: AIMarkdownProviderProps) => {\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  //\n  // This provider is the SINGLE descent point for documentId resolution:\n  // `<AIMarkdown>` forwards the raw (possibly undefined) prop straight here\n  // rather than pre-defaulting it, so the \"did the consumer supply an id?\"\n  // signal survives all the way to where it's consumed. Any deeper consumer\n  // that composes this provider directly (in-repo stories / test harnesses\n  // that bypass `<AIMarkdown>`) therefore gets identical resolution + the\n  // correct `documentIdExplicit` for free.\n  const fallbackId = useId();\n  const documentIdExplicit = !!(documentId && documentId.length > 0);\n  const resolvedDocumentId = documentIdExplicit ? documentId! : fallbackId;\n\n  // Dev probe (issue #32): an unpaired surrogate in a consumer-supplied\n  // documentId almost always means an upstream pipeline truncated a string\n  // mid-surrogate-pair (e.g. `.slice()` through an emoji). The derivation\n  // below survives it — `shortenDocumentId` reroutes ill-formed ids to the\n  // hash path — but the corruption is a real upstream bug worth surfacing.\n  // `hasLoneSurrogate` is the engine's own branch predicate, so detection\n  // here can never drift from what `shortenDocumentId` actually does.\n  // Gated on `documentIdExplicit`: the `useId()` fallback cannot contain\n  // surrogates, so only consumer-supplied ids are ever tested.\n  // Warn-once-per-ID: `warnedFor` tracks the last id warned about, so a\n  // reused provider that swaps to a DIFFERENT corrupted id warns again\n  // (a plain boolean latch would silently skip every id after the first).\n  // State lives in a lazily-initialized ref, same discipline as the\n  // core-key misuse warning above.\n  const surrogateWarnRef = useRef<{ warnedFor: string | null } | null>(null);\n  const surrogateWarn = (surrogateWarnRef.current ??= { warnedFor: null });\n  if (\n    __DEV__ &&\n    documentIdExplicit &&\n    surrogateWarn.warnedFor !== resolvedDocumentId &&\n    hasLoneSurrogate(resolvedDocumentId)\n  ) {\n    surrogateWarn.warnedFor = resolvedDocumentId;\n    console.warn(\n      `[AIMarkdown] documentId contains an unpaired UTF-16 surrogate — usually a string ` +\n        `truncated mid-emoji upstream. The id still works (ill-formed ids are hashed into ` +\n        `the prefix, distinctness preserved), but fix the id at its source: the corruption ` +\n        `likely affects more than this prop.`\n    );\n  }\n\n  // URI-fragment safe per-document prefix derived ONCE here so downstream\n  // consumers (MarkdownContent, cross-chunk placeholder components, and the\n  // document context) read from one canonical source.\n  // `encodeURIComponent` runs at the prefix construction site, not at the\n  // documentId storage site, so consumers accessing `documentId` directly\n  // still see the raw React-native value (e.g. `useId()`'s `_r_0_`) while\n  // 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 the raw `documentId` — 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  // Memoized: the Provider re-renders on every streamed frame, and this\n  // is a pure function of the id (shortenDocumentId + encodeURIComponent\n  // per frame was the one un-memoized derivation in this file).\n  const clobberPrefix = useMemo(\n    () => `${encodeURIComponent(shortenDocumentId(resolvedDocumentId))}-user-content-`,\n    [resolvedDocumentId]\n  );\n\n  const documentInfo = useMemo<AIMarkdownDocumentInfo>(\n    () => Object.freeze({ documentId: resolvedDocumentId, documentIdExplicit, clobberPrefix }),\n    [resolvedDocumentId, documentIdExplicit, clobberPrefix]\n  );\n  const themeInfo = useMemo<AIMarkdownThemeInfo>(\n    () => Object.freeze({ fontSize, variant, colorScheme }),\n    [fontSize, variant, colorScheme]\n  );\n  const stateCore = useMemo<AIMarkdownStateCore>(() => Object.freeze({ streaming }), [streaming]);\n  const behaviorsCore = useMemo<AIMarkdownBehaviorsCore>(\n    () => Object.freeze({ blockMemo, incrementalParse, preserveOrphanReferences }),\n    [blockMemo, incrementalParse, preserveOrphanReferences]\n  );\n\n  return (\n    <documentCell.Provider value={documentInfo}>\n      <themeCell.Provider value={themeInfo}>\n        <stateCell.CoreProvider coreValue={stateCore}>\n          <behaviorsCell.CoreProvider coreValue={behaviorsCore}>{children}</behaviorsCell.CoreProvider>\n        </stateCell.CoreProvider>\n      </themeCell.Provider>\n    </documentCell.Provider>\n  );\n};\n\nexport default AIMarkdownProvider;\n","/**\n * Single-point resolver for the flat engine/behavior props (v2.0.0).\n *\n * Precedence has exactly two levels (EXECUTION-PLAN §3.7):\n *\n * > An explicitly passed prop overrides the shipped default; an absent prop\n * > falls to the shipped default. \"Explicit\" is defined library-wide as\n * > `v != null` — explicitly passing `null` counts as absent, guarding\n * > against serialization boundaries (RSC, persistence) materializing\n * > \"not passed\" as `null` and punching through defaults.\n *\n * Resolution happens exactly once, in `<AIMarkdown>`; both the internal\n * pipeline props and the context payloads derive from this single\n * resolution. Resolved values are handed to the pipeline as individual\n * props — never as a bag (no whole-object ever enters a deps array or\n * cache identity; see EXECUTION-PLAN §3.4).\n *\n * @module resolveFlatProps\n */\n\nimport { defaultEnginePlugins } from '@ai-react-markdown/engine';\nimport { getEnginePluginInternals, type AIMarkdownEnginePlugin } from '@ai-react-markdown/engine';\n\n/** Module-scope dev flag — resolved at build time (see `useReferenceFlipWarning`'s docblock). */\nconst __DEV__ = process.env.NODE_ENV !== 'production';\n\n/**\n * Shipped defaults of the three Behaviors switches — the SINGLE source of\n * truth, shared by {@link resolveEngineValues} and the direct-provider\n * destructure defaults in `context.tsx` (in-repo stories / test harnesses\n * composing `AIMarkdownProvider` without `<AIMarkdown>` must see the same\n * values).\n * @internal\n */\nexport const SHIPPED_BEHAVIOR_DEFAULTS = Object.freeze({\n  blockMemo: true,\n  incrementalParse: true,\n  preserveOrphanReferences: true,\n} as const);\n\n/** Flat props the resolver consumes. `null` is tolerated at runtime (≡ absent). */\nexport interface AIMarkdownFlatEngineProps {\n  blockMemo?: boolean | null;\n  incrementalParse?: boolean | null;\n  preserveOrphanReferences?: boolean | null;\n  enginePlugins?: readonly AIMarkdownEnginePlugin[] | null;\n}\n\n/** Fully resolved values for every engine-consumed field. */\nexport interface ResolvedEngineValues {\n  blockMemo: boolean;\n  incrementalParse: boolean;\n  preserveOrphanReferences: boolean;\n  /** Sanitized selection; absent prop → `defaultEnginePlugins` (all five). */\n  enginePlugins: readonly AIMarkdownEnginePlugin[];\n}\n\n/**\n * Validate a user-supplied plugin selection: duplicate members (by name)\n * are deduplicated and objects without sealed metadata (forged / foreign)\n * are dropped — dev builds warn in both cases. Returns the INPUT array\n * identity when nothing was removed, so downstream chain memos keyed on\n * the selection identity stay warm.\n *\n * Chain position never depends on this array's order — the canonical\n * per-stage tables in `pluginChain.ts` fix each plugin's splice position.\n */\nexport function sanitizeEnginePlugins(plugins: readonly AIMarkdownEnginePlugin[]): readonly AIMarkdownEnginePlugin[] {\n  let kept: AIMarkdownEnginePlugin[] | null = null;\n  const seen = new Set<string>();\n  for (let index = 0; index < plugins.length; index++) {\n    const plugin = plugins[index];\n    let drop = false;\n    if (getEnginePluginInternals(plugin) === null) {\n      drop = true;\n      if (__DEV__) {\n        console.warn(\n          `[AIMarkdown] \\`enginePlugins\\` received an object that is not a sealed engine plugin` +\n            `${plugin && typeof plugin === 'object' && 'name' in plugin ? ` (name: ${String(plugin.name)})` : ''}. ` +\n            `Only the core-exported plugins from '@ai-react-markdown/core/plugins' are accepted; ` +\n            `the entry was ignored. Third-party content extension goes through ` +\n            `\\`contentPreprocessors\\` and \\`customComponents\\`.`\n        );\n      }\n    } else if (seen.has(plugin.name)) {\n      drop = true;\n      if (__DEV__) {\n        console.warn(\n          `[AIMarkdown] \\`enginePlugins\\` contains duplicate entries for \"${plugin.name}\"; duplicates are ignored.`\n        );\n      }\n    } else {\n      seen.add(plugin.name);\n    }\n    if (drop) {\n      kept ??= plugins.slice(0, index) as AIMarkdownEnginePlugin[];\n    } else {\n      kept?.push(plugin);\n    }\n  }\n  return kept ?? plugins;\n}\n\n/**\n * Resolve the flat props against the shipped defaults. The three boolean\n * defaults here ARE the shipped defaults of the Behaviors system — note\n * the v2.0.0 absence-semantics flip: an absent `incrementalParse` now\n * means the shipped default (`true`), not the v1.x custom-`defaultConfig`\n * trap value (`false`).\n */\nexport function resolveEngineValues(flat: AIMarkdownFlatEngineProps): ResolvedEngineValues {\n  return {\n    blockMemo: flat.blockMemo ?? SHIPPED_BEHAVIOR_DEFAULTS.blockMemo,\n    incrementalParse: flat.incrementalParse ?? SHIPPED_BEHAVIOR_DEFAULTS.incrementalParse,\n    preserveOrphanReferences: flat.preserveOrphanReferences ?? SHIPPED_BEHAVIOR_DEFAULTS.preserveOrphanReferences,\n    enginePlugins: flat.enginePlugins != null ? sanitizeEnginePlugins(flat.enginePlugins) : defaultEnginePlugins,\n  };\n}\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 dual dev/prod build resolves `process.env.NODE_ENV` at build time\n * (tsup `env`), so `__DEV__` folds to a constant and the body's\n * `if (!__DEV__) return;` drops the rest. The single `useRef` allocation\n * remains (unconditional, by rules of hooks) but is harmless.\n *\n * History note: this module once gated on\n * `typeof process !== 'undefined' && process.env.NODE_ENV !== 'production'`,\n * which was silently FALSE in bundler browser dev — Vite substitutes only\n * the bare `process.env.NODE_ENV` text and leaves `typeof process`\n * evaluating `'undefined'` in the browser, so these warnings never fired\n * where they mattered most. Bare text everywhere + build-time resolution\n * is the fix; do not reintroduce `typeof process` guards.\n *\n * @module hooks/useReferenceFlipWarning\n */\n\nimport { useRef } from 'react';\n\n/** Module-scope dev flag — resolved at build time (see docblock). */\nconst __DEV__ = 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/** Flips further apart than this restart the count: three theme switches\n *  minutes apart are legitimate changes, not \"changing on every render\",\n *  and a lifetime counter warned on the third (2026-08 project review,\n *  core-api-06). */\nexport const FLIP_WINDOW_MS = 10_000;\n\n/** Internal state mutated by {@link trackFlip} across renders. */\nexport interface FlipState {\n  prev: unknown;\n  flips: number;\n  lastWarnAt: number;\n  /** Clock time of the previous flip; absent until the first one. */\n  lastFlipAt?: 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(state: FlipState, value: unknown, propName: string, now: number): void {\n  if (state.prev === value) return;\n  if (state.lastFlipAt !== undefined && now - state.lastFlipAt > FLIP_WINDOW_MS) state.flips = 0;\n  state.lastFlipAt = now;\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 * 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","/**\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","/** 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 {boolean} 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","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\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","/**\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","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","/**\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","/**\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 * 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","/** 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","/** 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 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","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","/** 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","/**\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 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 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 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 * 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 selectable extra syntax extensions\n * and display optimizations. Plugin selection is driven by the resolved\n * `enginePlugins` internal prop (sealed plugin objects).\n *\n * ## Render strategy\n *\n * Two render paths gated by the resolved `blockMemo` value (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` at its stability firewall. If you wire\n * `<AIMarkdownContent>` directly, ensure `customComponents` is memoized at\n * the call site.\n *\n * @module components/MarkdownContent\n */\n\nimport { Fragment, memo, useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport Markdown, { defaultUrlTransform, type Options as MarkdownOptions } from './markdown';\n\ntype RemarkPlugins = NonNullable<MarkdownOptions['remarkPlugins']>;\ntype RehypePlugins = NonNullable<MarkdownOptions['rehypePlugins']>;\ntype RemarkRehypeOptions = NonNullable<MarkdownOptions['remarkRehypeOptions']>;\nimport { sanitizeSchema } from '@ai-react-markdown/engine';\nimport { createBlockPlanner } from './blockPlanner';\nimport { createCache, renderBlocksWithCache, type Cache, type PostOptions } from './blockMemo';\nimport {\n  buildCoreRehypePlugins,\n  buildCoreRemarkPlugins,\n  buildCoreRemarkRehypeOptions,\n} from '@ai-react-markdown/engine';\nimport {\n  createPipelineSession,\n  derivePhantomTargets,\n  deriveCoordinationPolicy,\n  buildContributionChain,\n  type CoordinationPolicy,\n} from '@ai-react-markdown/runtime';\nimport { measureStage } from '@ai-react-markdown/engine';\nimport { useAIMarkdownDocument, useAIMarkdownState } from '../context';\nimport { useProvenanceCredential } from './provenance';\nimport { deriveTailSignal } from './streamingCursor/tailSignal';\nimport { AIMarkdownCustomComponents } from '../defs';\nimport type { AIMarkdownEnginePlugin } from '@ai-react-markdown/engine';\nimport { collectDefLabels, createDefLabelScanner, type DefLabelScanner } from '@ai-react-markdown/engine';\nimport { useDocumentRegistry, usePreserveOrphanReferences } from './AIMarkdownDocuments';\nimport type { RegistryInternal } from '@ai-react-markdown/engine';\nimport type { SanitizeSchema } from '@ai-react-markdown/engine';\nimport { crossChunkComponents } from './crossChunkPlaceholders';\nimport { CrossChunkUrlContext, type CrossChunkUrlPolicy } from './crossChunkUrlContext';\nimport { AggregateFootnotesIfLast } from './aggregateFootnotesIfLast';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport { useRegistryContribution } from './useRegistryContribution';\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/** Stable empty object to avoid unnecessary re-renders when no custom components are given. */\nconst DefaultCustomComponents: AIMarkdownCustomComponents = {};\n\n/** Stable empty result for the PASS 0 def-label scan in standalone mode\n *  (no registry). One shared frozen instance so `ownLabels` keeps the same\n *  identity across every render — downstream effects and memos that list it\n *  as a dep never churn while uncoordinated. */\nconst EMPTY_DEF_LABELS: ReturnType<typeof collectDefLabels> = Object.freeze({\n  footnoteLabels: new Set<string>(),\n  linkLabels: new Set<string>(),\n});\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  /** This chunk's position in the document — see the `documentIndex` prop\n   *  on `<AIMarkdown>`. Undefined keeps registration in mount order. */\n  documentIndex?: number;\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   * is used (not publicly exported as a value — see\n   * {@link extendSanitizeSchema}). Callers should produce this via\n   * {@link extendSanitizeSchema} to avoid silently dropping the cross-chunk\n   * tag allowlist.\n   */\n  sanitizeSchema?: SanitizeSchema;\n  // ── Resolved engine values ──\n  // Passed field-by-field from `<AIMarkdown>`'s single resolution point.\n  /** Renderer dispatch: block-memo path (`true`) vs legacy path (`false`). */\n  blockMemo: boolean;\n  /** Incremental (prefix-freeze) parse gate. */\n  incrementalParse: boolean;\n  /** Orphan-reference policy (standalone mode; `<AIMarkdownDocuments>` overrides via its own chain). */\n  preserveOrphanReferences: boolean;\n  /** Resolved sealed-plugin selection (sanitized; absent prop already defaulted upstream). */\n  enginePlugins: readonly AIMarkdownEnginePlugin[];\n}\n\ninterface RendererProps {\n  content: string;\n  /** This chunk's position in the document — see the `documentIndex` prop\n   *  on `<AIMarkdown>`. Undefined keeps registration in mount order. */\n  documentIndex?: number;\n  usedComponents: AIMarkdownCustomComponents;\n  remarkPlugins: RemarkPlugins;\n  rehypePlugins: RehypePlugins;\n  remarkRehypeOptions: RemarkRehypeOptions;\n  urlTransform: MarkdownOptions['urlTransform'];\n  /** Incremental-parse gate (resolved). */\n  incrementalParse: boolean;\n  /** Resolved orphan-reference policy (standalone tier of the override chain). */\n  preserveOrphanReferences: boolean;\n  /**\n   * Whether the definition-list plugin is in the active chain. Feeds the\n   * boundary scanner's syntax awareness (`computeFreezeBoundary`'s\n   * `defListEnabled`) — the scanner must know the boundary rules of every\n   * active multiline construct.\n   */\n  defListEnabled: boolean;\n  /** Resolved sanitize schema. Propagated to cross-chunk placeholders via\n   *  {@link CrossChunkUrlContext} so they can apply the same `protocols.*`\n   *  allowlist that `rehype-sanitize` applies to in-tree `<a>`/`<img>` —\n   *  see `crossChunkUrlSanitize.ts` for why this must happen at render\n   *  time rather than at contribute time. */\n  sanitizeSchema: SanitizeSchema;\n  /** Per-instance provenance credential (see `./provenance`). Stamped by the\n   *  cross-chunk handlers through the remark-rehype options and checked by\n   *  the verifier `buildCoreRehypePlugins` installed with the same value. */\n  provenance: string;\n}\n\n/**\n * Block-memo render path. Mounted when the resolved `blockMemo` is `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  ({\n    content,\n    documentIndex,\n    usedComponents,\n    remarkPlugins,\n    rehypePlugins,\n    remarkRehypeOptions,\n    urlTransform,\n    sanitizeSchema: usedSanitizeSchema,\n    incrementalParse,\n    preserveOrphanReferences,\n    defListEnabled,\n    provenance,\n  }: 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, documentIdExplicit, clobberPrefix } = useAIMarkdownDocument();\n    const reactId = useId();\n    // The runtime value behind `useDocumentRegistry` is always a\n    // `RegistryInternal` (see `createRegistry`); the public hook narrows\n    // the return type to `Registry` so external consumers don't see the\n    // mutator methods. Here — the canonical internal coordinator — we\n    // widen back to `RegistryInternal` once at the top so subsequent\n    // mutator calls (`registerChunk`, `releaseSymbol`, `contributeChunkData`)\n    // type-check without scattered `as` casts.\n    const registry = useDocumentRegistry(documentId, documentIdExplicit) as RegistryInternal | null;\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: RegistryInternal; 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: def-label scan, then publish to registry.labelSet.\n    //\n    // Coordinated mode ONLY. Despite the \"lightweight\" framing in\n    // collectDefLabels' docs, it is a full second remark-parse of the\n    // content (def-only pipeline, but parsing is parsing), and every\n    // consumer of `ownLabels` — the register effect below, targetPhantoms,\n    // the contribute effect — no-ops without a registry. Running it in\n    // standalone mode doubles the per-token parse cost of a streaming\n    // render for output nobody reads (measured at ~1/3 of total commit\n    // time on the BlockMemoCompare story). Skip it entirely and hand back\n    // a stable empty result so downstream deps never churn.\n    //\n    // Coordinated mode goes through an append-aware scanner: while a token\n    // stream appends prose that can't contain a definition, the previous\n    // result is returned by REFERENCE — no re-parse, and the register\n    // effect below (which lists `ownLabels` as a dep) stops re-registering\n    // the chunk on every token. When a definition MAY be present, the\n    // scanner freezes the settled prefix at an engine-verified boundary and\n    // re-parses only the live tail. It stays convergent — equal to a full\n    // parse at every step, with non-append input resetting all cached\n    // state — so StrictMode double-invokes and aborted renders can't\n    // poison it.\n    const defScannerRef = useRef<DefLabelScanner | null>(null);\n    const ownLabels = useMemo(() => {\n      if (!registry) return EMPTY_DEF_LABELS;\n      const scanner = (defScannerRef.current ??= createDefLabelScanner());\n      return scanner.scan(content ?? '');\n    }, [content, registry]);\n\n    useEffect(() => {\n      if (!registry) return;\n      const s = registry.registerChunk(reactId, ownLabels.footnoteLabels, ownLabels.linkLabels, documentIndex);\n      setAllocation({ registry, sym: s });\n      return () => {\n        registry.releaseSymbol(reactId);\n        setAllocation(null);\n      };\n    }, [reactId, registry, ownLabels, documentIndex]);\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    // Every stage measurement in this component MUST carry this instance's\n    // documentId — a stageInstanceId-scoped subscriber silently drops\n    // unattributed emissions (the panel then shows \"0 ms ×0\", which reads\n    // as \"stage never ran\"). The bound wrapper makes forgetting impossible\n    // at call sites; do not call the bare measureStage here.\n    const measureHere = useCallback(\n      <T,>(stage: Parameters<typeof measureStage>[0], fn: () => T): T => measureStage(stage, fn, documentId),\n      [documentId]\n    );\n\n    const cacheRef = useRef<Cache>(createCache());\n    const [planBlocks] = useState(createBlockPlanner);\n    // Incremental-parse state (previous frame's content + post-transform\n    // trees + verified freeze boundary). Render-phase ref mutation, same\n    // pattern as `defScannerRef`/`cacheRef`. Cleared by the G3 flush below\n    // (belt-and-suspenders — the engine's own depsKey gate, which covers\n    // MORE inputs than G3's 12 fields, is the primary invalidation).\n    const [pipelineSession] = useState(createPipelineSession);\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: RegistryInternal | 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      pipelineSession.reset();\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 → `pipeline` 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      const next = derivePhantomTargets(\n        { content: content ?? '', ownLabels, labels: registry?.labelSet ?? null },\n        targetPhantomsRef.current\n      );\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(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 previousPolicy = useRef<CoordinationPolicy | undefined>(undefined);\n    const { handlers, preserveForBodyHarvest } = useMemo(() => {\n      const next = deriveCoordinationPolicy(\n        { coordinated: Boolean(registry), registered: Boolean(sym), preserveOrphanReferences: effectivePreserveOrphan },\n        previousPolicy.current\n      );\n      previousPolicy.current = next;\n      return next;\n    }, [registry, sym, effectivePreserveOrphan]);\n    // G3 supplement: the orphan policy is a to-hast input (footnote handler +\n    // `preserveOrphan` option) that changes footer membership AND body sup\n    // numbering without touching the mdast the block-memo ctx is derived\n    // from — so a runtime flip left the synthetic footer slot (keyed by\n    // globalCtx alone) and reference-bearing blocks serving stale nodes\n    // (2026-08 project review, core-render-03). Flush the block cache when\n    // it flips; the incremental engine's own depsKey already covers it.\n    // Render-phase ref mutation, same pattern as the G3 block above.\n    const preserveOrphanDepRef = useRef(preserveForBodyHarvest);\n    if (preserveOrphanDepRef.current !== preserveForBodyHarvest) {\n      cacheRef.current = createCache();\n      preserveOrphanDepRef.current = preserveForBodyHarvest;\n    }\n\n    // Runtime selects coordinated handlers, orphan-only handling or normal\n    // standalone semantics. React owns policy memoization and commit timing.\n\n    // Stage 1 + 2: parse → run remark/rehype pipeline, as ONE memo returning\n    // `{ mdast, hast }`. Merged (formerly separate `parsed`/`hast` memos)\n    // because the incremental-parse engine owns both stages: on a splice it\n    // reuses the frozen prefix of the previous frame's post-transform trees\n    // and runs parse+transform over the tail only.\n    const pipeline = useMemo(\n      () =>\n        pipelineSession.parse({\n          content: content ?? '',\n          targetPhantoms,\n          remarkPlugins,\n          rehypePlugins,\n          remarkRehypeOptions,\n          handlers,\n          preserveForBodyHarvest,\n          documentId,\n          provenance,\n          incrementalParse: incrementalParse && typeof window !== 'undefined',\n          defListEnabled,\n          measure: measureHere,\n        }),\n      [\n        pipelineSession,\n        content,\n        targetPhantoms,\n        remarkPlugins,\n        rehypePlugins,\n        remarkRehypeOptions,\n        handlers,\n        preserveForBodyHarvest,\n        documentId,\n        provenance,\n        incrementalParse,\n        defListEnabled,\n        measureHere,\n      ]\n    );\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(\n      () =>\n        measureHere('build', () =>\n          planBlocks(pipeline.mdast, pipeline.hast, content ?? '', {\n            // The block cache's footnote rank models `state.footnoteOrder`,\n            // which phantom labels never enter (2026-08-20 B2). Identity is\n            // stable across renders whose phantom sets match, so this does\n            // not defeat the memo.\n            phantomFootnoteLabels: targetPhantoms.missingFootnotes,\n          })\n        ),\n      [pipeline, content, measureHere, targetPhantoms, planBlocks]\n    );\n\n    // Streaming-cursor tail signal: classify whether the source tail sits\n    // inside a (footnote / link-reference) definition — derived from the\n    // SAME mdast this render draws, with phantom-suffix nodes filtered by\n    // offset against the preprocessed content. Only computed while\n    // streaming: the marker it drives must not exist in static documents\n    // (see the marker's own comment in the render tail). The legacy\n    // (blockMemo:false) path has no pipeline mdast and renders no marker —\n    // the cursor keeps today's body-tail behavior there.\n    const { streaming } = useAIMarkdownState();\n    const tailSignal = useMemo(\n      () => (streaming ? deriveTailSignal(pipeline.mdast, (content ?? '').length) : null),\n      [streaming, pipeline, content]\n    );\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    const contributionChain = useMemo(\n      () =>\n        buildContributionChain({\n          remarkPlugins,\n          rehypePlugins,\n          remarkRehypeOptions,\n          handlers,\n          preserveForBodyHarvest,\n          clobberPrefix,\n          documentId,\n          provenance,\n        }),\n      [\n        remarkPlugins,\n        rehypePlugins,\n        remarkRehypeOptions,\n        handlers,\n        preserveForBodyHarvest,\n        clobberPrefix,\n        documentId,\n        provenance,\n      ]\n    );\n    useRegistryContribution({\n      pipeline,\n      ownLabels,\n      registry,\n      targetPhantoms,\n      sym,\n      clobberPrefix,\n      chain: contributionChain,\n    });\n\n    // Intentional cache memoization via cacheRef; see G3 comment above.\n    // Unlike the three memoized stages above, this runs on EVERY render —\n    // its 'render' measures therefore include the cheap all-cache-hit\n    // re-renders, which is the honest shape of what block-memo saves.\n    const rendered = measureHere('render', () =>\n      renderBlocksWithCache(cacheRef, built.plan, built.globalCtx, postOptions)\n    );\n\n    // Cross-chunk URL sanitization policy — read by `CrossChunkLink` and\n    // `CrossChunkImage` at render time to apply schema, hash rebasing and\n    // urlTransform in the order that the standalone in-tree pass\n    // applies. Resolved here so the same `defaultUrlTransform` /\n    // `sanitizeSchema` fallbacks the rest of the pipeline uses are honored\n    // — no chance of drift between standalone and cross-chunk paths.\n    const crossChunkUrlPolicy = useMemo<CrossChunkUrlPolicy>(\n      () => ({\n        urlTransform: urlTransform || defaultUrlTransform,\n        sanitizeSchema: usedSanitizeSchema,\n      }),\n      [urlTransform, usedSanitizeSchema]\n    );\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      <CrossChunkUrlContext.Provider value={crossChunkUrlPolicy}>\n        <ChunkSymbolContext.Provider value={sym}>\n          {rendered.map(({ node, key }) => (\n            <Fragment key={key}>{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          {tailSignal ? (\n            // Streaming-cursor tail marker: tells the cursor shell (same\n            // commit as the content DOM it will measure — no React timing\n            // skew) that the source tail is inside a definition, and which\n            // footer <li> the text is streaming into. Rendered ONLY while\n            // streaming with a definition tail: a permanent marker would\n            // re-break the `:last-child` margin-trim fallbacks the SCSS\n            // keeps for pre-Baseline-2023 engines (the modern rulesets\n            // exclude it explicitly, same as the cursor wrapper). display:\n            // none keeps it out of layout; the anchor walk skips it by\n            // attribute. Mount/unmount on signal flips doubles as the\n            // childList mutation that wakes the shell's observer.\n            <span\n              data-aimd-tail-kind={tailSignal.kind}\n              data-aimd-tail-label={tailSignal.kind === 'footnote-def' ? tailSignal.identifier : undefined}\n              data-aimd-clobber-prefix={tailSignal.kind === 'footnote-def' ? clobberPrefix : undefined}\n              style={{ display: 'none' }}\n            />\n          ) : null}\n        </ChunkSymbolContext.Provider>\n      </CrossChunkUrlContext.Provider>\n    );\n  }\n);\nBlockMemoizedRenderer.displayName = 'BlockMemoizedRenderer';\n\n/**\n * Legacy render path. Mounted when the resolved `blockMemo` is `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`), INCLUDING the orphan-reference policy: the\n * standalone `footnoteDefinition` handler is merged here exactly as the\n * block-memo path does it, so `blockMemo` stays output-invariant (it was\n * not — a def arriving before its reference vanished from the footer only\n * on this path; 2026-08 project review, core-render-04).\n *\n * **Cross-chunk coordination (Phase 11) is NOT wired through this path.**\n * Wrapping `<AIMarkdown>` with `<AIMarkdownDocuments>` while keeping\n * `blockMemo: false` silently runs without coordination — refs across\n * chunks don't resolve (orphan defs ARE still protected, per the wrapper/\n * prop/default override chain). If you need cross-chunk behavior, keep\n * `blockMemo: true` (the default).\n */\nconst LegacyRenderer = memo(\n  // `sanitizeSchema` is accepted (and ignored) here purely for prop-shape\n  // parity with `BlockMemoizedRenderer` — legacy mode skips cross-chunk\n  // coordination entirely, so there's no placeholder needing the schema.\n  // Rebind to an underscore-prefixed local so the project's\n  // no-unused-vars rule (which allows `_`-prefixed names) accepts it.\n  ({\n    content,\n    usedComponents,\n    remarkPlugins,\n    rehypePlugins,\n    remarkRehypeOptions,\n    urlTransform,\n    preserveOrphanReferences,\n    sanitizeSchema: _sanitizeSchema,\n    provenance,\n  }: RendererProps) => {\n    const effectivePreserveOrphan = usePreserveOrphanReferences(preserveOrphanReferences);\n    const { documentId } = useAIMarkdownDocument();\n    // Same merge as the block-memo path's standalone branch: only the\n    // footnoteDefinition handler (the other three depend on a registry and\n    // would emit placeholders that render nothing here); phantom sets are\n    // empty so the handler's phantom check is always false.\n    const mergedRemarkRehypeOptions = useMemo<RemarkRehypeOptions>(() => {\n      if (!effectivePreserveOrphan) return remarkRehypeOptions;\n      const { handlers } = deriveCoordinationPolicy({\n        coordinated: false,\n        registered: false,\n        preserveOrphanReferences: true,\n      });\n      return {\n        ...remarkRehypeOptions,\n        handlers: { ...(remarkRehypeOptions?.handlers ?? {}), ...handlers },\n        phantomFootnoteLabels: new Set<string>(),\n        phantomLinkLabels: new Set<string>(),\n        preserveOrphan: true,\n        documentId,\n        provenance,\n      } as RemarkRehypeOptions;\n    }, [remarkRehypeOptions, effectivePreserveOrphan, documentId, provenance]);\n    return (\n      <Markdown\n        remarkPlugins={remarkPlugins}\n        rehypePlugins={rehypePlugins}\n        remarkRehypeOptions={mergedRemarkRehypeOptions}\n        components={usedComponents}\n        urlTransform={urlTransform}\n      >\n        {content}\n      </Markdown>\n    );\n  }\n);\nLegacyRenderer.displayName = 'LegacyRenderer';\n\n/**\n * Internal component that assembles the remark/rehype plugin chain based on\n * the resolved engine values (received as internal props from\n * `<AIMarkdown>`'s single resolution point), then dispatches to either the\n * block-memo renderer or the legacy renderer based on `blockMemo`.\n */\nconst AIMarkdownContent = memo(\n  ({\n    content,\n    documentIndex,\n    customComponents,\n    urlTransform,\n    sanitizeSchema: customSanitizeSchema,\n    blockMemo,\n    incrementalParse,\n    preserveOrphanReferences,\n    enginePlugins,\n  }: AIMarkdownContentProps) => {\n    const { clobberPrefix } = useAIMarkdownDocument();\n    // One provenance credential per mounted instance (see ./provenance for\n    // why it is a lazy state initialiser and not a ref or a memo).\n    const provenance = useProvenanceCredential().value;\n    // Dev-mode flip probes live in the parent `<AIMarkdown>`'s stability\n    // firewall (`useStableRecord`, `./../index.tsx`) — the DEEP_EQUAL policy\n    // there both warns on identity churn and restores the previous reference.\n    // Don't add a duplicate probe 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's firewall, so this picks one of two\n    // stable references rather than minting a new object every render —\n    // important for the rehypePlugins memo below.\n    const usedSanitizeSchema = customSanitizeSchema ?? sanitizeSchema;\n\n    const enableDefinitionList = enginePlugins.some((plugin) => plugin.name === 'definitionList');\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    // Chain assembly lives in pluginChain.ts — the single source shared with\n    // the splice-equivalence arbiter and the prefixFreeze experiment harness,\n    // so verification suites can never drift from the shipped order.\n    const remarkPlugins = useMemo<RemarkPlugins>(() => buildCoreRemarkPlugins(enginePlugins), [enginePlugins]);\n\n    const rehypePlugins = useMemo<RehypePlugins>(\n      () => buildCoreRehypePlugins(usedSanitizeSchema, clobberPrefix, { provenance }),\n      [clobberPrefix, usedSanitizeSchema, provenance]\n    );\n\n    const remarkRehypeOptions = useMemo<RemarkRehypeOptions>(\n      () => buildCoreRemarkRehypeOptions(enableDefinitionList),\n      [enableDefinitionList]\n    );\n\n    const Renderer = blockMemo ? BlockMemoizedRenderer : LegacyRenderer;\n    return (\n      <Renderer\n        content={content}\n        documentIndex={documentIndex}\n        usedComponents={usedComponents}\n        remarkPlugins={remarkPlugins}\n        rehypePlugins={rehypePlugins}\n        remarkRehypeOptions={remarkRehypeOptions}\n        urlTransform={urlTransform}\n        sanitizeSchema={usedSanitizeSchema}\n        incrementalParse={incrementalParse}\n        preserveOrphanReferences={preserveOrphanReferences}\n        defListEnabled={enableDefinitionList}\n        provenance={provenance}\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 { toJsxRuntime } from 'hast-util-to-jsx-runtime';\nimport type { Element, Root as HastRoot, RootContent } from 'hast';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { visit } from 'unist-util-visit';\nimport { buildTransform, defaultUrlTransform, parseStage, transformStage } from '@ai-react-markdown/engine';\nimport { cloneHastForRender } from '../cloneHastForRender';\nimport type { Options } from './types';\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 tree it walks in place, and callers\n * MAY pass a tree that outlives the call — the block-memo flow re-enters the\n * same memoized hast whenever a render happens without a re-parse (G3 cache\n * flush, registry version bump, urlTransform prop swap). Re-entry is safe\n * because every mutation class is handled:\n *\n * - `urlTransform` overwrites are applied CONVERGENTLY — recomputed from an\n *   original value stashed on `element.data.originalUrls` (see\n *   `buildTransform`), so a non-idempotent transform never compounds and a\n *   swapped transform never sees its predecessor's output. No clone needed.\n * - The raw→text rewrite is value-preserving and self-exhausting (no raw\n *   nodes remain after the first pass). No clone needed.\n * - The element filters (`allowedElements` / `disallowedElements` /\n *   `allowElement`) and `skipHtml` splice children DESTRUCTIVELY — removed\n *   nodes are unrecoverable, so when any of them is set the visit runs on a\n *   private structural clone. `<AIMarkdown>` never sets them (hardcoded\n *   `undefined` in `MarkdownContent`), so its flows never pay the clone.\n *   A caller that OWNS the tree — fresh-parsed, discarded when the call\n *   returns, never re-entered (the legacy `Markdown()` path) — passes\n *   `ownsTree: true` to skip the clone: there is nothing to protect, and\n *   for a react-markdown-compat caller with a filter set the clone would\n *   otherwise cost O(nodes) per render (per token when streaming).\n *\n * Known accepted edge: flipping a filter/skipHtml ON between renders of the\n * SAME shared tree cannot retroactively restore nodes an earlier unfiltered\n * pass already rendered — unreachable from `<AIMarkdown>`, and a content\n * re-parse heals it on the next token in any streaming flow.\n */\nexport function renderHastSubtree(\n  tree: HastRoot | RootContent,\n  options: Readonly<Options>,\n  opts?: { ownsTree?: boolean }\n): ReactNode {\n  const needsClone =\n    !opts?.ownsTree &&\n    Boolean(options.allowedElements || options.disallowedElements || options.allowElement || options.skipHtml);\n  const input: HastRoot | RootContent = needsClone ? cloneHastForRender(tree) : tree;\n  const root: HastRoot = input.type === 'root' ? input : { type: 'root', children: [input] };\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  // The tree is a local, parsed fresh on every call and dead after it —\n  // no shared-tree re-entry exists here, so the destructive filters may\n  // splice it in place instead of paying the defensive clone.\n  return renderHastSubtree(tree, options, { ownsTree: true }) 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","/** Framework-neutral block planning and dependency fingerprints.\n * Cache ownership and conversion to framework nodes belong to adapters.\n * See docs/architecture.md and packages/runtime/README.md for the contract.\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 { SKIP, visit } from 'unist-util-visit';\nimport { isFootnoteSection, normalizeId, type Registry } from '@ai-react-markdown/engine';\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/** 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  /**\n   * Structural digest of the block's hast subtree, computed ONLY for blocks\n   * that originate from raw HTML (mdast `html` nodes, or blocks resolved via\n   * the range-containment fallback). Undefined for markdown-native blocks.\n   *\n   * Why it exists: rehype-raw applies the HTML parsing algorithm, so an\n   * UNCLOSED container tag (`<details>` mid-stream, before its `</details>`\n   * arrives) swallows every FOLLOWING top-level sibling into itself —\n   * including the synthetic `<section data-footnotes>`. The block's mdast\n   * identity (raw, position, ctx) is byte-identical across all those frames,\n   * so without this digest the first swallowed snapshot would be a permanent\n   * cache hit: content rendered inside the container freezes, and when the\n   * close tag finally arrives the real nodes re-render at top level while the\n   * stale copies stay trapped in the cached container (the \"duplicate\n   * footnote section inside <details>\" bug).\n   *\n   * Digest composition — `maxEnd:descendantCount:hasFootnoteSection:swallowedHash`:\n   * - max end offset over the subtree catches swallowed POSITIONED siblings\n   *   (their offsets lie beyond the mdast node's own range);\n   * - descendant count catches position-less synthetic content moving in or\n   *   out (the footnote section's own element carries no position, and its\n   *   li contents point BACK at the definitions' offsets, which can be\n   *   smaller than the container's end — maxEnd alone misses that case);\n   * - the explicit dataFootnotes bit closes the degenerate corner where a\n   *   swallowed section and later real children tie on both numbers;\n   * - a hash of the swallowed extent's SOURCE (`[ownEnd, maxEnd)`) catches\n   *   an equal-length, equal-shape single-frame replacement of the\n   *   swallowed siblings, which leaves every count unchanged.\n   *\n   * Markdown-native blocks (paragraph/list/math/code/…) never receive\n   * reparented content — every hast descendant derives from their own mdast\n   * source range — so they skip the subtree walk entirely. This keeps the\n   * per-frame cost away from huge deterministic subtrees like KaTeX output.\n   */\n  hastDigest?: string;\n  /** A raw-HTML container that swallowed the synthesized\n   *  `<section data-footnotes>` (rehype-raw reparents the following siblings\n   *  into an unclosed `<details>` / `<div>` mid-stream). The footer is then\n   *  NOT a top-level plan item, so coordinated mode's \"skip the local\n   *  footer, the aggregate renders it\" rule never fired and the document\n   *  showed two `<section data-footnotes>` with colliding li ids (2026-08-19\n   *  review r2 P2-9). Coordinated renders strip it from this block's subtree;\n   *  standalone renders keep it exactly where the full parse puts it. */\n  containsFootnoteSection?: 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    /** Chunk-local footnote state the engine baked into this block's\n     *  `footnote-sup` placeholders (`localOccurrence` / `localNumber` come\n     *  from a per-chunk counter over all PRECEDING refs, customMdastHandlers):\n     *  per ref label, refs-before-this-block count and first-appearance\n     *  rank. Same raw + same registry answers but a different prefix (an\n     *  in-place `[^x]`→`[^w]` edit upstream) must miss the cache, or the\n     *  stale occurrence resolves to a null global occurrence and the mark\n     *  vanishes (2026-08-19 review P2-4). Absent when the block has no refs. */\n    footnoteRefLocalCtx?: string;\n    /** Baked `localUrl` / `localTitle` of swallowed `cross-chunk-link` /\n     *  `-image` placeholders, as `[[label, url, title|null]…]` (JSON). The\n     *  render falls back to these when the registry has no canonical def,\n     *  where the fingerprint's `lr:`/`ir:` part is the constant `null` —\n     *  see scanSwallowedSubtree. Absent when nothing was swallowed. */\n    swallowedDefCtx?: string;\n  };\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// isFootnoteSection lives in the engine now (boundary action ①): the\n// incremental-parse engine's attributeHastChildren needs it too, and\n// engine→core imports are forbidden. Re-exported so this module's export\n// surface (and its tests) stay unchanged.\nexport { isFootnoteSection };\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 * Compute {@link BlockInfo.hastDigest} for a raw-HTML block: iterative walk\n * over the hast subtree collecting (max end offset, descendant count,\n * contains-footnote-section). See the field's JSDoc for why each component\n * is load-bearing. Exported for tests.\n */\nexport function computeHtmlBlockDigest(el: HastElement, source?: string, ownEnd?: number): string {\n  return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;\n}\n\n/** {@link computeHtmlBlockDigest} plus the subtree's max end offset — the end\n *  of the SWALLOWED extent, which callers need to ask what fell inside.\n *\n *  Both position sources here are HAST offsets, and every use of the extent\n *  is unsafe in the SHORT direction (too small and a swallowed reference\n *  escapes the taint test, so an edit to a definition outside the container\n *  leaves a stale href in the cache). They are redundant on purpose: the\n *  container's own end already reaches past the swallowed blocks, because\n *  `rehype-raw` reparses the raw string and closes the element wherever\n *  parse5 does — NOT where the mdast `html` node ends, which is just the\n *  opening tag. The descendant walk covers it a second time. Verified in\n *  2026-08-20 A1 across 162 container/tail shapes: destroying either source\n *  alone changes nothing, destroying both under-taints 130 of them. */\nexport function computeHtmlBlockDigestWithExtent(\n  el: HastElement,\n  source?: string,\n  ownEnd?: number\n): { digest: string; maxEnd: number } {\n  let maxEnd = el.position?.end?.offset ?? 0;\n  let count = 0;\n  let hasFootnoteSection = false;\n  const stack: HastElement['children'][number][] = [...el.children];\n  while (stack.length > 0) {\n    const node = stack.pop()!;\n    count++;\n    const end = node.position?.end?.offset;\n    if (end !== undefined && end > maxEnd) {\n      maxEnd = end;\n    }\n    if (node.type === 'element') {\n      if (isFootnoteSection(node)) {\n        hasFootnoteSection = true;\n      }\n      for (const child of node.children) {\n        stack.push(child);\n      }\n    }\n  }\n  // Swallowed SOURCE hash: `maxEnd:count` are blind to an equal-length,\n  // equal-shape replacement of the swallowed siblings (`Answer: 42` →\n  // `Answer: 43` inside an unclosed <details>, single-frame — v2.4.2 review\n  // P2-1); the container's own `raw` is unchanged, so the cache hit kept\n  // rendering the old text. Hashing the swallowed extent's source closes it.\n  const swallowed = source !== undefined && ownEnd !== undefined && maxEnd > ownEnd ? source.slice(ownEnd, maxEnd) : '';\n  return { digest: `${maxEnd}:${count}:${hasFootnoteSection ? 1 : 0}:${fnv1a(swallowed)}`, maxEnd };\n}\n\n/** FNV-1a 32-bit over UTF-16 code units — cheap, no allocation. */\nfunction fnv1a(text: string): string {\n  let h = 0x811c9dc5;\n  for (let i = 0; i < text.length; i++) {\n    h ^= text.charCodeAt(i);\n    h = Math.imul(h, 0x01000193) >>> 0;\n  }\n  return h.toString(36);\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 the adapter’s block cache\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; key: string; info: BlockInfo }\n  | { kind: 'inline'; el: HastChild; key: string }\n  | { kind: 'synthetic'; el: HastElement; key: string };\n\nconst EMPTY_LABELS: ReadonlySet<string> = new Set<string>();\n\n/** Extra render-time facts {@link buildBlocks} cannot read off the trees. */\nexport interface BuildBlocksOptions {\n  /** Full document when planning only a tail. Its ordered reference and\n   * definition context seeds numbering and invalidation for tail blocks. */\n  contextMdast?: MdastRoot;\n  /**\n   * Labels this chunk phantom-injected because another chunk defines them\n   * (already normalized). The coordinated handlers keep these out of\n   * `state.footnoteOrder`, so the cache key's rank must keep them out too —\n   * see the note in the rank pass. Empty / omitted in standalone mode, where\n   * no phantom injection happened.\n   */\n  phantomFootnoteLabels?: ReadonlySet<string>;\n}\n\n/** Result of {@link buildBlocks}. */\nexport interface BuildBlocksResult {\n  /** Render plan in document order — drives the adapter’s block cache. */\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\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(\n  mdast: MdastRoot,\n  hast: HastRoot,\n  source: string,\n  options: BuildBlocksOptions = {}\n): BuildBlocksResult {\n  const phantomFootnotes = options.phantomFootnoteLabels ?? EMPTY_LABELS;\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  // Start offsets of every taint node, in document order — used to tell\n  // whether a raw-HTML container swallowed a reference whose RENDERING\n  // depends on a definition outside it (see the isRawHtmlBlock branch).\n  const taintOffsets: number[] = [];\n  /** First index in `taintOffsets` at or after `offset`. The offsets are\n   *  pushed by a document-order `visit`, so the array is already sorted —\n   *  the same property `findContainingMdast` above relies on. */\n  const firstTaintAtOrAfter = (offset: number): number => {\n    let lo = 0;\n    let hi = taintOffsets.length;\n    while (lo < hi) {\n      const mid = (lo + hi) >>> 1;\n      if (taintOffsets[mid] < offset) lo = mid + 1;\n      else hi = mid;\n    }\n    return lo;\n  };\n  visit(options.contextMdast ?? mdast, (n) => {\n    if (!CTX_TYPES.has(n.type)) return;\n    const at = n.position?.start?.offset;\n    if (at !== undefined) taintOffsets.push(at);\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  if (process.env.NODE_ENV !== 'production') {\n    // A preorder walk yields non-decreasing start offsets on any well-formed\n    // tree, and `firstTaintAtOrAfter` is a binary search over exactly that.\n    // Same guard, same reason, and the same shape as the one on\n    // `mdastRanges`: the env read stays OUT of the per-node path, which cost\n    // more than the search saved when it was inside it.\n    for (let i = 1; i < taintOffsets.length; i++) {\n      if (taintOffsets[i] < taintOffsets[i - 1]) {\n        throw new Error(\n          'block-memo: taint node start offsets are not source-ordered — ' +\n            'a remark plugin is reordering nodes or emitting bad positions.'\n        );\n      }\n    }\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  // Mirror of the engine's per-chunk footnote counter (customMdastHandlers:\n  // one bump per footnoteReference in mdast-util-to-hast's preorder walk):\n  // computed ONCE over the mdast in document order, per ref NODE, so the\n  // hast-driven block loop below cannot skew it — a range-fallback block\n  // resolves several hast siblings to one mdast node (its refs would be\n  // counted twice), and refs inside a footnote definition are rendered by\n  // the footer AFTER every body ref (never in a body block) — skipped.\n  const refLocalCtx = new Map<MdastNodes, readonly [prior: number, rank: number]>();\n  {\n    const counts = new Map<string, number>();\n    const ranks = new Map<string, number>();\n    const rankOf = (id: string): number => {\n      // A PHANTOM label never enters the engine's footnoteOrder — the\n      // coordinated handlers return early for both its definition and its\n      // references, and its `footnote-sup` gets no `localNumber` at all. It\n      // must not take a rank here either, or the model drifts from the value\n      // actually baked into the placeholder: with `[^A]` cross-chunk and\n      // `[^B]` local, B's baked number is 1 while A is phantom and 2 once A's\n      // definition arrives — and B's rank, counting A both times, stayed 1.\n      // Same raw, same position, same rank: the cache served a superscript\n      // reading 1 under a footer numbering it 2 (2026-08-20 B2).\n      if (phantomFootnotes.has(id)) return -1;\n      let rank = ranks.get(id);\n      if (rank === undefined) {\n        rank = ranks.size;\n        ranks.set(id, rank);\n      }\n      return rank;\n    };\n    visit(options.contextMdast ?? mdast, (n) => {\n      if (n.type === 'footnoteDefinition') {\n        // A definition met before the label's first ref can enter the\n        // engine's footnoteOrder first (preserveOrphan) — it takes part in\n        // the first-appearance rank; its body refs are footer-rendered.\n        //\n        // Modelled as `preserveOrphan: true` unconditionally, which is not\n        // always what the engine does. Deliberate: with orphan protection\n        // OFF the two orderings can disagree, but they disagree the SAME way\n        // in every frame, and the flag only changes by a prop change — which\n        // re-parses the whole pipeline anyway. Phantom status is different:\n        // it flips mid-stream, which is what made it a stale-cache bug.\n        rankOf(normalizeId(String(n.identifier)));\n        return SKIP;\n      }\n      if (n.type !== 'footnoteReference') return;\n      const id = normalizeId(String(n.identifier));\n      const prior = counts.get(id) ?? 0;\n      refLocalCtx.set(n, [prior, rankOf(id)]);\n      counts.set(id, prior + 1);\n    });\n  }\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 key = off !== undefined ? `inline-${off}` : `inline-i${i}`;\n      plan.push({ kind: 'inline', el: hastChild, key });\n      continue;\n    }\n\n    const el = hastChild;\n\n    if (isFootnoteSection(el)) {\n      synthetic = el;\n      plan.push({ kind: 'synthetic', el, key: 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, key: `inline-i${i}` });\n      continue;\n    }\n\n    let mdastNode = mdastByOffset.get(hastOffset);\n    let viaRangeFallback = false;\n\n    if (!mdastNode) {\n      mdastNode = findContainingMdast(hastOffset);\n      viaRangeFallback = mdastNode !== undefined;\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, key: `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, key: `inline-${hastOffset}` });\n      continue;\n    }\n\n    // Only a raw-HTML block can have foreign content reparented into it by\n    // rehype-raw (an unclosed container tag mid-stream); markdown-native\n    // blocks derive their whole subtree from their own source range.\n    const isRawHtmlBlock = mdastNode.type === 'html' || viaRangeFallback;\n    let hasReference = false;\n    const swallowed = isRawHtmlBlock ? scanSwallowedSubtree(el) : null;\n    const footnoteRefLabels: string[] = [];\n    const linkRefLabels: string[] = [];\n    const imageRefLabels: string[] = [];\n    const footnoteDefLabels: string[] = [];\n    const local: [string, number, number][] = [];\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') {\n        footnoteRefLabels.push(id);\n        // Refs inside a nested footnote definition have no entry (footer-\n        // rendered, not part of this block's output).\n        const ctx = refLocalCtx.get(n);\n        if (ctx) local.push([id, ctx[0], ctx[1]]);\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    // Merge what the container swallowed (see scanSwallowedSubtree): the\n    // mdast walk above saw only the empty `html` node.\n    if (swallowed !== null && swallowed.hasReference) {\n      hasReference = true;\n      footnoteRefLabels.push(...swallowed.refLabels);\n      linkRefLabels.push(...swallowed.linkLabels);\n      imageRefLabels.push(...swallowed.imageLabels);\n      local.push(...swallowed.local);\n    }\n    // JSON-encoded: labels may hold any separator character.\n    const footnoteRefLocalCtx = local.length > 0 ? JSON.stringify(local) : undefined;\n    const swallowedDefCtx =\n      swallowed !== null && swallowed.bakedDefs.length > 0 ? JSON.stringify(swallowed.bakedDefs) : undefined;\n\n    const mdastPos = mdastNode.position;\n    if (!mdastPos || mdastPos.start?.offset === undefined || mdastPos.end?.offset === undefined) {\n      // A third-party remark plugin emitting a half-built position: the\n      // block cannot be cached, but the user's content is never silently\n      // lost — render it uncached like the other no-counterpart fallbacks\n      // above (v2.4.1 review: this path used to drop the hast element).\n      plan.push({ kind: 'inline', el, key: `inline-${hastOffset}` });\n      continue;\n    }\n\n    // Raw-HTML blocks are the only ones rehype-raw can reparent following\n    // siblings into (unclosed container tags mid-stream). Two origins:\n    // a top-level mdast `html` node, or a block resolved via the\n    // range-containment fallback (raw HTML embedded in another node, split\n    // into extra hast siblings). Digest their subtree so the cache\n    // invalidates when the swallowed extent changes; markdown-native blocks\n    // skip the walk (their subtrees derive purely from their own source\n    // range, already covered by `raw` + position).\n    let hastDigest: string | undefined;\n    let swallowedTaint = false;\n    if (isRawHtmlBlock) {\n      const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);\n      hastDigest = d.digest;\n      // Did the container swallow a reference or definition? The hast scan\n      // above sees coordinated placeholders and standalone footnote marks,\n      // but a STANDALONE link/image reference renders as a plain `<a href>` /\n      // `<img src>` — indistinguishable from an inline link. Ask the mdast\n      // instead: any taint node whose source offset lies inside the swallowed\n      // extent. Without this a definition sitting BEFORE the container (thus\n      // outside the digest's `[ownEnd, maxEnd)` hash) could change the\n      // rendered href while every cache-key component stayed equal.\n      //\n      // What this buys, per mode: in STANDALONE mode the flag switches the\n      // key to `globalCtx`, which encodes every definition's url/title —\n      // strictly stronger. In COORDINATED mode the labels come from the\n      // placeholder scan above (every resolvable reference becomes a\n      // `cross-chunk-*` element), so this test is belt-and-braces there.\n      // `[ownEnd, maxEnd)` mixes offset systems on purpose: `ownEnd` is the\n      // MDAST end (where the opening tag stops), `maxEnd` the HAST end\n      // (where parse5 closed the element, past everything it swallowed).\n      // Half-open at the low end because anything below `ownEnd` is already\n      // covered by `raw`, and `maxEnd` erring high only over-taints.\n      // Binary search, not a scan: the linear form was O(taint nodes ×\n      // raw-HTML blocks) on the streaming hot path, and the sortedness it\n      // needs is the same one `findContainingMdast` already assumes\n      // (2026-08-20 B5 — measured at 14% of buildBlocks on a document with\n      // 200 definitions and 120 containers).\n      const first = firstTaintAtOrAfter(mdastPos.end.offset);\n      swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;\n    }\n\n    // A standalone link/image reference renders as a plain `<a href>` /\n    // `<img src>`, so only the mdast range test above can see it — fold that\n    // in now that the extent is known.\n    if (swallowedTaint) hasReference = true;\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      ...(hastDigest !== undefined ? { hastDigest } : {}),\n      ...(swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {}),\n      ...(hasReference\n        ? {\n            taintLabels: {\n              footnoteRefLabels,\n              linkRefLabels,\n              imageRefLabels,\n              footnoteDefLabels,\n              ...(footnoteRefLocalCtx !== undefined ? { footnoteRefLocalCtx } : {}),\n              ...(swallowedDefCtx !== undefined ? { swallowedDefCtx } : {}),\n            },\n          }\n        : {}),\n    };\n    blocks.push(info);\n    blockHasts.push(el);\n    // render 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 render key. Hast positions are unique\n    // per element in the rendered tree.\n    plan.push({ kind: 'block', el, info, key: `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>|fl:<[[L,prior,rank]…]>|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  // Chunk-local occurrence/rank baked into the placeholders (P2-4) — see\n  // buildBlocks; JSON-encoded there, so label bytes cannot collide with `|`.\n  if (taintLabels.footnoteRefLocalCtx !== undefined) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);\n  if (taintLabels.swallowedDefCtx !== undefined) parts.push(`sd:${taintLabels.swallowedDefCtx}`);\n  // url/title are JSON-encoded so a `|` inside them cannot collide with the\n  // part separator (url `a|b` + no title ≡ url `a` + title `b` would be a\n  // stale cache hit — v2.4.1 review).\n  for (const label of taintLabels.linkRefLabels) {\n    const def = registry.resolveLinkDef(label);\n    parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : 'null'}`);\n  }\n  for (const label of taintLabels.imageRefLabels) {\n    const def = registry.resolveLinkDef(label);\n    parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : 'null'}`);\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\nconst PLACEHOLDER_TAGS = new Set(['footnote-sup', 'cross-chunk-link', 'cross-chunk-image']);\n\n/**\n * What a raw-HTML container swallowed, read from the HAST subtree rather\n * than from the container's mdast node — that node is an empty `html` node\n * whose own range says nothing about the reparented siblings, so every\n * mdast-derived taint fact came out empty and the block fell back to the\n * un-fingerprinted cache key (2026-08-19 review r2 P2-8: an equal-length\n * edit BEFORE the container changed a `localOccurrence` baked inside it and\n * the stale subtree stayed cached).\n *\n * Reads what is actually baked into the cached render output: the placeholders'\n * `label` / `localOccurrence` (coordinated), the standalone footnote marks\n * (`a[data-footnote-ref]`), and whether the synthesized footnote section\n * landed inside (see {@link BlockInfo.containsFootnoteSection}).\n */\nfunction scanSwallowedSubtree(el: HastElement): {\n  hasReference: boolean;\n  refLabels: string[];\n  linkLabels: string[];\n  imageLabels: string[];\n  local: [string, number, number][];\n  bakedDefs: [string, string, string | null][];\n  hasFootnoteSection: boolean;\n} {\n  const refLabels: string[] = [];\n  const linkLabels: string[] = [];\n  const imageLabels: string[] = [];\n  const local: [string, number, number][] = [];\n  const bakedDefs: [string, string, string | null][] = [];\n  let hasReference = false;\n  let hasFootnoteSection = false;\n  visit(el, 'element', (node: HastElement) => {\n    if (isFootnoteSection(node)) {\n      hasFootnoteSection = true;\n      hasReference = true;\n      return;\n    }\n    const props = (node.properties ?? {}) as Record<string, unknown>;\n    if (PLACEHOLDER_TAGS.has(node.tagName)) {\n      hasReference = true;\n      const identifier = props.identifier ?? props.label;\n      const label = identifier === undefined ? null : normalizeId(String(identifier));\n      if (label === null) return;\n      if (node.tagName === 'footnote-sup') {\n        refLabels.push(label);\n        // Chunk-local occurrence as BAKED into this placeholder — the exact\n        // value a stale cache hit would keep serving.\n        const occ = Number(props.localOccurrence);\n        const num = Number(props.localNumber);\n        local.push([label, Number.isFinite(occ) ? occ : -1, Number.isFinite(num) ? num : -1]);\n        return;\n      }\n      if (node.tagName === 'cross-chunk-link') linkLabels.push(label);\n      else imageLabels.push(label);\n      // `resolveDef` falls back to the placeholder's BAKED `localUrl` /\n      // `localTitle` when the registry has no canonical def — and the\n      // fingerprint writes `lr:LABEL=null` in exactly that case, a constant,\n      // so the rendered href could change while the key did not. Carry the\n      // baked pair SEPARATELY (never folded into the label, which must stay\n      // resolvable by `resolveLinkDef` so a canonical change is still\n      // tracked) — the same argument that put `footnote-sup`'s occurrence in\n      // the footprint; link/image were left asymmetric (oracle review, 2.5.0).\n      if (typeof props.localUrl === 'string') {\n        bakedDefs.push([label, props.localUrl, typeof props.localTitle === 'string' ? props.localTitle : null]);\n      }\n      return;\n    }\n    // Standalone mode bakes footnote numbering into plain marks; their ctx\n    // is the whole-document globalCtx, so the flag alone is enough.\n    if (node.tagName === 'a' && props.dataFootnoteRef !== undefined) hasReference = true;\n  });\n  return { hasReference, refLabels, linkLabels, imageLabels, local, bakedDefs, hasFootnoteSection };\n}\n","import type { Root as MdastRoot, RootContent as MdastNode } from 'mdast';\nimport type { Root as HastRoot } from 'hast';\nimport { visit } from 'unist-util-visit';\nimport { buildBlocks, type BuildBlocksOptions, type BuildBlocksResult, type RenderItem } from './blockPlan';\n\nconst UNPAIRED_TYPES = new Set(['html', 'definition', 'footnoteDefinition']);\n\n/** Reuse the engine's retained prefix plans, including reference blocks.\n * Reference prefixes require full-document context when planning the tail.\n * Raw HTML and definition regions retain complete planning: their ownership\n * need not be one-to-one. Identity checks, not source-text\n * guesses, establish which trees the incremental engine actually retained.\n * Top-level traversal remains O(blocks); reference context still visits the\n * full mdast when needed, while per-block HAST planning is tail-only. */\nexport function createBlockPlanner() {\n  let previous:\n    | {\n        mdast: MdastRoot;\n        hast: HastRoot;\n        source: string;\n        result: BuildBlocksResult;\n        phantoms: BuildBlocksOptions['phantomFootnoteLabels'];\n      }\n    | undefined;\n  const eligible = new WeakMap<MdastNode, boolean>();\n  const isEligible = (node: MdastNode) => {\n    let result = eligible.get(node);\n    if (result === undefined) {\n      result = true;\n      visit(node, (child) => {\n        if (UNPAIRED_TYPES.has(child.type)) result = false;\n      });\n      eligible.set(node, result);\n    }\n    return result;\n  };\n  return (mdast: MdastRoot, hast: HastRoot, source: string, options: BuildBlocksOptions = {}): BuildBlocksResult => {\n    let m = 0;\n    let h = 0;\n    let reusedContext = false;\n    if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {\n      while (m < mdast.children.length) {\n        const node = mdast.children[m];\n        const el = hast.children[h];\n        const item = previous.result.plan[h];\n        if (\n          node !== previous.mdast.children[m] ||\n          el !== previous.hast.children[h] ||\n          !el ||\n          el.type !== 'element' ||\n          !item ||\n          item.kind !== 'block' ||\n          item.info.startOffset !== node.position?.start.offset ||\n          !isEligible(node)\n        )\n          break;\n        reusedContext ||= item.info.hasReference;\n        m++;\n        h++;\n        while (h < hast.children.length) {\n          const gap = hast.children[h];\n          if (gap !== previous.hast.children[h] || gap.type !== 'text' || /\\S/.test(gap.value)) break;\n          h++;\n        }\n      }\n    }\n    let result: BuildBlocksResult;\n    if (m > 0 && previous) {\n      const tail = buildBlocks(\n        { ...mdast, children: mdast.children.slice(m) },\n        { ...hast, children: hast.children.slice(h) },\n        source,\n        reusedContext ? { ...options, contextMdast: options.contextMdast ?? mdast } : options\n      );\n      const prefix = previous.result.plan.slice(0, h);\n      const prefixBlocks = prefix.filter(\n        (item): item is Extract<RenderItem, { kind: 'block' }> => item.kind === 'block'\n      );\n      result = {\n        ...tail,\n        plan: [\n          ...prefix,\n          ...tail.plan.map((item) =>\n            /^inline-i\\d+$/.test(item.key) ? { ...item, key: `inline-i${Number(item.key.slice(8)) + h}` } : item\n          ),\n        ],\n        blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],\n        blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts],\n      };\n    } else result = buildBlocks(mdast, hast, source, options);\n    previous = { mdast, hast, source, result, phantoms: options.phantomFootnoteLabels };\n    return result;\n  };\n}\n","import type { Root as MdastRoot } from 'mdast';\nimport type { Root as HastRoot, ElementContent as HastElementContent } from 'hast';\nimport { extractContributions, extractDefBodiesFromHast, type RegistryInternal } from '@ai-react-markdown/engine';\n\nexport interface ContributionOptions {\n  pipeline: { mdast: MdastRoot; hast: HastRoot };\n  ownLabels: { footnoteLabels: Set<string>; linkLabels: Set<string> };\n  registry: RegistryInternal | null;\n  targetPhantoms: { missingFootnotes: Set<string>; missingLinks: Set<string> };\n  sym: symbol | null;\n  clobberPrefix: string;\n  /** Stable identity tuple of parse inputs. Source equality alone cannot\n   * validate definition bodies after a plugin or schema change. */\n  chain: readonly unknown[];\n}\n\n/** Create one contribution publisher per mounted chunk.\n * Call commit only in the host's commit/effect phase, after registration.\n * Constructing a session does not register or publish anything. A discarded\n * render must never call commit. The host owns registration and cleanup.\n */\nexport function createContributionSession() {\n  let lastContribution: {\n    registry: RegistryInternal;\n    symbol: symbol;\n    fp: string;\n    chain: readonly unknown[];\n  } | null = null;\n  return {\n    commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }: ContributionOptions): void {\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      // Link-definition URLs enter the registry RAW: the render-time\n      // `resolveCrossChunkReference` gate in the placeholders is the single point\n      // of enforcement (schema + hash rebasing + urlTransform, per attribute\n      // key). A contribute-time pre-pass used to collapse a blocked URL to ''\n      // — indistinguishable from a legal empty destination — and applied a\n      // rewriting urlTransform twice (v2.4.2 review P1-4).\n      for (const node of extractContributions(pipeline.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      const last = lastContribution;\n      if (\n        last?.registry === registry &&\n        last.symbol === sym &&\n        last.fp === fp &&\n        last.chain.length === chain.length &&\n        last.chain.every((dep, i) => dep === chain[i])\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(pipeline.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      lastContribution = { registry, symbol: sym, fp, chain };\n      registry.contributeChunkData(sym, {\n        refs,\n        defs,\n        linkDefs,\n        ownFootnoteLabels: ownLabels.footnoteLabels,\n        ownLinkLabels: ownLabels.linkLabels,\n      });\n    },\n  };\n}\n","/**\n * Turn-taking coordinator for smooth-streaming chunks that share a\n * `documentId` under `<AIMarkdownDocuments>`.\n *\n * Each `useDocumentSmoothStream` chunk registers here in mount order and\n * reports a sticky `done` (source stopped AND reveal drained). A chunk that\n * mounted with empty content stays gated until every REGISTERED chunk\n * earlier in the order is done — so the chunks read as one typewriter:\n * chunk N reveals completely, then chunk N+1 starts.\n *\n * The structure deliberately mirrors `documentRegistry`'s proven patterns\n * (chunkId-keyed refcount with microtask-deferred reclaim for Strict Mode,\n * monotonic version + microtask-coalesced subscriber fanout, `onEmpty`\n * container eviction) without touching the registry itself: the def\n * registry and this coordinator share only the `documentId` scope. Chunks\n * that never register (non-smooth chunks, opted-out chunks) simply do not\n * exist here and can never block a successor; an unmounting chunk leaves\n * the order, so a virtualized-away predecessor releases its successors by\n * construction.\n *\n * `lastProgressAt` is the reveal-progress heartbeat behind the dev-only\n * stuck-flag warning. Writes to it intentionally do NOT bump `version` and\n * do NOT fan out — stamping happens once per reveal frame, and a fanout to\n * every sibling chunk per frame would be a performance bug. Nothing\n * subscribes to it; the pending chunk's warning timer reads it on demand.\n *\n * @module components/smoothStream/coordinator\n */\n\nexport interface SmoothCoordinator {\n  /** Chunk mount-order chunkId list. **Read-only** — mutation corrupts the\n   *  release predicate for every successor. */\n  readonly order: readonly string[];\n  /** Chunk IDs that have reported done. Sticky: entries are only removed\n   *  when the chunk unregisters. **Read-only.** */\n  readonly done: ReadonlySet<string>;\n  /** Reveal-progress heartbeat, ms timestamps from the reporting chunk's\n   *  clock. Written WITHOUT a version bump (see module doc). */\n  readonly lastProgressAt: ReadonlyMap<string, number>;\n  /** Monotonic counter bumped by every gating-relevant mutation\n   *  (register / unregister / done transition). */\n  readonly version: number;\n\n  subscribe(cb: () => void): () => void;\n\n  /** Allocate (or refcount-reuse, for Strict Mode remounts) this chunk's\n   *  slot at the current end of the mount order. */\n  register(chunkId: string): void;\n  /** Refcount decrement with microtask-deferred reclaim; the last release\n   *  removes the chunk from the order (waking successors) and, when the\n   *  coordinator empties, fires the container's `onEmpty`. */\n  release(chunkId: string): void;\n  /** Sticky, idempotent: the first call per chunk bumps the version; the\n   *  transition is never retracted while the chunk stays mounted (a\n   *  predecessor that un-finishes must not re-gate successors). */\n  markDone(chunkId: string): void;\n  /** Heartbeat stamp — no version bump, no fanout. */\n  stampProgress(chunkId: string, at: number): void;\n  /** True when every registered chunk BEFORE `chunkId` in the order has\n   *  reported done. Unregistered predecessors don't exist here, so they\n   *  never block. A `chunkId` that is not (yet) registered itself is\n   *  treated as sitting AFTER every registered chunk — a pre-registration\n   *  query must not release a chunk whose predecessors are still\n   *  revealing. */\n  isReleased(chunkId: string): boolean;\n  /** The earliest not-done registered chunk before `chunkId`, or null.\n   *  Read by the dev-only stuck-flag warning timer. */\n  earliestBlockerOf(chunkId: string): string | null;\n}\n\n/** Widened internal view (parallel to `RegistryInternal`): implementation-\n *  private fields, exported for tests but not from the package barrel. */\nexport interface SmoothCoordinatorInternal extends SmoothCoordinator {\n  _refcounts: Map<string, number>;\n  _subscribers: Set<() => void>;\n  _notifyScheduled: boolean;\n  _notify(): void;\n}\n\n/**\n * Construct a coordinator. `onEmpty` fires synchronously from inside the\n * deferred-release microtask when the last chunk just left, so the\n * container can evict its `documentId → coordinator` map entry while the\n * state is quiescent (same contract as the registry's `onEmpty`).\n */\nexport function createSmoothCoordinator(onEmpty?: () => void): SmoothCoordinatorInternal {\n  const order: string[] = [];\n  const done = new Set<string>();\n  const lastProgressAt = new Map<string, number>();\n\n  const coord: SmoothCoordinatorInternal = {\n    order,\n    done,\n    lastProgressAt,\n    version: 0,\n    _refcounts: new Map(),\n    _subscribers: new Set(),\n    _notifyScheduled: false,\n\n    register(chunkId: string): void {\n      const count = this._refcounts.get(chunkId) ?? 0;\n      this._refcounts.set(chunkId, count + 1);\n      if (count === 0 && !order.includes(chunkId)) {\n        order.push(chunkId);\n        this._notify();\n      }\n    },\n\n    release(chunkId: string): void {\n      const count = this._refcounts.get(chunkId);\n      if (count === undefined) return;\n      if (count > 1) {\n        this._refcounts.set(chunkId, count - 1);\n        return;\n      }\n      this._refcounts.set(chunkId, 0);\n      queueMicrotask(() => {\n        if (this._refcounts.get(chunkId) !== 0) return; // Strict Mode revived it\n        this._refcounts.delete(chunkId);\n        const idx = order.indexOf(chunkId);\n        if (idx !== -1) order.splice(idx, 1);\n        done.delete(chunkId);\n        lastProgressAt.delete(chunkId);\n        // Successors gated behind this chunk may now be releasable.\n        this._notify();\n        if (order.length === 0 && onEmpty) onEmpty();\n      });\n    },\n\n    markDone(chunkId: string): void {\n      if (done.has(chunkId)) return; // idempotent — repeat reports don't bump version\n      done.add(chunkId);\n      this._notify();\n    },\n\n    stampProgress(chunkId: string, at: number): void {\n      lastProgressAt.set(chunkId, at);\n    },\n\n    isReleased(chunkId: string): boolean {\n      for (const id of order) {\n        if (id === chunkId) return true;\n        if (!done.has(id)) return false;\n      }\n      // Not registered (yet): treated as after every registered chunk, so\n      // reaching here means all of them are done.\n      return true;\n    },\n\n    earliestBlockerOf(chunkId: string): string | null {\n      for (const id of order) {\n        if (id === chunkId) return null;\n        if (!done.has(id)) return id;\n      }\n      return null;\n    },\n\n    subscribe(cb: () => void): () => void {\n      this._subscribers.add(cb);\n      return () => {\n        this._subscribers.delete(cb);\n      };\n    },\n\n    _notify(): void {\n      (this as { version: number }).version++;\n      if (this._notifyScheduled) return;\n      this._notifyScheduled = true;\n      queueMicrotask(() => {\n        this._notifyScheduled = false;\n        for (const cb of [...this._subscribers]) cb();\n      });\n    },\n  };\n  return coord;\n}\n\n/** Outcome of one stuck-flag warning timer firing (dev-only diagnostics). */\nexport type GateWarnVerdict = 'warn' | 'rearm' | 'clear';\n\n/**\n * The warn / re-arm / clear decision behind the dev-only stuck-flag\n * warning, extracted as a pure function so the judgment is unit-testable\n * in node — the `setTimeout` wiring in `useDocumentSmoothStream` reduces\n * to \"call this when the timer fires\".\n *\n * - `'clear'`: no blocker left — the release is propagating; stop.\n * - `'rearm'`: the earliest blocker showed reveal progress within the\n *   threshold — a slow model still emitting, not a stuck flag; check\n *   again later.\n * - `'warn'`: the blocker has made no visible progress for a full\n *   threshold while this chunk stayed gated — the predecessor's\n *   `streaming` flag is likely stuck.\n */\nexport function evaluateGateWarn(\n  coordinator: SmoothCoordinator,\n  chunkId: string,\n  nowMs: number,\n  thresholdMs: number\n): GateWarnVerdict {\n  const blocker = coordinator.earliestBlockerOf(chunkId);\n  if (!blocker) return 'clear';\n  const progressedAt = coordinator.lastProgressAt.get(blocker) ?? 0;\n  return nowMs - progressedAt < thresholdMs ? 'rearm' : 'warn';\n}\n","/**\n * Source-tail classification for the streaming cursor.\n *\n * The cursor's DOM walk cannot know whether the source tail is in the body\n * or inside a footnote definition — mdast-util-to-hast relocates every\n * definition into the synthetic end-of-document footer, decoupling the\n * footer's DOM position from source position. This module answers the\n * question at the mdast level, where micromark has already made every\n * grammar decision (lazy continuation lines, container nesting, blank-line\n * attachment, label escapes): the renderer derives a signal per frame from\n * the tree it is about to render and stamps it on a DOM marker the cursor\n * shell reads in the same commit.\n *\n * Deliberately NOT a text scan of the trailing lines: a hand-rolled\n * back-walk would be a third parallel grammar in the repo and provably\n * mis-classifies lazy continuations (`[^1]: line\\nline2` keeps line2 in\n * the definition with zero indentation), resurfacing the exact bug this\n * exists to fix.\n *\n * @module components/streamingCursor/tailSignal\n */\n\nimport type { Parent, Root, RootContent } from 'mdast';\n\nexport type TailSignal =\n  /** The source tail is inside a footnote definition — its text renders in\n   *  the footnote footer's `<li>` for `identifier` (mdast's case-folded\n   *  form), not at the body tail. */\n  | { kind: 'footnote-def'; identifier: string }\n  /** The source tail is inside a link-reference definition — it renders\n   *  nothing at all; the cursor should hide rather than point at stale\n   *  body text. */\n  | { kind: 'invisible-def' }\n  /** The source tail is ordinary body content — the DOM-tail heuristic is\n   *  correct as-is. */\n  | null;\n\n/** Node types the descent passes THROUGH looking for the tail definition.\n *  Definitions legally nest inside all of these (`> [^a]: x`,\n *  `- [^a]: x`, and a def inside another def's body), and their rendered\n *  text still relocates to the footer — so the descent is required for\n *  correctness, not an optimization. Nothing else can contain a def. */\nconst DESCEND_THROUGH = new Set(['blockquote', 'list', 'listItem', 'footnoteDefinition']);\n\n/**\n * Classify the source tail of `mdast`.\n *\n * @param mdast - The tree the renderer is about to render (post-pipeline\n *   parse output; the incremental path's spliced tree carries correct\n *   positions on real nodes).\n * @param contentLength - Length of the PREPROCESSED content string the\n *   renderer parsed (not the caller's raw prop). Phantom definitions are\n *   injected as an appended suffix before parsing, so every node whose\n *   start offset sits at or past the real content's end is a phantom — the\n *   scan walks backwards past ALL of them (a real trailing def plus\n *   several phantoms is a normal shape) and classifies the first real\n *   node.\n */\nexport function deriveTailSignal(mdast: Root, contentLength: number): TailSignal {\n  const children = mdast.children;\n  let index = children.length - 1;\n  while (index >= 0) {\n    const offset = children[index].position?.start?.offset;\n    if (offset !== undefined && offset >= contentLength) {\n      index--;\n      continue;\n    }\n    break;\n  }\n  if (index < 0) return null;\n\n  let node: RootContent = children[index];\n  let deepestFootnoteDef: { identifier: string } | null = null;\n  for (;;) {\n    if (node.type === 'footnoteDefinition') deepestFootnoteDef = node;\n    if (node.type === 'definition') {\n      // A link-reference definition renders nothing wherever it sits —\n      // including as the last child of a footnote definition's body.\n      return { kind: 'invisible-def' };\n    }\n    if (!DESCEND_THROUGH.has(node.type)) break;\n    const kids = (node as Parent).children;\n    if (!kids || kids.length === 0) break;\n    node = kids[kids.length - 1] as RootContent;\n  }\n  // The DEEPEST definition on the last-child chain is where text is\n  // streaming (a def nested in another def's body renders in ITS OWN li).\n  return deepestFootnoteDef ? { kind: 'footnote-def', identifier: deepestFootnoteDef.identifier } : null;\n}\n","/** Assemble document footnotes as HAST without framework nodes or DOM access. */\nimport type { Element as HastElement, ElementContent as HastElementContent } from 'hast';\nimport { footnoteSafeId, lastMeaningfulIdx, type Registry } from '@ai-react-markdown/engine';\nimport { cloneHastForRender } from './cloneHastForRender';\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\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\nexport function 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    // Same id encoding as mdast-util-to-hast's footer / the marks (percent-\n    // encoded non-ASCII etc.); `sourceIdFromFootnoteLiId` decodes it on the\n    // way back, so the harvest and the cursor anchor keep working.\n    const safeId = footnoteSafeId(sourceIdentifier);\n    // Assembly-time clone: the backref logic below pushes anchors into these\n    // children, which must never mutate the registry-held `bodyHast`.\n    const liChildren = bodyHast.map((c) => cloneHastForRender(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 = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${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-${safeId}`,\n        // Stringified: @types/hast (≥3.0.5) types li's `value` as string;\n        // React serializes value={3} and value=\"3\" to identical markup.\n        ...(n !== null ? { value: String(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","/**\n * Structural clone of a hast subtree for render-time use.\n *\n * Copies exactly what the render-time mutators touch — every node object,\n * its `children` array (the allow/disallow filters splice it), and its\n * `properties` object (`urlTransform` overwrites `href`/`src`) — while\n * SHARING `position`, `data`, string values, and individual property values\n * by reference. This is both cheaper than a JSON round-trip (no string\n * intermediate; `position` objects, typically over half of a serialized\n * hast, are never materialized) and exact for any tree the pipeline\n * produces (no lossy JSON semantics to reason about).\n *\n * @module components/cloneHastForRender\n */\n\nimport type { Nodes as HastNodes } from 'hast';\n\n/** See module docs. Safe for any hast node union member. */\nexport function cloneHastForRender<T extends HastNodes>(node: T): T {\n  const copy = { ...node } as T;\n  const withChildren = copy as { children?: HastNodes[] };\n  if (Array.isArray(withChildren.children)) {\n    withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));\n  }\n  const withProperties = copy as { properties?: Record<string, unknown> };\n  if (withProperties.properties) {\n    withProperties.properties = { ...withProperties.properties };\n  }\n  return copy;\n}\n","/** Per-consumer parse state and full/incremental fallback policy.\n * The host decides whether a next frame is expected (false for SSR), owns\n * this session, and resets it when render policy invalidates retained trees.\n * Parsing does not register chunks or publish document contributions.\n */\nimport {\n  advanceIncrementalParse,\n  buildPhantomSuffix,\n  phantomSuffixCloser,\n  parseStage,\n  transformStage,\n  type IncrementalParseState,\n  type PipelineOptions,\n  type AdvanceOptions,\n} from '@ai-react-markdown/engine';\n\ntype RemarkRehypeOptions = NonNullable<PipelineOptions['remarkRehypeOptions']>;\nexport interface PipelineFrameOptions {\n  content: string;\n  targetPhantoms: { missingFootnotes: Set<string>; missingLinks: Set<string> };\n  remarkPlugins: PipelineOptions['remarkPlugins'];\n  rehypePlugins: PipelineOptions['rehypePlugins'];\n  remarkRehypeOptions: PipelineOptions['remarkRehypeOptions'];\n  handlers?: RemarkRehypeOptions['handlers'];\n  preserveForBodyHarvest: boolean;\n  documentId: string;\n  provenance: string;\n  /** False for a one-shot server render; no browser-global probe is needed. */\n  incrementalParse: boolean;\n  defListEnabled: boolean;\n  measure?: AdvanceOptions['measure'];\n}\nconst unmeasured: NonNullable<AdvanceOptions['measure']> = (_stage, fn) => fn();\n\nexport function createPipelineSession() {\n  let state: IncrementalParseState | null = null;\n  return {\n    reset(): void {\n      state = null;\n    },\n    parse({\n      content,\n      targetPhantoms,\n      remarkPlugins,\n      rehypePlugins,\n      remarkRehypeOptions,\n      handlers,\n      preserveForBodyHarvest,\n      documentId,\n      provenance,\n      incrementalParse,\n      defListEnabled,\n      measure: measureHere = unmeasured,\n    }: PipelineFrameOptions) {\n      // The suffix is APPENDED (the engine treats it as an always-tail\n      // input; prepending would shift every source position). A frame that\n      // ends inside an open fence / `$$` block would swallow it — sentinel\n      // lines rendered as code, every cross-chunk ref falling back to\n      // literal text for the block's whole streaming lifetime — so the\n      // engine first emits an output-neutral closer for that block (see\n      // phantomSuffixCloser; '' when nothing is open or the phase is\n      // untrusted). Only chunks with a non-empty suffix pay the line scan.\n      const phantomDefs = buildPhantomSuffix(targetPhantoms);\n      const phantomSuffix = phantomDefs === '' ? '' : phantomSuffixCloser(content ?? '') + phantomDefs;\n      const augmented = (content ?? '') + phantomSuffix;\n      const baseHandlers = remarkRehypeOptions?.handlers ?? {};\n      const mergedRemarkRehypeOptions = (\n        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              // The SAME value `buildCoreRehypePlugins` received — the\n              // verifier unwraps every placeholder stamped with anything else.\n              provenance,\n            }\n          : {\n              ...remarkRehypeOptions,\n            }\n      ) as RemarkRehypeOptions;\n\n      // Coordinated (registry) mode is incremental-eligible since v2: the\n      // engine takes the phantom suffix as a separate always-tail input (its\n      // frame-to-frame churn re-parses only the tail — the reference taint\n      // keeps every phantom-resolved ref out of the frozen prefix), and the\n      // contribute effect's inputs are covered by splice equivalence (mdast)\n      // plus the replay-regenerated footer (hast). When the flag is off, the\n      // state is CLEARED — a later eligible frame must never splice against\n      // trees parsed under different conditions.\n      //\n      // SSR takes this branch too: the engine's first-frame scan exists to\n      // seed the NEXT frame's checkpoint, and a per-request server render\n      // has no next frame — routing through the engine would pay a dead\n      // O(document) line-lex per request. Hydration is unaffected (the\n      // client's first frame rebuilds from null either way).\n      if (!incrementalParse) {\n        state = null;\n        // Dev-only stage telemetry (`ai-markdown:stage:*` performance\n        // measures; no-op in production). Wraps only the stage calls — the\n        // surrounding option assembly is trivial.\n        const parsed = measureHere('parse', () =>\n          parseStage({\n            children: augmented,\n            remarkPlugins,\n            rehypePlugins,\n            remarkRehypeOptions: mergedRemarkRehypeOptions,\n          })\n        );\n        const hastRoot = measureHere('transform', () => transformStage(parsed));\n        return { mdast: parsed.mdast, hast: hastRoot };\n      }\n\n      try {\n        const result = advanceIncrementalParse(state, content ?? '', {\n          remarkPlugins,\n          rehypePlugins,\n          remarkRehypeOptions: mergedRemarkRehypeOptions,\n          // Identity tuple over every parse input beyond the content itself.\n          // Deliberately covers MORE than the G3 flush's 12 fields (handlers /\n          // preserveForBodyHarvest / documentId can change without touching\n          // any G3 field — e.g. a `preserveOrphanReferences` flip). The\n          // phantom label sets are deliberately NOT here: their churn tracks\n          // the suffix (always re-parsed with the tail), never the prefix.\n          depsKey: [\n            remarkPlugins,\n            rehypePlugins,\n            remarkRehypeOptions,\n            handlers,\n            preserveForBodyHarvest,\n            documentId,\n            // Explicit even though `rehypePlugins` already carries it: a\n            // credential change must never reuse trees stamped under the\n            // old one.\n            provenance,\n          ],\n          defListEnabled,\n          phantomSuffix,\n          measure: measureHere,\n        });\n        state = result.nextState;\n        return { mdast: result.mdast, hast: result.hast };\n      } catch (error) {\n        // The engine mutates prev's scan checkpoint IN PLACE before the tail\n        // parse/splice — a throw mid-frame (an engine bug, or a plugin\n        // choking on the synthetic tail source) leaves the retained state's\n        // checkpoint describing content the state's trees do not. Clearing\n        // the ref restores the \"state is CLEARED when unusable\" discipline;\n        // the frame then renders via the ordinary full pipeline so one bad\n        // frame cannot take the surface down.\n        state = null;\n        if (process.env.NODE_ENV !== 'production') {\n          console.error('[ai-react-markdown] incremental parse failed — full parse fallback for this frame:', error);\n        }\n        const parsed = measureHere('parse', () =>\n          parseStage({\n            children: augmented,\n            remarkPlugins,\n            rehypePlugins,\n            remarkRehypeOptions: mergedRemarkRehypeOptions,\n          })\n        );\n        const hastRoot = measureHere('transform', () => transformStage(parsed));\n        return { mdast: parsed.mdast, hast: hastRoot };\n      }\n    },\n  };\n}\n","/** Shared decisions only: no registration, subscriptions or publication.\n * Previous outputs are optional identity hints owned by one host consumer.\n * Input label sets and returned objects must be treated as immutable snapshots.\n */\nimport { buildCrossChunkHandlers, normalizeForMatch } from '@ai-react-markdown/engine';\nimport type { PipelineFrameOptions } from './pipelineSession';\n\nexport interface DefinitionLabels {\n  footnoteLabels: ReadonlySet<string>;\n  linkLabels: ReadonlySet<string>;\n}\nexport type PhantomTargets = PipelineFrameOptions['targetPhantoms'];\n\nexport function derivePhantomTargets(\n  { content, ownLabels, labels }: { content: string; ownLabels: DefinitionLabels; labels: DefinitionLabels | null },\n  previous?: PhantomTargets\n): PhantomTargets {\n  const missingFootnotes = new Set<string>();\n  const missingLinks = new Set<string>();\n  if (labels) {\n    const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));\n    const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));\n    // Avoid two full-content normalization passes when there are no candidates.\n    if (footnotes.length || links.length) {\n      const normalized = normalizeForMatch(content);\n      for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);\n      for (const label of links) if (normalized.includes(label)) missingLinks.add(label);\n    }\n  }\n  if (\n    previous &&\n    missingFootnotes.size === previous.missingFootnotes.size &&\n    missingLinks.size === previous.missingLinks.size &&\n    [...missingFootnotes].every((label) => previous.missingFootnotes.has(label)) &&\n    [...missingLinks].every((label) => previous.missingLinks.has(label))\n  )\n    return previous;\n  return { missingFootnotes, missingLinks };\n}\n\nexport interface CoordinationPolicy {\n  mode: 'coordinated' | 'orphan' | 'standalone';\n  handlers: PipelineFrameOptions['handlers'];\n  preserveForBodyHarvest: boolean;\n}\n\nexport function deriveCoordinationPolicy(\n  {\n    coordinated,\n    registered,\n    preserveOrphanReferences,\n  }: {\n    coordinated: boolean;\n    registered: boolean;\n    /** The host has already resolved any wrapper-level override. */\n    preserveOrphanReferences: boolean;\n  },\n  previous?: CoordinationPolicy\n): CoordinationPolicy {\n  const mode = coordinated ? 'coordinated' : preserveOrphanReferences ? 'orphan' : 'standalone';\n  const preserveForBodyHarvest = preserveOrphanReferences || (coordinated && registered);\n  if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;\n  // Registration can change body harvesting without changing handler identity.\n  const handlers =\n    previous?.mode === mode\n      ? previous.handlers\n      : mode === 'coordinated'\n        ? buildCrossChunkHandlers()\n        : mode === 'orphan'\n          ? { footnoteDefinition: buildCrossChunkHandlers().footnoteDefinition }\n          : undefined;\n  return { mode, handlers, preserveForBodyHarvest };\n}\n\nexport type ContributionPolicyInputs = Pick<\n  PipelineFrameOptions,\n  | 'remarkPlugins'\n  | 'rehypePlugins'\n  | 'remarkRehypeOptions'\n  | 'handlers'\n  | 'preserveForBodyHarvest'\n  | 'documentId'\n  | 'provenance'\n> & { clobberPrefix: string };\n\n/** Source/phantom/registry/symbol changes are compared by the publisher itself.\n * This tuple covers the remaining inputs that can alter harvested bodies.\n */\nexport function buildContributionChain(inputs: ContributionPolicyInputs): readonly unknown[] {\n  return [\n    inputs.remarkPlugins,\n    inputs.rehypePlugins,\n    inputs.remarkRehypeOptions,\n    inputs.handlers,\n    inputs.preserveForBodyHarvest,\n    inputs.clobberPrefix,\n    inputs.documentId,\n    inputs.provenance,\n  ];\n}\n","/**\n * Internal barrel for the local Markdown wrapper. Not re-exported from the\n * core package's public entrypoint — callers should keep going through\n * `<AIMarkdown>`.\n *\n * @module components/markdown\n */\n\nexport { default, Markdown, renderHastSubtree } from './Markdown';\nexport { parseStage, transformStage, type ParsedMarkdown } from '@ai-react-markdown/engine';\nexport { defaultUrlTransform } from '@ai-react-markdown/engine';\nexport type { AllowElement, Components, Deprecation, ExtraProps, Options, UrlTransform } from './types';\n","/** React node caching for the framework-neutral runtime block plan.\n * Planning and fingerprints are shared; ReactNode ownership and JSX conversion\n * remain local to each renderer. See packages/runtime/README.md.\n */\nimport type { Element as HastElement } from 'hast';\nimport type { ReactNode } from 'react';\nimport type { Registry } from '@ai-react-markdown/engine';\nimport { renderHastSubtree, type Options } from './markdown';\nimport {\n  isFootnoteSection,\n  hasMdastSource,\n  computeBlockFingerprint,\n  type RenderItem,\n} from '@ai-react-markdown/runtime';\nexport {\n  buildBlocks,\n  isFootnoteSection,\n  hasMdastSource,\n  computeHtmlBlockDigest,\n  computeHtmlBlockDigestWithExtent,\n  computeBlockFingerprint,\n} from '@ai-react-markdown/runtime';\nexport type { BlockInfo, RenderItem, BuildBlocksOptions, BuildBlocksResult } from '@ai-react-markdown/runtime';\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 the document context; entered\n   *  into fingerprint so id/href prefix changes invalidate the cache. */\n  clobberPrefix?: string;\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  /** Mirrors {@link BlockInfo.hastDigest} — must match for raw-HTML blocks\n   *  (undefined === undefined for markdown-native blocks). */\n  hastDigest?: string;\n  /** Whether the cached node was rendered with the swallowed footnote\n   *  section STRIPPED (coordinated mode). Without it in the key the strip\n   *  decision is only correct by accident — it happens to co-vary with\n   *  `blockCtx` today through a three-link chain (section ⇒ hasReference ⇒\n   *  fingerprint path, and a non-empty clobberPrefix). Break any link and a\n   *  cached unstripped node would serve after registration: two\n   *  `<section data-footnotes>` with colliding li ids (oracle review, 2.5.0). */\n  strippedFootnoteSection?: boolean;\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/** A single rendered output item with its stable React key. */\nexport interface RenderedItem {\n  node: ReactNode;\n  key: string;\n}\n\n/** A shallow-cloned copy of `el` with any `<section data-footnotes>` in its\n *  subtree removed (see {@link BlockInfo.containsFootnoteSection}). Only the\n *  spine down to each removed node is cloned; every other child keeps its\n *  identity so untouched subtrees stay reference-equal. */\nfunction withoutFootnoteSection(el: HastElement): HastElement {\n  const prune = (node: HastElement): HastElement => {\n    const kids = node.children;\n    let changed = false;\n    const next: typeof kids = [];\n    for (const child of kids) {\n      if (child.type === 'element') {\n        if (isFootnoteSection(child)) {\n          changed = true;\n          continue;\n        }\n        const pruned = prune(child);\n        if (pruned !== child) changed = true;\n        next.push(pruned);\n        continue;\n      }\n      next.push(child);\n    }\n    // `data` must be SHARED with the original, not left undefined on the\n    // clone: `buildTransform` stashes the pre-transform URL on\n    // `element.data.originalUrls` and recomputes from it, which is what makes\n    // urlTransform convergent across re-renders (see the contract note in\n    // markdown/Markdown.tsx). With a plain `{...node}` the `data ??= {}` lands\n    // on the throwaway clone, the stash dies with it, and the next frame reads\n    // the ALREADY-transformed value as the original — a non-idempotent\n    // transform compounds (`/x` → `/x?t` → `/x?t?t`). Oracle review of 2.5.0.\n    return changed ? { ...node, data: (node.data ??= {}), children: next } : node;\n  };\n  return prune(el);\n}\n\n/** Placeholder tags the coordinated pipeline bakes chunk-local facts into. */\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, position triple, hastDigest)`. ctx == globalCtx for tainted blocks, ''\n * otherwise (sentinel collapses both paths into one validation). hastDigest\n * is undefined for markdown-native blocks (undefined === undefined passes)\n * and a subtree digest for raw-HTML blocks, so containers that swallowed\n * following siblings mid-stream re-render when the swallowed extent changes.\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: item.el.type === 'text' ? item.el.value : renderHastSubtree(item.el, postOptions),\n        key: item.key,\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 — and the placeholders fall back to the same standalone facts\n      // (local footnote number, own link def) in exactly this state, so the\n      // static output of a wrapped chunk is byte-identical to its standalone\n      // render (pinned in `byteEquivalence.test.tsx`), which is what users\n      // 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, key: item.key });\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    // Same coordinated-mode test as the top-level synthetic skip above\n    // (registry + a registered chunk Symbol): under SSR the chunk has not\n    // registered yet and the local footer is the right output.\n    const stripSection = Boolean(block.containsFootnoteSection && postOptions.registry && postOptions.thisChunkSymbol);\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        entry.hastDigest === block.hastDigest &&\n        Boolean(entry.strippedFootnoteSection) === stripSection;\n\n      let node: ReactNode;\n      if (valid) {\n        node = entry.node; // cache hit: skip everything\n      } else {\n        // The aggregate footer (AggregateFootnotesIfLast) reconstructs the\n        // footnote section from registry state, and the synthetic plan item\n        // for a TOP-LEVEL `<section data-footnotes>` is skipped earlier in\n        // this loop. A raw-HTML container that swallowed the section is the\n        // one case where it is not top level — strip it here, or the\n        // document renders the local footer inside the container AND the\n        // aggregate one (colliding li ids; r2 P2-9). Standalone renders keep\n        // it where the full parse puts it.\n        node = renderHastSubtree(stripSection ? withoutFootnoteSection(item.el) : 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        hastDigest: block.hastDigest,\n        strippedFootnoteSection: stripSection,\n      });\n      rendered.push({ node, key: item.key });\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        entry.hastDigest === block.hastDigest &&\n        Boolean(entry.strippedFootnoteSection) === stripSection;\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        hastDigest: block.hastDigest,\n        strippedFootnoteSection: stripSection,\n      });\n      rendered.push({ node, key: item.key });\n    }\n  }\n\n  cacheRef.current = next;\n  return rendered;\n}\n","/**\n * Per-pipeline provenance credential for the engine's placeholder elements.\n *\n * `<AIMarkdownContent>` creates ONE credential per mounted instance (a\n * null-sentinel `useRef`, never `useRef(createCredential())`, which would\n * evaluate its argument on every render) and hands the same string to two\n * places: the remark-rehype options, where the cross-chunk handlers stamp it\n * on every placeholder they emit, and `buildCoreRehypePlugins`, which\n * installs `rehypeVerifyEngineTags` to unwrap any placeholder without it.\n * The verifier deletes the property before anything downstream sees the\n * tree, so the value never reaches the DOM, caches or logs.\n *\n * Two defence layers (see `rehypeVerifyEngineTags` in the engine):\n * 1. the property NAME — authored raw HTML comes back from the tokenizer\n *    lowercased and cannot produce `engineProvenance` at all; this layer\n *    needs nothing from the runtime;\n * 2. the VALUE — 128 random bits from Web Crypto, so that a future upstream\n *    change preserving authored attribute case would still leave the value\n *    to guess.\n *\n * Without Web Crypto (no supported runtime lacks it — `engines.node >= 20`,\n * every browser since 2014 — but the repository declares no browser floor\n * and the credential is created before coordinated mode is known, so\n * throwing here would break plain standalone rendering) layer 2 degrades to\n * a unique non-secret value and layer 1 keeps holding: the verifier still\n * runs, forged instances are still unwrapped, nothing is silently lost. One\n * dev-only diagnostic per credential that fell back — i.e. per retained\n * mount — and none in production.\n *\n * @module components/provenance\n */\nimport { useState } from 'react';\n\nexport interface ProvenanceCredential {\n  /** The string stamped on placeholders and checked by the verifier. */\n  value: string;\n  /** Whether `value` came from a CSPRNG. `false` only on the fallback path. */\n  secret: boolean;\n}\n\n/** Diagnostic text for the fallback path. Kept as one constant so the\n *  build-aware production gate (`scripts/assert-prod-diagnostic-inert.mjs`)\n *  can look for exactly this. */\nexport const PROVENANCE_FALLBACK_MESSAGE =\n  'Web Crypto (globalThis.crypto.getRandomValues) is unavailable; the cross-chunk placeholder credential is unique but not secret. Forged placeholders are still unwrapped by the property-name channel.';\n\nlet fallbackCounter = 0;\n\n/**\n * One credential per mounted component, created exactly once by a lazy\n * `useState` initialiser. Not `useRef(createCredential())`: that evaluates\n * its argument on EVERY render (React keeps only the first result), burning\n * randomness and, on the fallback path, repeating the diagnostic. Not\n * `useMemo` either: React may discard memo caches, and a fresh value changes\n * the `rehypePlugins` identity, which resets the incremental parse state and\n * the block cache. (A null-sentinel `useRef` would do too, but reading a ref\n * during render is what `react-hooks/refs` forbids; the state initialiser\n * is the sanctioned once-only construct.) Strict Mode may run the\n * initialiser twice in development and keep one result — the diagnostic\n * guarantee is therefore per credential instance, not per mount.\n */\nexport function useProvenanceCredential(): ProvenanceCredential {\n  const [credential] = useState<ProvenanceCredential>(createCredential);\n  return credential;\n}\n\nfunction hex(bytes: Uint8Array): string {\n  let out = '';\n  for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, '0');\n  return out;\n}\n\n/** Create a credential. Never throws; never returns an empty value. */\nexport function createCredential(): ProvenanceCredential {\n  // `globalThis.crypto`, not a bare `crypto` identifier: absence must be a\n  // detectable `undefined`, not a `ReferenceError`.\n  const webCrypto = globalThis.crypto as { getRandomValues?: (a: Uint8Array) => Uint8Array } | undefined;\n  if (webCrypto && typeof webCrypto.getRandomValues === 'function') {\n    const bytes = new Uint8Array(16);\n    webCrypto.getRandomValues(bytes);\n    return { value: hex(bytes), secret: true };\n  }\n  fallbackCounter += 1;\n  if (process.env.NODE_ENV !== 'production') {\n    console.error(`[ai-react-markdown] ${PROVENANCE_FALLBACK_MESSAGE}`);\n  }\n  return { value: `fallback-${fallbackCounter}-${Date.now().toString(36)}`, secret: false };\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, useState, type PropsWithChildren, type FC } from 'react';\nimport { createRegistry, type Registry, type RegistryInternal } from '@ai-react-markdown/engine';\nimport { createDocumentScopeCache } from './documentScopeCache';\nimport {\n  createSmoothCoordinator,\n  SmoothCoordinatorContext,\n  type SmoothCoordinatorContextValue,\n} from './smoothStream/coordinator';\n\ninterface AIMarkdownDocumentsContextValue {\n  /** Returns the registry for a given documentId. Holds the internal\n   *  (mutator-bearing) shape; {@link useDocumentRegistry} narrows the\n   *  return type to the public read-only {@link Registry} surface so\n   *  external consumers can't drive the registry directly. Internal\n   *  callers (`MarkdownContent`, tests via `__internalGetContext`) keep\n   *  the wider view. */\n  getRegistry: (documentId: string) => RegistryInternal;\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 each chunk's own\n   * `preserveOrphanReferences` prop. Does not control cross-chunk\n   * coordination itself (that's gated by wrapper presence + `documentId`).\n   */\n  preserveOrphanReferences?: boolean;\n  /**\n   * Default `true`. Turn-taking for smooth-streaming chunks: chunks that\n   * share a `documentId` and stream from empty reveal sequentially (chunk\n   * N fully revealed before chunk N+1 starts — one typewriter, one\n   * cursor). `false` disables coordination wholesale; every\n   * `AIMarkdownSmoothStream` / `useDocumentSmoothStream` under this\n   * wrapper then behaves like plain `useSmoothStream`. Per-chunk opt-out\n   * exists too (`smoothCoordination={false}` on the shell). Has no effect\n   * on chunks that don't smooth-stream.\n   */\n  smoothTurnTaking?: boolean;\n}\n\n/** Message body for the \"nested wrapper\" misuse error / warning. Centralised\n *  so dev and prod paths emit the exact same text — easier to grep in user\n *  bug reports. */\nconst NESTED_WRAPPER_MESSAGE =\n  '<AIMarkdownDocuments> must not be nested inside another <AIMarkdownDocuments>. Use a single top-level wrapper per coordinated scope.';\n\n/**\n * The \"happy path\" implementation: allocates per-instance scope caches\n * and Provider value. Split out from `AIMarkdownDocuments` so the parent\n * component's pre-hook nesting gate (which may early-return) doesn't put\n * the hooks below behind a conditional — rules-of-hooks is then trivially\n * satisfied because every render of THIS inner component goes through all\n * the hooks in the same order.\n */\nconst AIMarkdownDocumentsRoot: FC<\n  Required<Pick<AIMarkdownDocumentsProps, 'preserveOrphanReferences' | 'smoothTurnTaking'>> & PropsWithChildren\n> = ({ preserveOrphanReferences, smoothTurnTaking, children }) => {\n  // Weak entries preserve synchronous identity while a render or mounted\n  // consumer owns the scope, without retaining objects from aborted renders.\n  // onEmpty still evicts promptly after the final committed registration.\n  const [registries] = useState(() => createDocumentScopeCache(createRegistry));\n  const [coordinators] = useState(() => createDocumentScopeCache(createSmoothCoordinator));\n\n  const smoothValue = useMemo<SmoothCoordinatorContextValue | null>(\n    () => (smoothTurnTaking ? { getCoordinator: coordinators.get } : null),\n    [smoothTurnTaking, coordinators]\n  );\n  const value = useMemo<AIMarkdownDocumentsContextValue>(\n    () => ({ preserveOrphanReferences, getRegistry: registries.get }),\n    [preserveOrphanReferences, registries]\n  );\n\n  return (\n    <AIMarkdownDocumentsContext.Provider value={value}>\n      <SmoothCoordinatorContext.Provider value={smoothValue}>{children}</SmoothCoordinatorContext.Provider>\n    </AIMarkdownDocumentsContext.Provider>\n  );\n};\n\nexport const AIMarkdownDocuments: FC<AIMarkdownDocumentsProps> = ({\n  preserveOrphanReferences = true,\n  smoothTurnTaking = true,\n  children,\n}) => {\n  const parent = useContext(AIMarkdownDocumentsContext);\n  if (parent !== null) {\n    // Dev: fail fast. The error makes the misuse obvious in any non-\n    // production environment and prevents subtle bugs (the inner wrapper's\n    // children would silently see the outer wrapper's registry / preserve-\n    // orphan policy, which is almost never what a nested wrapper was\n    // attempting to express).\n    //\n    // Prod: degrade gracefully. AI chat / document UIs that wire\n    // `<AIMarkdownDocuments>` deep inside dynamic composition (RSC, portals,\n    // third-party layout libs) can hit the nested-wrapper case via an\n    // upstream bug — crashing the entire conversation pane is worse user\n    // experience than silently rendering the inner subtree against the outer\n    // wrapper. Emit a `console.error` (visible to ops dashboards / Sentry)\n    // and render `children` as-is so the existing outer Provider continues\n    // to apply.\n    //\n    // Hooks-rules note: the outer component only calls `useContext` before\n    // the early return; the hooks that allocate state (`useState`, `useMemo`)\n    // live in `AIMarkdownDocumentsRoot`, which is only mounted on the\n    // non-nested branch. Whichever branch this instance takes, it takes\n    // for its entire lifetime — React's per-instance hook order stays\n    // stable and ESLint's `react-hooks/rules-of-hooks` is happy.\n    //\n    // The dev/prod split mirrors React's own invariant-vs-warning pattern.\n    if (process.env.NODE_ENV !== 'production') {\n      throw new Error(NESTED_WRAPPER_MESSAGE);\n    }\n    console.error(\n      `[ai-react-markdown] ${NESTED_WRAPPER_MESSAGE} Falling back to the outer wrapper; the inner wrapper is a no-op.`\n    );\n    return <>{children}</>;\n  }\n  return (\n    <AIMarkdownDocumentsRoot preserveOrphanReferences={preserveOrphanReferences} smoothTurnTaking={smoothTurnTaking}>\n      {children}\n    </AIMarkdownDocumentsRoot>\n  );\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, OR\n *  - `documentIdExplicit` is `false` — i.e. the id was auto-generated rather\n *    than supplied by the consumer.\n *\n * The `documentIdExplicit` gate is the crux of the standalone-vs-coordinated\n * decision. An auto-generated id (`useId()` fallback) is non-empty and unique\n * by construction, so a chunk carrying one has nothing to coordinate with even\n * inside the wrapper — it must run standalone. Without this gate, the mere\n * presence of `<AIMarkdownDocuments>` would drag every uncoordinated chunk\n * onto the cross-chunk registry path (subscribe / allocate / evict overhead)\n * for no behavioral gain. The flag defaults to `true` so external callers who\n * pass an id directly are treated as explicit (passing an id IS the intent to\n * coordinate); the internal renderer threads through `state.documentIdExplicit`.\n *\n * Callers should treat `null` as \"no coordination; run standalone path.\"\n */\nexport function useDocumentRegistry(documentId: string | undefined, documentIdExplicit = true): Registry | null {\n  const ctx = useContext(AIMarkdownDocumentsContext);\n  if (!ctx || !documentId || !documentIdExplicit) 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 the chunk's resolved `preserveOrphanReferences` prop). */\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","/** Synchronous scope identity without owning abandoned render allocations.\n * Mounted consumers and pending renders keep their scopes alive. The cache\n * only observes them; otherwise a render that never commits cannot run the\n * registration cleanup needed to release a strongly cached scope.\n */\nexport function createDocumentScopeCache<T extends object>(create: (onEmpty: () => void) => T) {\n  const entries = new Map<string, WeakRef<T>>();\n  const collected = new FinalizationRegistry<{ id: string; ref: WeakRef<T> }>(({ id, ref }) => {\n    // Collection can arrive after onEmpty and a new allocation of this id.\n    if (entries.get(id) === ref) entries.delete(id);\n  });\n  return {\n    get(id: string): T {\n      const existing = entries.get(id)?.deref();\n      if (existing) return existing;\n      const scope = create(() => {\n        if (entries.get(id) === ref) entries.delete(id);\n        collected.unregister(ref);\n      });\n      const ref = new WeakRef(scope);\n      entries.set(id, ref);\n      // Holdings must never contain scope: that would keep the target alive.\n      collected.register(scope, { id, ref }, ref);\n      return scope;\n    },\n  };\n}\n","import { createContext } from 'react';\nimport type { SmoothCoordinatorInternal } from '@ai-react-markdown/runtime';\nexport { createSmoothCoordinator, evaluateGateWarn } from '@ai-react-markdown/runtime';\nexport type { SmoothCoordinator, SmoothCoordinatorInternal, GateWarnVerdict } from '@ai-react-markdown/runtime';\n\n/**\n * Context value provided by `<AIMarkdownDocuments>` (a sibling of the def\n * registry context — the two never reference each other). `null` when\n * outside the wrapper or when the wrapper sets `smoothTurnTaking={false}`;\n * consumers treat `null` as \"no coordination, plain smooth behavior\".\n */\nexport interface SmoothCoordinatorContextValue {\n  getCoordinator: (documentId: string) => SmoothCoordinatorInternal;\n}\n\nexport const SmoothCoordinatorContext = createContext<SmoothCoordinatorContextValue | null>(null);\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 {\n  type ReactNode,\n  Fragment,\n  cloneElement,\n  isValidElement,\n  useCallback,\n  useContext,\n  useSyncExternalStore,\n} from 'react';\nimport { useAIMarkdownDocument } from '../context';\nimport { useDocumentRegistry } from './AIMarkdownDocuments';\nimport { ChunkSymbolContext } from './chunkSymbolContext';\nimport { CrossChunkUrlContext } from './crossChunkUrlContext';\nimport { resolveCrossChunkReference } from '@ai-react-markdown/engine';\nimport { toJsxRuntime } from 'hast-util-to-jsx-runtime';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport type { CrossChunkUrlPolicy } from './crossChunkUrlContext';\nimport { defaultUrlTransform } from './markdown';\nimport { sanitizeSchema as defaultSanitizeSchema } from '@ai-react-markdown/engine';\nimport type { Element } from 'hast';\nimport type { LinkDef } from '@ai-react-markdown/engine';\nimport { footnoteSafeId } from '@ai-react-markdown/engine';\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_LABEL_SNAPSHOT = () => '';\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  /** The number a standalone render would give this reference (its\n   *  footnoteOrder position) — the fallback while the registry has no\n   *  global number yet: server render and the client's first frame, where\n   *  the chunk's LOCAL synthetic footer is what renders, so mark and footer\n   *  agree. Absent on phantom (cross-chunk) refs. */\n  localNumber?: 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({\n  label,\n  localOccurrence: localOccurrenceRaw,\n  localNumber: localNumberRaw,\n}: FootnoteSupProps): ReactNode {\n  const localOccurrence = coerceLocalOccurrence(localOccurrenceRaw);\n  const localNumber = coerceLocalOccurrence(localNumberRaw);\n  const { documentId, documentIdExplicit, clobberPrefix } = useAIMarkdownDocument();\n  // Thread `documentIdExplicit` exactly like `MarkdownContent` does: a chunk\n  // with an auto-generated id must NOT open a registry even if a raw/crafted\n  // placeholder tag for it survives into hast inside <AIMarkdownDocuments>.\n  // Without this, such a tag would create an orphan registry shell that has\n  // no paired registerChunk, so eviction never fires — a leak on the path\n  // this whole change exists to keep standalone.\n  const registry = useDocumentRegistry(documentId, documentIdExplicit);\n  const chunkSym = useContext(ChunkSymbolContext);\n  // Route notifications by label, then select only facts used by this mark.\n  const subscribe = useCallback(\n    (cb: () => void) => (registry ? registry.subscribeLabel('footnote', label, cb) : () => {}),\n    [registry, label]\n  );\n  const getSnapshot = useCallback(\n    () =>\n      JSON.stringify([\n        registry?.globalNumber(label) ?? null,\n        registry && chunkSym && localOccurrence !== null\n          ? registry.globalOccurrenceForRef(chunkSym, label, localOccurrence)\n          : null,\n      ]),\n    [registry, label, chunkSym, localOccurrence]\n  );\n  useSyncExternalStore(subscribe, getSnapshot, SSR_LABEL_SNAPSHOT);\n  const num = registry?.globalNumber(label) ?? null;\n  // Same id encoding as mdast-util-to-hast's marks and footer (and the\n  // aggregate footer): a raw label in the id broke `[^注]` / `[^a%b]`\n  // anchors — mark and <li> disagreed (v2.4.0 review).\n  const safeId = footnoteSafeId(label);\n  // Global occurrence of THIS mark (`-N` for the 2nd+ ref of the label\n  // across the document). Null while this chunk has not contributed yet.\n  const globalOcc =\n    registry && chunkSym && localOccurrence !== null && num !== null\n      ? registry.globalOccurrenceForRef(chunkSym, label, localOccurrence)\n      : null;\n  // (`chunkSym === null` with a numbered label falls through to the id-less\n  //  mark below — see the note there.)\n  if (num === null) {\n    // No global number yet — server render, or the client's first frame\n    // before the contribute effect. Render the STANDALONE mark (local\n    // number, `-N` by local occurrence) so it lines up with the local\n    // synthetic footer that renders in exactly this state; the global\n    // numbering takes over once the registry knows the label. Rendering\n    // null here left coordinated SSR with footers but no marks\n    // (2026-08 project review, core-render-02). Phantom refs (no local\n    // number) still render nothing — their def is in another chunk.\n    if (localNumber === null) return null;\n    const localSuffix = localOccurrence !== null && localOccurrence > 1 ? `-${localOccurrence}` : '';\n    // Byte-for-byte the mark mdast-util-to-hast emits (attribute set and\n    // order included, id encoding via footnoteSafeId), so a wrapped chunk's\n    // server output equals its standalone output — pinned in\n    // byteEquivalence.test.tsx.\n    return (\n      <sup>\n        <a\n          href={`#${clobberPrefix}fn-${safeId}`}\n          id={`${clobberPrefix}fnref-${safeId}${localSuffix}`}\n          data-footnote-ref=\"\"\n          aria-describedby={`${clobberPrefix}footnote-label`}\n        >\n          {localNumber}\n        </a>\n      </sup>\n    );\n  }\n  // No chunk symbol yet (`chunkSym` is state, null on a chunk's very first\n  // frame) while the label is already numbered by another chunk: same\n  // \"known number, unregistered occurrence\" transient as below — show the\n  // number, no id (r2 P3 carry-over of the 2.4.5 fix; it used to render\n  // nothing, and SSR shipped a footer backref pointing at no anchor).\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  //\n  // `globalOcc === null` with `num` known: the label is numbered but THIS\n  // occurrence is not in the registry — transiently (a later-mounted chunk\n  // repeating the label, contribute effect pending) or permanently (a ref\n  // inside a footnote DEFINITION body: the engine's per-chunk counter bumps\n  // it, but contributions skip definition bodies). Both used to render\n  // nothing (2026-08-19 review P3, oracle F2). The number is right either\n  // way — show it, WITHOUT an id: the registry does not know this ref, so\n  // no footer backref will ever point at it, and a chunk-local id would\n  // collide with another chunk's real `fnref-<label>` mark (oracle re-check).\n  const occSuffix = globalOcc !== null && globalOcc > 1 ? `-${globalOcc}` : '';\n  const markId =\n    globalOcc !== null || localOccurrence === null ? `${clobberPrefix}fnref-${safeId}${occSuffix}` : undefined;\n  return (\n    <sup>\n      <a href={`#${clobberPrefix}fn-${safeId}`} id={markId} data-footnote-ref=\"\">\n        {num}\n      </a>\n    </sup>\n  );\n}\n\n/** Convert sanitized HAST properties with the same JSX runtime as regular\n * elements (including required/class/style attributes from custom schemas).\n * Link children are already rendered; retain their component identities. */\nfunction renderResolvedReference(\n  input: Parameters<typeof resolveCrossChunkReference>[0],\n  policy: CrossChunkUrlPolicy | null,\n  clobberPrefix: string,\n  children?: ReactNode\n): ReactNode {\n  const result = resolveCrossChunkReference(\n    input,\n    policy?.sanitizeSchema ?? defaultSanitizeSchema,\n    policy?.urlTransform ?? defaultUrlTransform,\n    clobberPrefix\n  );\n  if (!result.element) return result.keepChildren ? children : null;\n  const rendered = toJsxRuntime(result.element, { Fragment, jsx, jsxs });\n  return input.tagName === 'a' && isValidElement(rendered) ? cloneElement(rendered, undefined, children) : rendered;\n}\n\ninterface CrossChunkLinkProps {\n  node?: Element;\n  label: string;\n  identifier?: string;\n  referenceType: RefType;\n  children?: ReactNode;\n  /** The chunk's OWN definition (never a phantom's) — carried by the\n   *  handler so the link renders before the registry has it (server render,\n   *  first client frame). Runs through the same URL gates as a registry\n   *  value; a cross-chunk (canonical) def replaces it once the registry\n   *  resolves. See core-render-02. */\n  localUrl?: string;\n  localTitle?: string;\n}\n\n/** The registry's canonical def, or the chunk's own as a fallback. */\nfunction resolveDef(\n  registry: { resolveLinkDef(label: string): LinkDef | null } | null,\n  label: string,\n  localUrl?: string,\n  localTitle?: string\n): LinkDef | null {\n  const canonical = registry?.resolveLinkDef(label) ?? null;\n  if (canonical) return canonical;\n  if (typeof localUrl === 'string') return { identifier: label, url: localUrl, title: localTitle };\n  return null;\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({\n  node,\n  label,\n  identifier,\n  referenceType,\n  children,\n  localUrl,\n  localTitle,\n}: CrossChunkLinkProps): ReactNode {\n  const { documentId, documentIdExplicit, clobberPrefix } = useAIMarkdownDocument();\n  // See FootnoteSupNumber: gate on explicitness so an auto-id chunk never\n  // opens a registry shell via a stray placeholder tag.\n  const registry = useDocumentRegistry(documentId, documentIdExplicit);\n  const policy = useContext(CrossChunkUrlContext);\n  // Links and images share the definition channel; unrelated labels do not wake this subscriber.\n  const subscribe = useCallback(\n    (cb: () => void) => (registry ? registry.subscribeLabel('link', identifier ?? label, cb) : () => {}),\n    [registry, identifier, label]\n  );\n  const getSnapshot = useCallback(() => {\n    const def = registry?.resolveLinkDef(identifier ?? label);\n    return JSON.stringify(def ? [def.url, def.title ?? null] : null);\n  }, [registry, identifier, label]);\n  useSyncExternalStore(subscribe, getSnapshot, SSR_LABEL_SNAPSHOT);\n  const def = resolveDef(registry, identifier ?? label, localUrl, localTitle);\n  if (!def) {\n    return literalLink(referenceType, label, children);\n  }\n  return renderResolvedReference(\n    { tagName: 'a', url: def.url, title: def.title, node },\n    policy,\n    clobberPrefix,\n    children\n  );\n}\n\ninterface CrossChunkImageProps {\n  node?: Element;\n  label: string;\n  identifier?: string;\n  referenceType: RefType;\n  alt?: string;\n  /** See CrossChunkLinkProps. */\n  localUrl?: string;\n  localTitle?: 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({\n  node,\n  label,\n  identifier,\n  referenceType,\n  alt = '',\n  localUrl,\n  localTitle,\n}: CrossChunkImageProps): ReactNode {\n  const { documentId, documentIdExplicit, clobberPrefix } = useAIMarkdownDocument();\n  // See FootnoteSupNumber: gate on explicitness so an auto-id chunk never\n  // opens a registry shell via a stray placeholder tag.\n  const registry = useDocumentRegistry(documentId, documentIdExplicit);\n  const policy = useContext(CrossChunkUrlContext);\n  // Same subscription-only useSyncExternalStore pattern as CrossChunkLink —\n  // see that component for the rationale.\n  const subscribe = useCallback(\n    (cb: () => void) => (registry ? registry.subscribeLabel('link', identifier ?? label, cb) : () => {}),\n    [registry, identifier, label]\n  );\n  const getSnapshot = useCallback(() => {\n    const def = registry?.resolveLinkDef(identifier ?? label);\n    return JSON.stringify(def ? [def.url, def.title ?? null] : null);\n  }, [registry, identifier, label]);\n  useSyncExternalStore(subscribe, getSnapshot, SSR_LABEL_SNAPSHOT);\n  const def = resolveDef(registry, identifier ?? label, localUrl, localTitle);\n  if (!def) {\n    return literalImage(referenceType, label, alt);\n  }\n  return renderResolvedReference({ tagName: 'img', url: def.url, title: def.title, alt, node }, policy, clobberPrefix);\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 * Render-time URL sanitization policy exposed to cross-chunk placeholders.\n *\n * Carries the resolved `urlTransform` and `sanitizeSchema` for the current\n * `<AIMarkdown>` instance so {@link CrossChunkLink} and\n * {@link CrossChunkImage} can apply the same two-gate pipeline that\n * react-markdown's standalone hast pass applies to in-tree `<a href>` and\n * `<img src>` elements. See `crossChunkUrlSanitize.ts` for the gate logic\n * and why it must happen at render time rather than at contribute time.\n *\n * Value is `null` outside a coordinated render. When `null`, the\n * placeholders fall back to a safe baseline (`defaultUrlTransform` only),\n * which preserves the v1.4.3 behavior on the rare path where the context\n * is missing (e.g., a test renders a placeholder without an `<AIMarkdown>`\n * ancestor).\n *\n * @module components/crossChunkUrlContext\n */\nimport { createContext } from 'react';\nimport type { UrlTransform } from './markdown';\nimport type { SanitizeSchema } from '@ai-react-markdown/engine';\n\nexport interface CrossChunkUrlPolicy {\n  /** Resolved urlTransform — caller's prop or {@link defaultUrlTransform}. */\n  urlTransform: UrlTransform;\n  /** Resolved sanitize schema — caller's prop or the library default. */\n  sanitizeSchema: SanitizeSchema;\n}\n\nexport const CrossChunkUrlContext = createContext<CrossChunkUrlPolicy | null>(null);\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 { renderHastSubtree } from './markdown';\nimport type { Registry } from '@ai-react-markdown/engine';\nimport { buildAggregateTree } from '@ai-react-markdown/runtime';\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\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  // The \"am I the last chunk\" test lives INSIDE the factory: every chunk\n  // mounts one of these, and only the last one's tree is ever used — with\n  // the test outside, every chunk rebuilt the aggregate on every version\n  // bump (`buildAggregateTree` is O(chunks × refs)), O(N²) on the initial\n  // mount of N chunks (2026-08-19 review r2 P3).\n  const tree = useMemo(\n    () => {\n      const order = registry.chunkOrder;\n      if (order.length === 0 || order[order.length - 1] !== thisChunkSym) return null;\n      return buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences);\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [registry, registry.version, clobberPrefix, preserveOrphanReferences, thisChunkSym]\n  );\n  if (!tree) return null;\n  // Our `tree` is memoised by registry.version, so a non-version-bumping\n  // parent re-render re-enters the same cached tree. That is safe without a\n  // defensive clone: the visit transform applies urlTransform convergently\n  // (recomputed from the original stashed on `element.data` — see\n  // `buildTransform`), and `renderHastSubtree` itself clones when a\n  // destructive structural filter (element allow/disallow lists, skipHtml)\n  // is set on `postOptions` — never the case from `<AIMarkdown>`.\n  return <>{renderHastSubtree(tree, postOptions)}</>;\n};\n\nexport const AggregateFootnotesIfLast = memo(AggregateFootnotesIfLastImpl);\nAggregateFootnotesIfLast.displayName = 'AggregateFootnotesIfLast';\n","import { useEffect, useState } from 'react';\nimport { createContributionSession, type ContributionOptions } from '@ai-react-markdown/runtime';\n\n/** The runtime publishes only after React commits a registered chunk. */\nexport function useRegistryContribution({\n  pipeline,\n  ownLabels,\n  registry,\n  targetPhantoms,\n  sym,\n  clobberPrefix,\n  chain,\n}: ContributionOptions) {\n  const [session] = useState(createContributionSession);\n  useEffect(() => {\n    session.commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain });\n  }, [session, pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain]);\n}\n","/**\n * The stability firewall: single-boundary, table-driven reference\n * stabilization of object-valued props (EXECUTION-PLAN §3.9).\n *\n * Replaces scattered per-prop `useStableValue` calls with ONE hook whose\n * behavior per key is declared in a module-scope policy table. Layering\n * rule: below the firewall, internal code never stabilizes again —\n * reference equality is trusted outright.\n *\n * The table is the complete roster of object-valued props:\n * {@link AIMarkdownStabilityTable} is `Required<Record<keyof T, …>>`, so\n * adding an object prop without registering it is a compile error.\n * Exemption ({@link AIMarkdownStabilityPolicy.PASS_THROUGH}) and omission\n * (missing row) are thereby distinguishable — exemption is a decision,\n * a missing row is an omission.\n *\n * @module hooks/useStableRecord\n */\n\nimport { useRef, useLayoutEffect, useEffect } from 'react';\nimport isEqual from 'lodash-es/isEqual';\nimport { FLIP_WINDOW_MS } from './useReferenceFlipWarning';\n\n/** Module-scope dev flag — resolved at build time (see `useReferenceFlipWarning`'s docblock). */\nconst __DEV__ = process.env.NODE_ENV !== 'production';\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\n/**\n * Stabilization policy tiers. Publicly exported; wrappers reuse it for\n * their own tables (a wrapper builds a table only for object props it\n * *terminates* — forwarded props ride core's firewall untouched).\n */\nexport enum AIMarkdownStabilityPolicy {\n  /**\n   * Deep-equal backstop: when the reference changed, deep-compare; if the\n   * contents are deep-equal, reuse the previous reference. For\n   * structurally comparable data values. In dev, high-frequency\n   * \"deep-equal restores\" warn — the caller is inlining objects; caches\n   * stay warm, but every render pays one deep comparison.\n   */\n  DEEP_EQUAL = 'DEEP_EQUAL',\n  /**\n   * No comparison; dev-mode flip-rate probe only. For function and\n   * component values — deep-comparing closures is meaningless; the\n   * contract requires the caller to hold a stable reference.\n   */\n  WARN_ONLY = 'WARN_ONLY',\n  /**\n   * Explicit pass-through: no comparison, no probe. For deliberately\n   * exempted props (e.g. `metadata`: opaque shape, potentially huge,\n   * unbounded comparison cost — stabilization is the consumer's\n   * responsibility).\n   */\n  PASS_THROUGH = 'PASS_THROUGH',\n}\n\n/**\n * Policy table for a record of object-valued props. `Required` makes the\n * table the complete roster: every key of `T` must carry a policy row.\n */\nexport type AIMarkdownStabilityTable<T extends object> = Required<Record<keyof T, AIMarkdownStabilityPolicy>>;\n\n/**\n * Pure per-render stabilization step, exported for unit testing (the hook\n * wraps it with the committed-render ref discipline).\n *\n * Iterates the TABLE's keys (the roster is authoritative; keys of `record`\n * outside the table do not exist type-wise and are dropped). When no key's\n * output differs from `prev`, returns `prev` itself so the record keeps\n * its object identity — directly usable as a context value.\n */\nexport function stabilizeRecord<T extends object>(prev: T, record: T, table: AIMarkdownStabilityTable<T>): T {\n  let changed = false;\n  const out = {} as Record<PropertyKey, unknown>;\n  for (const key of Object.keys(table) as (keyof T)[]) {\n    const next = record[key];\n    const before = prev[key];\n    let value = next;\n    if (table[key] === AIMarkdownStabilityPolicy.DEEP_EQUAL && next !== before && isEqual(before, next)) {\n      value = before;\n    }\n    out[key] = value;\n    if (value !== before) {\n      changed = true;\n    }\n  }\n  return changed ? (out as T) : prev;\n}\n\n/** How many probe hits before the first warning fires. */\nconst HIT_THRESHOLD = 3;\n\n/** Minimum delay between successive warnings per key, milliseconds. */\nconst WARN_COOLDOWN_MS = 5000;\n\ninterface ProbeState {\n  prev: unknown;\n  hits: number;\n  lastWarnAt: number;\n  /** Clock time of the previous hit; hits further apart than\n   *  FLIP_WINDOW_MS restart the count (see useReferenceFlipWarning). */\n  lastHitAt?: number;\n}\n\n/**\n * Rate-limited dev probe shared by the two warning tiers. Mirrors the\n * threshold/cooldown semantics of `useReferenceFlipWarning`'s `trackFlip`.\n */\nfunction probeHit(state: ProbeState, message: string, now: number): void {\n  if (state.lastHitAt !== undefined && now - state.lastHitAt > FLIP_WINDOW_MS) state.hits = 0;\n  state.lastHitAt = now;\n  state.hits++;\n  if (state.hits < HIT_THRESHOLD) return;\n  if (now - state.lastWarnAt < WARN_COOLDOWN_MS) return;\n  state.lastWarnAt = now;\n  console.warn(message);\n}\n\n/**\n * Returns a stabilized version of `record` according to `table`.\n *\n * - The loop lives inside the hook (static hook count — rules-compliant\n *   regardless of table size).\n * - The previous-value ref advances in a post-commit layout effect,\n *   identical to `useStableValue`'s concurrent-safety discipline:\n *   discarded renders never pollute the cache.\n * - When no key changed, the output object keeps its identity.\n *\n * `table` must be a module-scope constant: the roster (and each key's\n * policy) is fixed for the lifetime of the call site.\n */\nexport default function useStableRecord<T extends object>(record: T, table: AIMarkdownStabilityTable<T>): T {\n  const ref = useRef(record);\n  const probesRef = useRef<Record<string, ProbeState> | null>(null);\n\n  const prev = ref.current;\n  const stable = stabilizeRecord(prev, record, table);\n\n  if (__DEV__) {\n    const probes = (probesRef.current ??= {});\n    // Intentional render-time `Date.now()`: wall-clock cooldown between\n    // probe events, same rationale as `useReferenceFlipWarning`.\n    const now = Date.now();\n    for (const key of Object.keys(table) as (keyof T)[]) {\n      const policy = table[key];\n      if (policy === AIMarkdownStabilityPolicy.PASS_THROUGH) continue;\n      const next = record[key];\n      const state = (probes[String(key)] ??= { prev: next, hits: 0, lastWarnAt: -Infinity });\n      if (state.prev !== next) {\n        if (policy === AIMarkdownStabilityPolicy.WARN_ONLY) {\n          probeHit(\n            state,\n            `[AIMarkdown] \\`${String(key)}\\` reference is changing on every render. ` +\n              `This prop's contract requires a stable reference — define it at module ` +\n              `scope or wrap it with useMemo/useCallback.`,\n            now\n          );\n        } else if ((stable as Record<keyof T, unknown>)[key] !== next) {\n          // DEEP_EQUAL tier: the stabilizer restored the previous reference,\n          // i.e. the caller re-built a deep-equal object this render.\n          probeHit(\n            state,\n            `[AIMarkdown] \\`${String(key)}\\` is re-created on every render with deep-equal ` +\n              `contents — the caller is likely inlining the value. Caches stay warm, but ` +\n              `every render pays one deep comparison; define it at module scope or memoize it.`,\n            now\n          );\n        }\n        state.prev = next;\n      }\n    }\n  }\n\n  useIsomorphicLayoutEffect(() => {\n    ref.current = stable;\n  }, [stable]);\n\n  return stable;\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 * `useSmoothStream` with document-level turn-taking.\n *\n * Inside `<AIMarkdownDocuments>`, chunks sharing a `documentId` should read\n * as ONE typewriter: chunk N reveals completely before chunk N+1 starts,\n * with a single cursor throughout. This hook wraps an UNCHANGED\n * `useSmoothStream` with that gate:\n *\n * - A chunk that mounts with EMPTY content queues behind its earlier-mounted\n *   siblings and renders nothing (no cursor) until every one of them is\n *   done (source stopped AND reveal drained).\n * - A chunk that mounts with non-empty content passes through ungated —\n *   the mount snap presents it instantly, exactly like `useSmoothStream`\n *   (hydration, virtualization scroll-back, and mid-stream remounts must\n *   not blank out or replay; see the gate note below). It still occupies\n *   its queue slot, so later empty-mounted chunks wait for it.\n * - Without a `documentId`, or outside `<AIMarkdownDocuments>` (or with\n *   `smoothTurnTaking={false}` on the wrapper), behavior is identical to\n *   `useSmoothStream`.\n *\n * The result is props-shaped and spreads into `<AIMarkdown>` or any\n * wrapper, same as `useSmoothStream`. `documentId` must match the one the\n * rendered component receives (the hook cannot cross-check; a mismatch\n * silently loses coordination) and must be mount-stable.\n *\n * Contract shifts relative to `useSmoothStream`, both gate-inherent:\n * `onDrained` fires after the chunk's TURN completes — potentially long\n * after its source stream ended — and a content replacement that happens\n * entirely while gated DOES fire it (the reveal only ever saw empty →\n * final text, so the finally-revealed message genuinely completed).\n * `flush()` while gated is a no-op: nothing is playing yet, and skipping\n * the whole document's queue is deliberately not a per-chunk power.\n *\n * @module components/smoothStream/useDocumentSmoothStream\n */\n\nimport { useContext, useEffect, useId, useRef, useState } from 'react';\nimport { useSmoothStream, type UseSmoothStreamOptions, type UseSmoothStreamResult } from './useSmoothStream';\nimport { evaluateGateWarn, SmoothCoordinatorContext, type SmoothCoordinatorInternal } from './coordinator';\n\nexport interface UseDocumentSmoothStreamOptions extends UseSmoothStreamOptions {\n  /**\n   * The document this chunk belongs to — the same value the rendered\n   * `<AIMarkdown>` receives. Coordination engages only when this is a\n   * non-empty string AND the component sits under `<AIMarkdownDocuments>`\n   * with turn-taking enabled; otherwise the hook degrades to plain\n   * `useSmoothStream`. Must be mount-stable: changing it mid-life is\n   * undefined behavior.\n   */\n  documentId?: string;\n  /** Hold this queue slot before input starts, without showing a streaming\n   * cursor. Clear when input starts OR when an empty result completes.\n   * `streaming: false` alone still means a completed source. */\n  waiting?: boolean;\n}\n\n/** Dev-only stuck-flag warning threshold (§ ordering failure modes in the\n *  turn-taking plan): a chunk pending longer than this while its earliest\n *  blocker shows no reveal progress for as long triggers a console.warn. */\nconst GATE_WARN_THRESHOLD_MS = 10_000;\n\nexport const useDocumentSmoothStream = ({\n  documentId,\n  content,\n  streaming = false,\n  waiting = false,\n  pacing,\n  onDrained,\n  now,\n  schedule,\n}: UseDocumentSmoothStreamOptions): UseSmoothStreamResult => {\n  const ctx = useContext(SmoothCoordinatorContext);\n  const coordinator: SmoothCoordinatorInternal | null = ctx && documentId ? ctx.getCoordinator(documentId) : null;\n  const reactId = useId();\n\n  // ── Gate decision: FIRST MOUNT RENDER, before any effect ─────────────────\n  // Captured in a useState initializer so the very first client render (and\n  // the whole server render) already sees the verdict. Deciding in an effect\n  // would feed '' to the inner hook for one frame on non-empty mounts —\n  // a hydration mismatch (the server renders full text) and a visible\n  // flash-then-blank on remounts. Only empty-content mounts queue.\n  const [participates] = useState(() => coordinator !== null && content === '');\n\n  // Released is sticky: predecessors' done is sticky and unmounts only\n  // shrink the blocker set, so once true it can never flip back.\n  const [released, setReleased] = useState(!participates);\n  // Two-beat release handshake, beat 1: force streaming=true for exactly one\n  // commit so the inner reaction effect enters via the append/update branch.\n  // Releasing directly with the user's streaming=false would take the\n  // snap branch (false→false in the inner effect) and flash the whole\n  // backlog — precisely on the main scenario (source finished while queued).\n  const [forcedStreaming, setForcedStreaming] = useState(false);\n\n  // Latest content for the release check below. A ref (synced in an\n  // every-render effect, declared BEFORE the watcher so it is fresh within\n  // the same commit) because the watcher effect must not re-subscribe on\n  // every token append.\n  const contentRef = useRef(content);\n  useEffect(() => {\n    contentRef.current = content;\n  });\n\n  // ── Registration (effect time; refcounted for Strict Mode) ───────────────\n  useEffect(() => {\n    if (!coordinator) return;\n    coordinator.register(reactId);\n    return () => coordinator.release(reactId);\n  }, [coordinator, reactId]);\n\n  // ── Release watcher ──────────────────────────────────────────────────────\n  useEffect(() => {\n    if (released) return;\n    if (!coordinator) {\n      // Coordination withdrawn while gated (`smoothCoordination` /\n      // `smoothTurnTaking` flipped false, the documented escape hatch for a\n      // wedged queue): release unconditionally. Without this branch the\n      // chunk is stuck at ''/false forever — nobody else can flip\n      // `released`. Sticky release (not a render-time `gatedPending &&\n      // coordinator` guard) so re-enabling coordination later can never\n      // re-hide visible text. No forced beat: with no coordinator there is\n      // no queue to protect, and the plain snap/update degradation is\n      // exactly what \"coordination off\" means.\n      // eslint-disable-next-line react-hooks/set-state-in-effect -- one-shot sticky latch\n      setReleased(true);\n      return;\n    }\n    const check = () => {\n      if (coordinator.isReleased(reactId)) {\n        // Both set in one callback → one batched commit = beat 1. The\n        // forced beat exists to protect a non-empty backlog from the snap\n        // branch; an EMPTY chunk has nothing to protect, and forcing it\n        // would render one frame of cursor on a chunk whose source already\n        // ended (content that arrives later takes the normal update/snap\n        // paths regardless).\n        setReleased(true);\n        if (contentRef.current !== '') setForcedStreaming(true);\n      }\n    };\n    check();\n    return coordinator.subscribe(check);\n  }, [coordinator, released, reactId]);\n\n  // ── Feed the inner hook ──────────────────────────────────────────────────\n  const gatedPending = participates && !released;\n  const innerContent = gatedPending ? '' : content;\n  const innerStreaming = gatedPending ? false : forcedStreaming || streaming;\n  // The inner hook is called unconditionally exactly once. It MUST be\n  // called before the handshake-clearing effect below is declared: within a\n  // commit, effects run in hook-call order, so the inner reaction effect\n  // (beat 1's update, which flips its prevStreamingRef to true) is\n  // guaranteed to run before the effect that schedules beat 2.\n  const inner = useSmoothStream({ content: innerContent, streaming: innerStreaming, pacing, onDrained, now, schedule });\n\n  // Beat 2: clear the forced flag in its own effect, keyed on the flag.\n  // Clearing it anywhere earlier (same callback, same microtask) lets React\n  // batch both beats into one render — the inner effect would then run once\n  // with (full, false) and take the snap branch.\n  useEffect(() => {\n    // The setState-in-effect is the MECHANISM here, not an accident: the\n    // flag must be cleared in a separate commit (beat 2), and an effect\n    // keyed on the flag is the only primitive that guarantees it. It runs\n    // at most once per release — no cascading-render risk.\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    if (forcedStreaming) setForcedStreaming(false);\n  }, [forcedStreaming]);\n\n  // ── Done reporting: value-derived, sticky at the coordinator ─────────────\n  // Derived from values the wrapper can see on every relevant commit — never\n  // from notify/onDrained edges: a released chunk whose content is still ''\n  // produces zero controller notifies, and edge-driven reporting would\n  // never mark it done, wedging every successor. The `released` guard is\n  // load-bearing: a QUEUED chunk whose source completed while gated\n  // (streaming=false, inner sees ''/false) must not report done — that\n  // would release its successors ahead of it.\n  useEffect(() => {\n    if (!coordinator || !released) return;\n    if (!waiting && !streaming && !forcedStreaming && !inner.streaming) coordinator.markDone(reactId);\n  }, [coordinator, released, reactId, waiting, streaming, forcedStreaming, inner.streaming]);\n\n  // ── Reveal-progress heartbeat (feeds the dev-only warning below) ─────────\n  // `now` is the @internal test-clock seam; identity-stable in practice, so\n  // listing it as a dep is free and keeps the effect lint-clean.\n  useEffect(() => {\n    if (!coordinator) return;\n    coordinator.stampProgress(reactId, (now ?? Date.now)());\n  }, [coordinator, reactId, inner.content, now]);\n\n  // ── Dev-only stuck-flag warning ──────────────────────────────────────────\n  // The coordinator fanout cannot drive this: the stuck scenario is exactly\n  // the one with zero state changes. A pending chunk arms a timer instead\n  // and reads the blocker's heartbeat on demand; progress re-arms silently.\n  useEffect(() => {\n    if (process.env.NODE_ENV === 'production') return;\n    if (!coordinator || !gatedPending) return;\n    let timer: ReturnType<typeof setTimeout>;\n    const arm = () => {\n      timer = setTimeout(() => {\n        // The warn/re-arm/clear decision lives in a pure function\n        // (unit-tested in node); this timer body only wires it up.\n        const verdict = evaluateGateWarn(coordinator, reactId, (now ?? Date.now)(), GATE_WARN_THRESHOLD_MS);\n        if (verdict === 'clear') return; // release is propagating\n        if (verdict === 'rearm') {\n          arm(); // blocker is still revealing — a slow model, not a stuck flag\n          return;\n        }\n        console.warn(\n          '[ai-react-markdown] A smooth-stream chunk has been gated for a while behind a predecessor ' +\n            'that shows no reveal progress. A predecessor chunk may have a stuck `streaming` flag ' +\n            '(it must flip to false when its stream ends), which blocks every later chunk in this document.'\n        );\n      }, GATE_WARN_THRESHOLD_MS);\n    };\n    arm();\n    return () => clearTimeout(timer);\n  }, [coordinator, gatedPending, reactId, now]);\n\n  if (gatedPending) {\n    // Pending presentation: nothing renders, no cursor. The inner hook is\n    // fed ''/false, so inner.content is '' and inner.streaming is false —\n    // returning `inner` directly would be equivalent; being explicit keeps\n    // the contract visible (flush stays the inner one: a no-op while empty).\n    return { content: '', streaming: false, flush: inner.flush };\n  }\n  return inner;\n};\n","/**\n * React binding for the smooth-stream controller.\n *\n * The return value is deliberately props-shaped: `{ content, streaming }`\n * mirrors the `<AIMarkdown>` props of the same names, so the result\n * spreads into the base component or ANY wrapper (mantine included) in\n * one line:\n *\n * ```tsx\n * const smooth = useSmoothStream({ content, streaming: !done });\n * return <MantineAIMarkdown {...smooth} />;\n * ```\n *\n * Semantics:\n * - Mount snaps to the current `content` — SSR hydration and mid-stream\n *   remounts (route return, list virtualization) show the full text\n *   instantly instead of replaying the typewriter from empty.\n * - While `streaming` is true, content growth animates.\n * - On the `streaming` true→false transition the controller drains the\n *   remaining backlog within its rate-continuity drain window (at most\n *   `3 × drainMs`); the RETURNED `streaming` stays true until drained so\n *   the cursor slot doesn't unmount mid-animation.\n * - Content changes while not streaming snap (no animation).\n *\n * @module components/smoothStream/useSmoothStream\n */\n\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport {\n  createSmoothStreamController,\n  type SmoothStreamOptions,\n  type SmoothStreamPacing,\n} from '@ai-react-markdown/engine';\n\nexport interface UseSmoothStreamOptions {\n  /** Full accumulated markdown source (the same value you would pass to `content`). */\n  content: string;\n  /** Whether the stream is still producing (the same value you would pass to `streaming`). */\n  streaming?: boolean;\n  /**\n   * Named pacing preset — the whole tuning surface at this level:\n   * `'smooth'` (extra buffer, never runs dry), `'balanced'` (default,\n   * minimal lag that still bridges typical bursts), `'responsive'`\n   * (lowest lag, accepts occasional pauses). Numeric parameters live on\n   * {@link createSmoothStreamController} for advanced hosts.\n   */\n  pacing?: SmoothStreamPacing;\n  /**\n   * Fires when the post-stream drain completes — the message is now\n   * fully visible. In practice this is end-of-stream only (the held-back\n   * trailing grapheme keeps the reveal one step short of a LIVE stream,\n   * so mid-stream catch-ups never count as drained); multi-round flows\n   * fire it once per round. Content replacement (regeneration) does NOT\n   * fire it — the replaced message never \"completed\". Read through a\n   * latest-ref: identity changes are safe and never re-trigger anything.\n   */\n  onDrained?: () => void;\n  /** @internal test seam — injectable clock, see {@link SmoothStreamOptions.now}. */\n  now?: SmoothStreamOptions['now'];\n  /** @internal test seam — injectable scheduler, see {@link SmoothStreamOptions.schedule}. */\n  schedule?: SmoothStreamOptions['schedule'];\n}\n\nexport interface UseSmoothStreamResult {\n  /** The paced (revealed-prefix) content — pass as `content`. */\n  content: string;\n  /** True while pixels should still read as streaming — pass as `streaming`. */\n  streaming: boolean;\n  /**\n   * Reveals everything pending immediately (a \"skip animation\" button).\n   * Identity-stable; safe to pass down memoized trees. Spreading it onto\n   * a component is harmless — the base components ignore unknown props.\n   */\n  flush: () => void;\n}\n\nexport const useSmoothStream = ({\n  content,\n  streaming = false,\n  pacing,\n  onDrained,\n  now,\n  schedule,\n}: UseSmoothStreamOptions): UseSmoothStreamResult => {\n  // Live options object: the controller reads the preset at tick time, so\n  // refreshing the field (in the every-render effect below) retunes\n  // pacing without controller churn. It lives in state, not a ref, so the\n  // construction path never reads a ref during render.\n  const [{ controller, liveOptions }] = useState(() => {\n    const initial: SmoothStreamOptions = { pacing, now, schedule };\n    const created = createSmoothStreamController(initial);\n    created.snap(content);\n    return { controller: created, liveOptions: initial };\n  });\n\n  const onDrainedRef = useRef(onDrained);\n  useEffect(() => {\n    // Every-render sync: latest callback + live preset retune. An explicit\n    // write (not Object.assign) so a preset the caller STOPS passing falls\n    // back to the controller default instead of sticking. `liveOptions` is\n    // not render state — it is the deliberately mutable channel the\n    // controller reads at tick time (its identity is fixed for the\n    // component's lifetime), so the immutability rule's premise doesn't\n    // apply here.\n    onDrainedRef.current = onDrained;\n    // eslint-disable-next-line react-hooks/immutability\n    liveOptions.pacing = pacing;\n  });\n\n  // Drained-edge latch (armed = \"currently caught up\"). Declared before\n  // the reaction effect below, which pre-arms it on content replacement.\n  const wasDrainedRef = useRef(true);\n\n  const prevStreamingRef = useRef(false);\n  const prevContentRef = useRef(content);\n  useEffect(() => {\n    // Content replacement (not an append-extension) means the animating\n    // message was aborted, not completed: pre-arm the drained latch so the\n    // snap inside the controller can't fire a spurious onDrained for it.\n    if (!content.startsWith(prevContentRef.current)) wasDrainedRef.current = true;\n    prevContentRef.current = content;\n\n    if (streaming) {\n      controller.update(content);\n    } else if (prevStreamingRef.current) {\n      // Stream just ended: make sure the final text is in, then drain.\n      controller.update(content);\n      controller.finish();\n    } else {\n      controller.snap(content);\n    }\n    prevStreamingRef.current = streaming;\n\n    // Arm the drained latch on BACKLOG FORMATION, not on the first\n    // un-drained notify: update() is silent, so a round whose only notify\n    // is the drain itself (single-grapheme append; a background tab's\n    // mega-reveal) would otherwise find the latch still armed-off from\n    // the previous round and swallow its onDrained. Mid-stream notifies\n    // can never read drained (the held-back tail keeps the reveal short\n    // of a live source), so arming here cannot cause a mid-stream fire —\n    // and after a replacement, snap() leaves the controller drained, so\n    // the pre-arm above is never overridden.\n    if (!controller.isDrained()) wasDrainedRef.current = false;\n  }, [controller, content, streaming]);\n\n  // Drained-edge detection: fire onDrained only when a real backlog\n  // catches up, not on every static snap (those never leave the drained\n  // state, so the edge never arms).\n  useEffect(\n    () =>\n      controller.subscribe(() => {\n        const drained = controller.isDrained();\n        if (drained && !wasDrainedRef.current) onDrainedRef.current?.();\n        wasDrainedRef.current = drained;\n      }),\n    [controller]\n  );\n\n  // Cleanup disposes; StrictMode's dev-only replay then REUSES this same\n  // controller — the replayed effects above (update/snap) and the uSES\n  // resubscribe revive it, rescheduling any surviving backlog. After a\n  // real unmount nothing calls back in, so disposal sticks.\n  useEffect(() => () => controller.dispose(), [controller]);\n\n  const visible = useSyncExternalStore(\n    controller.subscribe,\n    controller.getVisible,\n    // Server snapshot: the full content. Client mount snaps to the same\n    // value, so hydration sees identical text.\n    () => content\n  );\n\n  const flush = useCallback(() => controller.flush(), [controller]);\n\n  return {\n    content: visible,\n    streaming: streaming || visible.length < content.length,\n    flush,\n  };\n};\n","/**\n * `define*` factories — the packaging unit for integration-time\n * configuration (EXECUTION-PLAN §3.3).\n *\n * Factory output is a frozen, fully typed, reference-stable flat prop\n * fragment, spread into `<AIMarkdown>`:\n *\n * ```tsx\n * const THEME = defineTheme({ fontSize: 15, variant: 'default' });\n * const BEHAVIORS = defineBehaviors({ blockMemo: false });\n * const PIPELINE = definePipeline({ contentPreprocessors: [...], sanitizeSchema: mySchema });\n *\n * // runtime-varying fields go AFTER the spreads; later props win\n * <AIMarkdown content={content} {...THEME} {...BEHAVIORS} {...PIPELINE} colorScheme={userScheme} />\n * ```\n *\n * Three disciplines (binding):\n *\n * 1. A factory is identity + types + `Object.freeze`, zero logic. No\n *    default-filling (defaults live only in the component's destructuring),\n *    no merging, no side effects. `define` (vs `create`) signals \"declares\n *    data\", not \"manufactures a live object\".\n * 2. Factories package values decided at integration time. Data, State, and\n *    Document members change per frame/message and get no factory;\n *    runtime-switchable fields may enter a factory as initial values, with\n *    runtime overrides as post-spread props (see `colorScheme` above).\n * 3. Factories are sugar, not gates — passing bare flat props is always legal.\n *\n * Core factories accept core prop types only. Wrappers re-export widened\n * factories for their extension fields (e.g. `defineMantineBehaviors`) —\n * still identity + own types + freeze.\n *\n * @module define\n */\n\nimport type { AIMarkdownProps } from './index';\n\n/** Theme-system props packagable at integration time. */\nexport type AIMarkdownThemeProps = Pick<\n  AIMarkdownProps,\n  'fontSize' | 'variant' | 'colorScheme' | 'Typography' | 'ExtraStyles'\n>;\n\n/** Behavior-system core switches. */\nexport type AIMarkdownBehaviorProps = Pick<\n  AIMarkdownProps,\n  'blockMemo' | 'incrementalParse' | 'preserveOrphanReferences'\n>;\n\n/** Engine payloads + engine plugin selection. */\nexport type AIMarkdownPipelineProps = Pick<\n  AIMarkdownProps,\n  'contentPreprocessors' | 'urlTransform' | 'sanitizeSchema' | 'customComponents' | 'enginePlugins'\n>;\n\n// Deliberately NON-generic signatures: a fresh object literal is checked\n// for excess properties against the concrete parameter type, so passing a\n// field from another system is a compile error. A `<T extends …>` version\n// would let excess keys slip through whenever the literal shares at least\n// one property with the constraint (TS infers T from the literal itself).\n\n/** Freeze a theme fragment. Identity + types + freeze; zero logic. */\nexport function defineTheme(values: AIMarkdownThemeProps): Readonly<AIMarkdownThemeProps> {\n  return Object.freeze(values);\n}\n\n/** Freeze a behaviors fragment. Identity + types + freeze; zero logic. */\nexport function defineBehaviors(values: AIMarkdownBehaviorProps): Readonly<AIMarkdownBehaviorProps> {\n  return Object.freeze(values);\n}\n\n/** Freeze a pipeline fragment. Identity + types + freeze; zero logic. */\nexport function definePipeline(values: AIMarkdownPipelineProps): Readonly<AIMarkdownPipelineProps> {\n  return Object.freeze(values);\n}\n","/**\n * Streaming cursor — positioner shell and default indicator.\n *\n * The shell (`AIMarkdownStreamingCursor`) is a self-contained component\n * mounted via the `streamingCursor` slot on `<AIMarkdown>`. It never moves\n * in the React tree; what moves is the visual position of the indicator:\n * the shell detects the last character of the rendered content, measures it\n * with the Range API, and translates an absolutely-positioned holder to sit\n * right after it. Pixels are moved, not DOM nodes — the shell never enters\n * any React-managed container, so there is no DOM-ownership friction and\n * select-all/copy never picks the cursor up.\n *\n * Engine coupling is zero by construction: the content string, the parse\n * pipeline (hast, splice contract), and the block-memo cache are untouched.\n * Worst cases are cosmetic (a one-frame offset, a conservative hide) and\n * self-heal on the next observer callback.\n *\n * Update channels (see docs/proposals/streaming-cursor.md):\n * - Position (x, y) never enters React state. It changes on every token and\n *   must land in the same frame as the content change, so it is applied\n *   imperatively inside the observer callback — MutationObserver callbacks\n *   run as microtasks BEFORE paint, which is what makes the reposition\n *   flicker-free.\n * - `width`/`height` enter indicator props with an equality short-circuit.\n * - `lastMutationAt` updates once per mutation batch; the indicator is a\n *   leaf, so the per-token leaf re-render is negligible and lets the\n *   indicator reset its stall timer with a plain `useEffect`.\n *\n * @module components/streamingCursor\n */\n\nimport { useEffect, useInsertionEffect, useRef, useState, type ComponentType, type CSSProperties } from 'react';\nimport { detectAnchorTextNode } from './detectAnchor';\n\n/** Props the shell injects into the indicator (the actual visual layer). */\nexport interface AIMarkdownStreamingIndicatorProps {\n  /**\n   * Rendered height (px) of the last character at the anchor. Indicators\n   * use it to match the current line's text size — taller on headings,\n   * shorter on body text.\n   */\n  height: number;\n  /**\n   * Rendered width (px) of the last character at the anchor. Block-style\n   * cursors (e.g. `▍`) can use it to align with the character cell.\n   */\n  width: number;\n  /** Timestamp of the most recent content mutation (`performance.now()` basis). */\n  lastMutationAt: number;\n}\n\nexport type AIMarkdownStreamingIndicatorComponent = ComponentType<AIMarkdownStreamingIndicatorProps>;\n\nexport interface AIMarkdownStreamingCursorProps {\n  /**\n   * The indicator component the shell positions and feeds with\n   * {@link AIMarkdownStreamingIndicatorProps}. Defaults to the built-in\n   * blinking circle. Bind a custom one at module scope:\n   *\n   * ```tsx\n   * const MyCursor = () => <AIMarkdownStreamingCursor indicator={MyIndicator} />;\n   * <AIMarkdown streamingCursor={MyCursor} ... />\n   * ```\n   */\n  indicator?: AIMarkdownStreamingIndicatorComponent;\n}\n\n/** Horizontal gap (px) between the last character and the indicator. */\nconst ANCHOR_GAP = 4;\n\n/** Stall threshold of the DEFAULT indicator. Internal detail, not API. */\nconst STALL_MS = 5000;\n\nconst WRAPPER_STYLE: CSSProperties = {\n  position: 'relative',\n  display: 'block',\n  width: '100%',\n  height: 0,\n  margin: 0,\n  padding: 0,\n};\n\n/**\n * All positioning keys (`display`, `transform`, `left`, `right`) are\n * written imperatively in `measure()`/`hide()` and deliberately do NOT\n * appear in this style object — React's style diff only touches keys it\n * has seen in the prop, so it can never clobber the imperative values, no\n * matter how the object is created. Before the first measurement the\n * holder is empty (the indicator mounts only once an anchor state exists),\n * so nothing is visible without an explicit `display: none`.\n */\nconst HOLDER_STYLE: CSSProperties = {\n  position: 'absolute',\n  top: 0,\n  pointerEvents: 'none',\n};\n\nconst STYLE_MARKER = 'data-aimd-streaming-cursor-style';\n/**\n * Marker VALUE = a fingerprint of the injected rules. Two library versions\n * on one page (micro-frontends, duplicated installs) each dedupe on their\n * own fingerprint, so a version that changes the rules injects its own tag\n * instead of silently inheriting the first-mounted version's. The animation\n * names carry the same suffix — CSS resolves `@keyframes` by name\n * globally, so a same-name/different-body pair would still race (2026-08\n * project review, core-render-07). Bump the fingerprint whenever the\n * keyframes change.\n */\nconst STYLE_FINGERPRINT = 'v2'; // v2: keyframe names carry the suffix (2.4.2)\n/** Animation names DERIVE from the fingerprint, so bumping it versions\n *  the keyframes too — the cross-version isolation no longer rests on\n *  remembering to rename them by hand (v2.4.1 review). */\nconst BLINK_ANIMATION = `aimd-streaming-cursor-blink-${STYLE_FINGERPRINT}`;\nconst SPIN_ANIMATION = `aimd-streaming-cursor-spin-${STYLE_FINGERPRINT}`;\n\nconst CURSOR_KEYFRAMES =\n  `@keyframes ${BLINK_ANIMATION}{0%,100%{opacity:1}50%{opacity:.15}}` +\n  `@keyframes ${SPIN_ANIMATION}{to{transform:rotate(360deg)}}` +\n  // Reduced motion: freeze blink/spin and state transitions. The static\n  // dot/ring still convey streaming vs stalled without movement.\n  '@media (prefers-reduced-motion:reduce){[data-aimd-streaming-indicator] span,[data-aimd-streaming-indicator]{animation:none!important;transition:none!important}}';\n\n/**\n * Injects the cursor keyframes into `document.head` once per document.\n * `useInsertionEffect` runs before layout effects (and never on the\n * server), so the rules exist before anything measures. The tag is\n * deliberately never removed on unmount: orphan keyframes are inert, and\n * refcounting unmounts buys nothing (standard CSS-in-JS practice).\n *\n * Trade-off vs the previous inline `<style>`-per-instance: N concurrent\n * streaming messages now share ONE tag instead of N duplicates. Known\n * boundaries: a Shadow DOM host doesn't see `document.head` styles, and a\n * component portaled into an iframe injects into the PARENT document's\n * head (module-global `document`), not the iframe's — in either case,\n * mount a self-styled custom indicator (the shell itself is style-free).\n */\nfunction useCursorKeyframes() {\n  useInsertionEffect(() => {\n    if (typeof document === 'undefined') return;\n    if (document.head.querySelector(`style[${STYLE_MARKER}=\"${STYLE_FINGERPRINT}\"]`)) return;\n    const tag = document.createElement('style');\n    tag.setAttribute(STYLE_MARKER, STYLE_FINGERPRINT);\n    tag.textContent = CURSOR_KEYFRAMES;\n    document.head.appendChild(tag);\n  }, []);\n}\n\ninterface AnchorMeasure {\n  rect: DOMRect;\n  rtl: boolean;\n}\n\n/**\n * Measure the last non-whitespace character of the anchor text node.\n * Selects the character (not a collapsed end-point) because collapsed\n * ranges return an empty `getClientRects()` list in some engines; the last\n * rect wins when the character straddles a soft wrap. Returns null when the\n * environment cannot measure (jsdom) or the rect is degenerate.\n */\nfunction measureAnchor(anchor: Text): AnchorMeasure | null {\n  const data = anchor.data;\n  const trimmedLength = data.replace(/\\s+$/, '').length;\n  if (trimmedLength === 0) return null;\n  const doc = anchor.ownerDocument;\n  const win = doc?.defaultView;\n  if (!doc || !win) return null;\n  // Range offsets are UTF-16 code units. An emoji tail (astral plane) would\n  // otherwise select only the low surrogate and measure a degenerate\n  // half-glyph rect — step back to the full code point. Multi-code-point\n  // grapheme clusters (ZWJ sequences, combining marks) still anchor to\n  // their last code point; acceptable, the rect stays on the glyph.\n  let start = trimmedLength - 1;\n  const lastUnit = data.charCodeAt(trimmedLength - 1);\n  if (lastUnit >= 0xdc00 && lastUnit <= 0xdfff && trimmedLength >= 2) {\n    const prevUnit = data.charCodeAt(trimmedLength - 2);\n    if (prevUnit >= 0xd800 && prevUnit <= 0xdbff) start = trimmedLength - 2;\n  }\n  let rects: DOMRectList;\n  try {\n    const range = doc.createRange();\n    range.setStart(anchor, start);\n    range.setEnd(anchor, trimmedLength);\n    rects = range.getClientRects();\n  } catch {\n    // Range measurement unavailable (e.g. jsdom) — hide rather than guess.\n    return null;\n  }\n  if (!rects || rects.length === 0) return null;\n  const rect = rects[rects.length - 1];\n  if (rect.width === 0 && rect.height === 0) return null;\n  const parent = anchor.parentElement;\n  const rtl = parent ? win.getComputedStyle(parent).direction === 'rtl' : false;\n  return { rect, rtl };\n}\n\n/**\n * Default indicator: a blinking circle whose diameter tracks the line\n * height. After {@link STALL_MS} of silence it cross-fades into a rotating\n * ring (spinner) in the two-tone style of the reference demo: a muted\n * full-circle track plus a full-strength top segment that rotates. Blinking\n * pauses while the ring spins — a spinner communicates \"waiting\" on its\n * own — and the filled blinking circle returns as soon as content flows\n * again.\n */\nfunction DefaultStreamingIndicator({ height, lastMutationAt }: AIMarkdownStreamingIndicatorProps) {\n  // `stalled` is derived, not set: the timer only records WHEN the stall\n  // verdict fired. The condition requires the verdict to be a full\n  // STALL_MS after the CURRENT `lastMutationAt` — not merely after it —\n  // which closes a race: a timer armed for an old prop can fire in the\n  // window between a fresh mutation and this effect's cleanup, and a bare\n  // `stalledSince > lastMutationAt` would then declare a stall 1 ms into\n  // active streaming. A newer mutation always un-stalls without any state\n  // write (and without a synchronous setState in the effect body, which\n  // react-hooks forbids).\n  useCursorKeyframes();\n  const [stalledSince, setStalledSince] = useState<number | null>(null);\n  const stalled = stalledSince !== null && stalledSince >= lastMutationAt + STALL_MS;\n  useEffect(() => {\n    // Chromium can fire timers marginally EARLY relative to\n    // `performance.now()`. A single-shot timer stamping `now` would then\n    // fail the deadline check by a fraction of a millisecond and never\n    // retry — a sub-millisecond coin flip that silently kills the stall\n    // state (found as a flaky StallRecovery story). So: re-check on fire\n    // and re-arm while the deadline hasn't truly passed, then stamp the\n    // DEADLINE itself — exact for this `lastMutationAt`, and still\n    // fail-closed against any newer mutation's later deadline.\n    let timer: ReturnType<typeof setTimeout>;\n    const arm = () => {\n      const remaining = STALL_MS - (performance.now() - lastMutationAt);\n      if (remaining <= 0) {\n        setStalledSince(lastMutationAt + STALL_MS);\n        return;\n      }\n      timer = setTimeout(arm, Math.max(1, Math.ceil(remaining)));\n    };\n    timer = setTimeout(arm, Math.max(0, Math.ceil(STALL_MS - (performance.now() - lastMutationAt))));\n    return () => clearTimeout(timer);\n  }, [lastMutationAt]);\n\n  const size = Math.max(4, Math.round(height * 0.45));\n  // Symmetric horizontal breathing room around the dot, reserved INSIDE the\n  // indicator's box (constant layout, direction-agnostic). When the spinner\n  // takes over it grows to exactly fill this reserved space — \"growing by\n  // eating the whitespace\" — so the enlargement is pure transform and the\n  // outer footprint never changes.\n  const sideGap = Math.max(2, Math.round(size * 0.25));\n  // The ring is authored at its FINAL diameter with a thin border and\n  // parked scaled-DOWN while the dot shows. Settling at scale(1) keeps the\n  // border at its exact CSS width — scaling a small ring UP would multiply\n  // (and blur) the border, which reads as chunky. The grown ring does NOT\n  // consume the whole reserved gap: a sliver (`edgeKeep`, ~1/3 of the gap)\n  // stays as breathing room around the spinner.\n  const edgeKeep = Math.max(1, Math.round(sideGap / 3));\n  const ringGrow = sideGap - edgeKeep;\n  const ringDiameter = size + 2 * ringGrow;\n  const ringWidth = Math.max(1.5, Math.round(ringDiameter * 0.12));\n  const ringRestScale = Math.round((size / ringDiameter) * 100) / 100;\n  // Stacked layers cross-faded by opacity (compositor-friendly — no layout\n  // property is ever animated). The demo's two-tone spinner (muted\n  // `--border-strong` track + accent `--fill-primary` top segment) is\n  // decomposed into a static 25%-opacity track ring and a rotating\n  // full-strength top-segment ring, so the whole visual stays\n  // currentColor-only with no color-mix dependency. The two rings live in a\n  // group that owns fade and scale, so the top segment's spin animation\n  // never competes for the same `transform`. The dot's blink animation is\n  // disabled while stalled so the opacity transition owns the property.\n  const ringLayer: CSSProperties = {\n    position: 'absolute',\n    inset: 0,\n    boxSizing: 'border-box',\n    borderRadius: '50%',\n    borderStyle: 'solid',\n    borderWidth: ringWidth,\n  };\n  return (\n    <span\n      data-aimd-streaming-indicator=\"\"\n      data-stalled={stalled ? '' : undefined}\n      style={{\n        display: 'block',\n        position: 'relative',\n        width: size + 2 * sideGap,\n        height: size,\n        marginTop: Math.round((height - size) / 2),\n        userSelect: 'none',\n      }}\n    >\n      <span\n        style={{\n          position: 'absolute',\n          left: sideGap,\n          top: 0,\n          width: size,\n          height: size,\n        }}\n      >\n        <span\n          style={{\n            position: 'absolute',\n            inset: 0,\n            borderRadius: '50%',\n            backgroundColor: 'currentColor',\n            opacity: stalled ? 0 : 1,\n            transition: 'opacity 300ms ease',\n            animation: stalled ? 'none' : `${BLINK_ANIMATION} 900ms ease-in-out infinite`,\n          }}\n        />\n        <span\n          style={{\n            position: 'absolute',\n            inset: -ringGrow,\n            opacity: stalled ? 1 : 0,\n            transform: stalled ? 'scale(1)' : `scale(${ringRestScale})`,\n            transition: 'opacity 300ms ease, transform 300ms ease',\n          }}\n        >\n          <span\n            style={{\n              ...ringLayer,\n              borderColor: 'currentColor',\n              opacity: 0.25,\n            }}\n          />\n          <span\n            data-aimd-streaming-indicator-ring=\"\"\n            style={{\n              ...ringLayer,\n              borderColor: 'transparent',\n              borderTopColor: 'currentColor',\n              animation: stalled ? `${SPIN_ANIMATION} 800ms linear infinite` : 'none',\n            }}\n          />\n        </span>\n      </span>\n    </span>\n  );\n}\n\n/**\n * Positioner shell. Renders a zero-height wrapper (the coordinate base and\n * the handle to the content root via `parentElement`), detects the anchor,\n * and keeps the indicator positioned through three pre-paint signal\n * sources: a MutationObserver on the content root (tokens, tail-block\n * morphs), a ResizeObserver (reflow from container width changes), and\n * `document.fonts.ready` (one re-measure after font swap). Detection\n * failure hides the indicator; the next mutation re-detects.\n *\n * SSR renders the (invisible) wrapper only — detection needs a real DOM, so\n * the indicator appears after the first client-side measurement.\n */\nexport const AIMarkdownStreamingCursor = ({\n  indicator: Indicator = DefaultStreamingIndicator,\n}: AIMarkdownStreamingCursorProps) => {\n  const wrapperRef = useRef<HTMLSpanElement>(null);\n  const holderRef = useRef<HTMLSpanElement>(null);\n  const [anchorState, setAnchorState] = useState<AIMarkdownStreamingIndicatorProps | null>(null);\n  const anchorStateRef = useRef<AIMarkdownStreamingIndicatorProps | null>(null);\n\n  useEffect(() => {\n    const wrapper = wrapperRef.current;\n    const root = wrapper?.parentElement;\n    if (!wrapper || !root) return;\n\n    const hide = () => {\n      const holder = holderRef.current;\n      if (holder) holder.style.display = 'none';\n      if (anchorStateRef.current !== null) {\n        anchorStateRef.current = null;\n        setAnchorState(null);\n      }\n    };\n\n    const measure = (isMutation: boolean) => {\n      const holder = holderRef.current;\n      if (!holder) return;\n      const anchor = detectAnchorTextNode(root, wrapper);\n      const measured = anchor && measureAnchor(anchor);\n      if (!measured) {\n        hide();\n        return;\n      }\n      const wrapperRect = wrapper.getBoundingClientRect();\n      // Ancestor `transform: scale` correction: client rects are measured in\n      // post-transform pixels, but `translate()` applies in the wrapper's\n      // LOCAL units — under a scaled ancestor (entrance animations, zoom\n      // wrappers) the raw delta would be scaled twice. `offsetWidth` is the\n      // local layout width, so the ratio recovers the effective scale.\n      // Rotation/skew ancestors remain unsupported (see proposal, 已知边界).\n      const localWidth = wrapper.offsetWidth;\n      const scale = localWidth > 0 && wrapperRect.width > 0 ? wrapperRect.width / localWidth : 1;\n      if (!Number.isFinite(scale) || scale <= 0) {\n        hide();\n        return;\n      }\n      const { rect, rtl } = measured;\n      const maxX = wrapper.clientWidth;\n      let x: number;\n      if (rtl) {\n        // Right-anchor: the holder's RIGHT edge lands at (char left − gap),\n        // so the indicator grows leftward, away from the text. With\n        // `left: auto; right: 0` the untranslated right edge sits at the\n        // wrapper's right edge; the translate is the (negative) distance\n        // from there, in local units.\n        x = (rect.left - ANCHOR_GAP - wrapperRect.right) / scale;\n        if (maxX > 0) x = Math.min(0, Math.max(x, -(maxX - 1)));\n        holder.style.left = 'auto';\n        holder.style.right = '0px';\n      } else {\n        x = (rect.right + ANCHOR_GAP - wrapperRect.left) / scale;\n        if (maxX > 0) x = Math.max(0, Math.min(x, maxX - 1));\n        holder.style.left = '0px';\n        holder.style.right = 'auto';\n      }\n      const y = (rect.top - wrapperRect.top) / scale;\n      holder.style.display = 'block';\n      holder.style.transform = `translate(${x}px, ${y}px)`;\n      const width = Math.round(rect.width);\n      const height = Math.round(rect.height);\n      const prev = anchorStateRef.current;\n      const lastMutationAt = isMutation || !prev ? performance.now() : prev.lastMutationAt;\n      if (!prev || prev.width !== width || prev.height !== height || prev.lastMutationAt !== lastMutationAt) {\n        const next = { width, height, lastMutationAt };\n        anchorStateRef.current = next;\n        setAnchorState(next);\n      }\n    };\n\n    measure(true);\n\n    const mutationObserver = new MutationObserver((records) => {\n      // The shell's own subtree mutates when the indicator mounts/unmounts;\n      // those records must not reset the stall clock or re-trigger work.\n      if (records.every((record) => wrapper.contains(record.target))) return;\n      measure(true);\n    });\n    // Two documented semantics of this observer:\n    // - The stall clock counts ANY non-wrapper mutation under the content\n    //   root as activity (a mermaid repaint, a coordinated footer\n    //   re-render) — \"the message is alive\", not strictly \"new tokens\n    //   arrived\".\n    // - Attribute-only changes are a known blind spot: a class swap that\n    //   re-wraps text without childList/characterData records moves the\n    //   anchor with no callback; the cursor self-heals on the next\n    //   mutation. `attributes: true` was deliberately not enabled — it\n    //   would fire on every imperative style write of sibling instances.\n    mutationObserver.observe(root, { childList: true, characterData: true, subtree: true });\n\n    let resizeObserver: ResizeObserver | null = null;\n    if (typeof ResizeObserver !== 'undefined') {\n      resizeObserver = new ResizeObserver(() => measure(false));\n      resizeObserver.observe(root);\n    }\n\n    let cancelled = false;\n    document.fonts?.ready.then(() => {\n      if (!cancelled) measure(false);\n    });\n\n    return () => {\n      cancelled = true;\n      mutationObserver.disconnect();\n      resizeObserver?.disconnect();\n    };\n  }, []);\n\n  return (\n    <span ref={wrapperRef} data-aimd-streaming-cursor=\"\" aria-hidden=\"true\" style={WRAPPER_STYLE}>\n      <span ref={holderRef} style={HOLDER_STYLE}>\n        {anchorState ? <Indicator {...anchorState} /> : null}\n      </span>\n    </span>\n  );\n};\n","/**\n * Anchor detection for the streaming cursor.\n *\n * Walks the rendered content DOM to find the text node the cursor should\n * attach after: the deepest last text inside the last content block. The\n * walk is a whitelist descent — only elements whose content is plain\n * rendered prose are entered. Anything else (code, KaTeX output, SVG such\n * as rendered mermaid, raw-HTML-produced unknown tags, void elements)\n * aborts the walk and the cursor hides for that frame (the shell re-detects\n * on the next mutation).\n *\n * Only a tiny structural surface of the DOM is touched (`nodeType`,\n * `childNodes`, `tagName`, `classList.contains`, `hasAttribute`,\n * `getAttribute`, `data`), so the walk is unit-testable in the node\n * environment with plain-object fakes — no jsdom required.\n *\n * Definition tails: the renderer stamps a hidden tail marker while a\n * (footnote / link-reference) definition is streaming (see\n * `tailSignal.ts`), because definitions render in the relocated footer —\n * the DOM tail and the source tail diverge and no DOM-only heuristic can\n * reconcile them. With a marker present the walk anchors inside the\n * TARGETED footer `<li>` (or hides); without one it keeps its original\n * bet: skip the footer, anchor at the body tail.\n *\n * @module components/streamingCursor/detectAnchor\n */\n\nimport { sourceIdFromFootnoteLiId } from '@ai-react-markdown/engine';\nimport { normalizeId } from '@ai-react-markdown/engine';\n\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n\n/** Attribute names of the tail marker `MarkdownContent` stamps while\n *  streaming (see `tailSignal.ts`). Read via `getAttribute` so the walk's\n *  plain-object fake surface stays tiny. */\nconst TAIL_KIND_ATTR = 'data-aimd-tail-kind';\nconst TAIL_LABEL_ATTR = 'data-aimd-tail-label';\nconst TAIL_CLOBBER_ATTR = 'data-aimd-clobber-prefix';\n\n/**\n * Elements the walk may enter. Block-level containers markdown rendering\n * produces, plus inline formatting containers. Everything absent is\n * conservatively unsafe — this is what makes raw-HTML output (arbitrary\n * tags) and void elements abort the walk without an explicit denylist.\n * `SPAN` is listed because typography helpers (e.g. CJK spacing) wrap prose\n * in spans; KaTeX output is also span-based, which is why the walk\n * additionally rejects `.katex` / `.katex-display` by class.\n */\nconst SAFE_CONTAINERS = new Set([\n  // Block containers\n  'P',\n  'H1',\n  'H2',\n  'H3',\n  'H4',\n  'H5',\n  'H6',\n  'UL',\n  'OL',\n  'LI',\n  'DL',\n  'DT',\n  'DD',\n  'TABLE',\n  'THEAD',\n  'TBODY',\n  'TFOOT',\n  'TR',\n  'TD',\n  'TH',\n  'BLOCKQUOTE',\n  // Inline containers\n  'A',\n  'EM',\n  'STRONG',\n  'B',\n  'I',\n  'S',\n  'U',\n  'DEL',\n  'INS',\n  'MARK',\n  'SUB',\n  'SUP',\n  'SMALL',\n  'SPAN',\n]);\n\nfunction isWhitespaceOnlyText(node: Node): boolean {\n  return node.nodeType === TEXT_NODE && !/\\S/.test((node as Text).data);\n}\n\n/** Last child that is a non-whitespace text node or an element, or null. */\nfunction lastMeaningfulChild(parent: Node, skip?: (node: Node) => boolean): Node | null {\n  const children = parent.childNodes;\n  for (let i = children.length - 1; i >= 0; i--) {\n    const child = children[i];\n    if (skip && skip(child)) continue;\n    if (child.nodeType === TEXT_NODE) {\n      if (isWhitespaceOnlyText(child)) continue;\n      return child;\n    }\n    if (child.nodeType === ELEMENT_NODE) return child;\n    // Comments and other node types are never anchors and never containers.\n  }\n  return null;\n}\n\nfunction isFootnoteSection(node: Node): boolean {\n  if (node.nodeType !== ELEMENT_NODE) return false;\n  const el = node as Element;\n  return el.tagName === 'SECTION' && el.hasAttribute('data-footnotes');\n}\n\nfunction isTailMarker(node: Node): boolean {\n  return node.nodeType === ELEMENT_NODE && (node as Element).hasAttribute(TAIL_KIND_ATTR);\n}\n\nfunction isFootnoteBackref(node: Node): boolean {\n  return node.nodeType === ELEMENT_NODE && (node as Element).hasAttribute('data-footnote-backref');\n}\n\n/** Whitelist descent to the deepest last text, threading `skip` through\n *  EVERY level — the footer descent needs it because a definition body\n *  ending in a paragraph carries its backref `<a>↩</a>` INSIDE that\n *  trailing paragraph, not as a direct `<li>` child. */\nfunction descendToText(start: Node | null, skip?: (node: Node) => boolean): Text | null {\n  let node = start;\n  while (node) {\n    if (node.nodeType === TEXT_NODE) return node as Text;\n    if (node.nodeType !== ELEMENT_NODE) return null;\n    const el = node as Element;\n    if (!SAFE_CONTAINERS.has(el.tagName)) return null;\n    if (el.classList.contains('katex') || el.classList.contains('katex-display')) return null;\n    node = lastMeaningfulChild(el, skip);\n  }\n  return null;\n}\n\n/** The last tail-marker element among `root`'s children, or null. The\n *  renderer appends it after the content blocks, so scan from the end. */\nfunction findTailMarker(root: Element): Element | null {\n  const children = root.childNodes;\n  for (let i = children.length - 1; i >= 0; i--) {\n    const child = children[i];\n    if (isTailMarker(child)) return child as Element;\n  }\n  return null;\n}\n\n/** Locate the footnote `<li>` whose id encodes `label`, using the exact\n *  same two-tier id parsing the aggregate-footer harvest uses\n *  (`sourceIdFromFootnoteLiId`): exact clobber-prefix slice when the\n *  marker supplies one, `user-content-fn-` regex fallback otherwise. */\nfunction findFootnoteLi(root: Element, label: string, clobberPrefix: string | null): Element | null {\n  const section = ((): Element | null => {\n    const children = root.childNodes;\n    for (let i = children.length - 1; i >= 0; i--) {\n      if (isFootnoteSection(children[i])) return children[i] as Element;\n    }\n    return null;\n  })();\n  if (!section) return null;\n  const target = normalizeId(label);\n  // section children: sr-only heading + <ol>; defs are the <ol>'s <li>s.\n  for (const child of Array.from(section.childNodes)) {\n    if (child.nodeType !== ELEMENT_NODE || (child as Element).tagName !== 'OL') continue;\n    for (const li of Array.from(child.childNodes)) {\n      if (li.nodeType !== ELEMENT_NODE || (li as Element).tagName !== 'LI') continue;\n      const id = (li as Element).getAttribute('id');\n      if (!id) continue;\n      const sourceId = sourceIdFromFootnoteLiId(id, clobberPrefix ?? undefined);\n      if (sourceId !== null && normalizeId(sourceId) === target) return li as Element;\n    }\n  }\n  return null;\n}\n\n/**\n * Find the text node the streaming cursor anchors after, or `null` when the\n * cursor must hide for this frame.\n *\n * When the renderer's tail marker says the source tail is inside a footnote\n * definition, the anchor is the deepest last text of THAT definition's\n * footer `<li>` (targeted by label — footer `<li>` order is first-reference\n * order, not definition source order, so \"last li\" would mis-anchor on\n * out-of-order references), skipping backref links at every level. A\n * missing li (aggregate footer living in another chunk's root, an\n * unreferenced definition, an id whose encoding defeats matching) hides the\n * cursor — conservative, never wrong-place. An `invisible-def` tail (link\n * reference definitions render nothing) hides too. Without a marker the\n * walk keeps its original bet: skip the footer, anchor at the body tail.\n *\n * @param root - The content root: the DOM element whose children are the\n *   rendered top-level blocks (the cursor shell's `parentElement`).\n * @param exclude - The shell's own wrapper element (a child of `root`),\n *   skipped so the cursor never anchors to itself.\n */\nexport function detectAnchorTextNode(root: Element, exclude: Element | null): Text | null {\n  const marker = findTailMarker(root);\n  if (marker) {\n    const kind = marker.getAttribute(TAIL_KIND_ATTR);\n    if (kind === 'invisible-def') return null;\n    if (kind === 'footnote-def') {\n      const label = marker.getAttribute(TAIL_LABEL_ATTR);\n      if (!label) return null;\n      const li = findFootnoteLi(root, label, marker.getAttribute(TAIL_CLOBBER_ATTR));\n      if (!li) return null;\n      return descendToText(li, isFootnoteBackref);\n    }\n    // Unknown kind (a future marker version): fall through to the default\n    // walk rather than hiding — fail toward today's behavior.\n  }\n  return descendToText(lastMeaningfulChild(root, (n) => n === exclude || isFootnoteSection(n) || isTailMarker(n)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,IAAAA,iBAAgF;;;ACbhF,IAAAC,gBAA4G;AAE5G,IAAAC,iBAAoD;;;ACQpD,oBAAqC;AACrC,IAAAC,iBAAsE;AAGtE,IAAM,UAAU;AAUT,IAAM,4BAA4B,OAAO,OAAO;AAAA,E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WAAW,OAAO,WAAW;AACrF;AAEA,IAAM,iCAA6B,qBAAK,+BAA+B;AACvE,2BAA2B,cAAc;AAClC,IAAM,yBAAyB;","names":["import_react","import_react","import_engine","import_engine","__DEV__","__DEV__","document","import_react","Symbol","objectProto","nativeObjectToString","symToStringTag","funcProto","objectProto","funcToString","hasOwnProperty","Map","objectProto","hasOwnProperty","objectProto","hasOwnProperty","HASH_UNDEFINED","HASH_UNDEFINED","othValue","Uint8Array","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","objectProto","objectProto","hasOwnProperty","propertyIsEnumerable","Buffer","MAX_SAFE_INTEGER","argsTag","boolTag","dateTag","errorTag","funcTag","mapTag","numberTag","regexpTag","setTag","stringTag","arrayBufferTag","dataViewTag","freeExports","freeModule","moduleExports","objectProto","hasOwnProperty","objectProto","objectProto","hasOwnProperty","COMPARE_PARTIAL_FLAG","objectProto","hasOwnProperty","Promise","Set","WeakMap","mapTag","objectTag","setTag","weakMapTag","dataViewTag","COMPARE_PARTIAL_FLAG","argsTag","arrayTag","objectTag","objectProto","hasOwnProperty","import_engine","import_react","import_react","import_jsx_runtime","import_unist_util_visit","import_engine","import_engine","import_unist_util_visit","import_engine","import_engine","import_engine","import_engine","root","import_engine","import_engine","import_engine","import_engine","import_react","import_engine","import_react","import_engine","import_react","import_jsx_runtime","import_react","import_react","import_react","import_engine","import_hast_util_to_jsx_runtime","import_jsx_runtime","import_engine","import_jsx_runtime","defaultSanitizeSchema","def","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_react","__DEV__","useIsomorphicLayoutEffect","AIMarkdownStabilityPolicy","WARN_COOLDOWN_MS","import_react","import_jsx_runtime","import_react","import_react","import_engine","import_engine","import_react","import_engine","isFootnoteSection","root","import_jsx_runtime","root","import_engine","import_jsx_runtime","sanitizeSchema"]}