function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { Checkbox, Image } from "antd";
import { toJsxRuntime } from "hast-util-to-jsx-runtime";
import React from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { ToolUseBarThink } from "../ToolUseBarThink";
import { debugInfo } from "../Utils/debugUtils";
import { FncRefForMarkdown, extractFootnoteRefFromSupChildren } from "./FncRefForMarkdown";
import { createHastProcessor } from "./processor";
import { INITIAL_FENCE_STATE, updateFenceStateForLine } from "./streaming/fenceTracker";
import { StreamAnimWrap } from "./streaming/StreamAnimWrap";
import { extractChildrenText, extractLanguageFromClassName } from "./utils/astExtract";
var THINK_BLOCK_STYLES = {
    root: {
        boxSizing: 'border-box',
        maxWidth: '680px',
        marginTop: 8
    }
};
/** <think> 标签 → ToolUseBarThink（MarkdownRenderer 无 Slate 上下文，直接渲染） */ var ThinkBlockRendererComponent = function ThinkBlockRendererComponent(props) {
    var children = props.children;
    var content = extractChildrenText(children);
    var isLoading = content.endsWith('...');
    return React.createElement(ToolUseBarThink, {
        testId: 'think-block-renderer',
        styles: THINK_BLOCK_STYLES,
        toolName: isLoading ? '深度思考...' : '深度思考',
        thinkContent: content,
        status: isLoading ? 'loading' : 'success'
    });
};
/** hast → React 组件映射，与 MarkdownEditor Readonly 的 data-be / prefixCls 对齐 */ var buildEditorAlignedComponents = function buildEditorAlignedComponents(prefixCls, userComponents, streaming, linkConfig, fncProps, streamingParagraphAnimation, eleRender) {
    var listCls = "".concat(prefixCls, "-list");
    var tableCls = "".concat(prefixCls, "-content-table");
    var contentCls = prefixCls; // e.g. ant-agentic-md-editor-content
    /**
   * 段落级流式淡入：通过模块级 StreamAnimWrap 组件实现，避免 buildEditorAlignedComponents
   * 重建时 React 把 wrap 当作新组件类型导致整段子树卸载重挂。
   */ var wrapAnimation = function wrapAnimation(children) {
        return jsx(StreamAnimWrap, {
            streaming: streaming,
            streamingParagraphAnimation: streamingParagraphAnimation,
            children: children
        });
    };
    /**
   * 应用 eleRender 拦截：若用户返回非 undefined 值则使用，否则使用 defaultDom。
   * 不对 table-cell/table-row 等子结构元素（th/td/tr/thead/tbody）进行拦截，
   * 与 Slate 模式保持一致。
   */ var applyEleRender = function applyEleRender(tagName, props, defaultDom) {
        if (!eleRender) return defaultDom;
        var result = eleRender(_object_spread({
            tagName: tagName
        }, props), defaultDom);
        return result !== undefined ? result : defaultDom;
    };
    return _object_spread({
        // ================================================================
        // Block 级别元素
        // ================================================================
        p: function p(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('div', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'paragraph',
                'data-testid': 'markdown-paragraph',
                children: wrapAnimation(children)
            }));
            return applyEleRender('p', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h1: function h1(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h1', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-1',
                children: children
            }));
            return applyEleRender('h1', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h2: function h2(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h2', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-2',
                children: children
            }));
            return applyEleRender('h2', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h3: function h3(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h3', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-3',
                children: children
            }));
            return applyEleRender('h3', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h4: function h4(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h4', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-4',
                children: children
            }));
            return applyEleRender('h4', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h5: function h5(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h5', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-5',
                children: children
            }));
            return applyEleRender('h5', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        h6: function h6(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('h6', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'head',
                'data-testid': 'markdown-heading-6',
                children: children
            }));
            return applyEleRender('h6', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        blockquote: function blockquote(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('blockquote', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'blockquote',
                'data-testid': 'markdown-blockquote',
                children: children
            }));
            return applyEleRender('blockquote', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        ul: function ul(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('div', {
                className: "".concat(listCls, "-container"),
                'data-be': 'list',
                'data-testid': 'markdown-unordered-list',
                children: jsx('ul', _object_spread_props(_object_spread({}, rest), {
                    className: "".concat(listCls, " ul"),
                    children: children
                }))
            });
            return applyEleRender('ul', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        ol: function ol(props) {
            var node = props.node, children = props.children, start = props.start, rest = _object_without_properties(props, [
                "node",
                "children",
                "start"
            ]);
            var defaultDom = jsx('div', {
                className: "".concat(listCls, "-container"),
                'data-be': 'list',
                'data-testid': 'markdown-ordered-list',
                children: jsx('ol', _object_spread_props(_object_spread({}, rest), {
                    className: "".concat(listCls, " ol"),
                    start: start,
                    children: children
                }))
            });
            return applyEleRender('ol', _object_spread({
                node: node,
                children: children,
                start: start
            }, rest), defaultDom);
        },
        li: function li(props) {
            var node = props.node, children = props.children, className = props.className, rest = _object_without_properties(props, [
                "node",
                "children",
                "className"
            ]);
            var isTask = className === 'task-list-item' || Array.isArray(className) && className.includes('task-list-item');
            var defaultDom;
            if (isTask) {
                var childArray = Array.isArray(children) ? children : [
                    children
                ];
                var checked = false;
                var filteredChildren = childArray.filter(function(child) {
                    var _child_props;
                    if (React.isValidElement(child) && ((_child_props = child.props) === null || _child_props === void 0 ? void 0 : _child_props.type) === 'checkbox') {
                        var _child_props1;
                        checked = !!((_child_props1 = child.props) === null || _child_props1 === void 0 ? void 0 : _child_props1.checked);
                        return false;
                    }
                    return true;
                });
                defaultDom = jsxs('li', _object_spread_props(_object_spread({}, rest), {
                    className: "".concat(listCls, "-item ").concat(listCls, "-task"),
                    'data-be': 'list-item',
                    'data-testid': 'markdown-task-item',
                    children: [
                        jsx('span', {
                            className: "".concat(listCls, "-check-item"),
                            contentEditable: false,
                            'data-check-item': true,
                            children: jsx(Checkbox, {
                                checked: checked,
                                disabled: true
                            })
                        })
                    ].concat(_to_consumable_array(filteredChildren))
                }));
            } else {
                defaultDom = jsx('li', _object_spread_props(_object_spread({}, rest), {
                    className: "".concat(listCls, "-item"),
                    'data-be': 'list-item',
                    'data-testid': 'markdown-list-item',
                    children: children
                }));
            }
            return applyEleRender('li', _object_spread({
                node: node,
                children: children,
                className: className
            }, rest), defaultDom);
        },
        table: function table(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('div', {
                className: tableCls,
                'data-testid': 'markdown-table',
                children: jsx('div', {
                    className: "".concat(tableCls, "-container"),
                    children: jsx('table', _object_spread_props(_object_spread({}, rest), {
                        className: "".concat(tableCls, "-readonly-table"),
                        style: {
                            tableLayout: 'auto',
                            width: '100%'
                        },
                        children: children
                    }))
                })
            });
            return applyEleRender('table', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        thead: function thead(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            return jsx('thead', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-thead',
                children: children
            }));
        },
        tbody: function tbody(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            return jsx('tbody', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-tbody',
                children: children
            }));
        },
        tr: function tr(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            return jsx('tr', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-tr',
                children: children
            }));
        },
        th: function th(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            return jsx('th', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-th',
                style: {
                    whiteSpace: 'normal',
                    maxWidth: '20%'
                },
                children: wrapAnimation(children)
            }));
        },
        td: function td(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            return jsx('td', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-td',
                style: {
                    whiteSpace: 'normal',
                    maxWidth: '20%'
                },
                children: wrapAnimation(children)
            }));
        },
        // input[type=checkbox]：task list 的 checkbox（兜底，主逻辑在 li 中）
        input: function input(props) {
            var _node = props.node, type = props.type, checked = props.checked, disabled = props.disabled, rest = _object_without_properties(props, [
                "node",
                "type",
                "checked",
                "disabled"
            ]);
            if (type === 'checkbox') {
                return jsx(Checkbox, {
                    checked: !!checked,
                    disabled: true,
                    'data-testid': 'markdown-checkbox'
                });
            }
            return jsx('input', _object_spread_props(_object_spread({}, rest), {
                type: type,
                checked: checked,
                disabled: disabled
            }));
        },
        // ================================================================
        // Leaf 级别（行内元素）
        // ================================================================
        a: function a(props) {
            var node = props.node, href = props.href, _origOnClick = props.onClick, rest = _object_without_properties(props, [
                "node",
                "href",
                "onClick"
            ]);
            var openInNewTab = (linkConfig === null || linkConfig === void 0 ? void 0 : linkConfig.openInNewTab) !== false;
            var defaultDom = jsx('a', _object_spread_props(_object_spread({}, rest), {
                href: href,
                'data-be': 'text',
                'data-url': 'url',
                'data-testid': 'markdown-link',
                target: openInNewTab ? '_blank' : undefined,
                rel: openInNewTab ? 'noopener noreferrer' : undefined,
                onClick: function onClick(e) {
                    if (linkConfig === null || linkConfig === void 0 ? void 0 : linkConfig.onClick) {
                        var res = linkConfig.onClick(href);
                        if (res === false) {
                            e.preventDefault();
                            return;
                        }
                    }
                }
            }));
            return applyEleRender('a', _object_spread({
                node: node,
                href: href
            }, rest), defaultDom);
        },
        strong: function strong(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('strong', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-bold',
                style: {
                    fontWeight: 'bold'
                },
                children: children
            }));
            return applyEleRender('strong', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        em: function em(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('em', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-italic',
                style: {
                    fontStyle: 'italic'
                },
                children: children
            }));
            return applyEleRender('em', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        del: function del(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('del', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-strikethrough',
                children: children
            }));
            return applyEleRender('del', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        code: function code(props) {
            var _node = props.node, children = props.children, className = props.className, rest = _object_without_properties(props, [
                "node",
                "children",
                "className"
            ]);
            var fenceLang = extractLanguageFromClassName(className);
            return jsx('code', _object_spread_props(_object_spread({}, rest), {
                'data-testid': fenceLang ? 'markdown-fenced-code' : 'markdown-inline-code',
                className: fenceLang ? className : "".concat(contentCls, "-inline-code"),
                children: children
            }));
        },
        mark: function mark(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('mark', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-mark',
                style: {
                    background: 'var(--ant-color-warning-bg, #f59e0b)',
                    padding: '0.1em 0.2em',
                    borderRadius: 2
                },
                children: children
            }));
            return applyEleRender('mark', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        kbd: function kbd(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('kbd', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-kbd',
                style: {
                    padding: '0.1em 0.4em',
                    fontSize: '0.85em',
                    border: '1px solid var(--color-gray-border-light, #d9d9d9)',
                    borderRadius: 3,
                    boxShadow: '0 1px 0 var(--color-gray-border-light, #d9d9d9)',
                    fontFamily: 'Consolas, Monaco, "Courier New", monospace'
                },
                children: children
            }));
            return applyEleRender('kbd', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        sub: function sub(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('sub', _object_spread_props(_object_spread({}, rest), {
                'data-testid': 'markdown-sub',
                children: children
            }));
            return applyEleRender('sub', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        // ================================================================
        // 代码块 pre > code → 路由到自定义渲染器
        pre: function pre(props) {
            var _hastPreNode_children_, _hastPreNode_children, _hastPreNode_children__properties;
            var hastPreNode = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var codeChild = Array.isArray(children) ? children[0] : children;
            var codeProps = (codeChild === null || codeChild === void 0 ? void 0 : codeChild.props) || {};
            var codeHastClass = (hastPreNode === null || hastPreNode === void 0 ? void 0 : (_hastPreNode_children = hastPreNode.children) === null || _hastPreNode_children === void 0 ? void 0 : (_hastPreNode_children_ = _hastPreNode_children[0]) === null || _hastPreNode_children_ === void 0 ? void 0 : _hastPreNode_children_.type) === 'element' && hastPreNode.children[0].tagName === 'code' ? (_hastPreNode_children__properties = hastPreNode.children[0].properties) === null || _hastPreNode_children__properties === void 0 ? void 0 : _hastPreNode_children__properties.className : undefined;
            var language = extractLanguageFromClassName(codeProps.className);
            if (!language) {
                language = extractLanguageFromClassName(codeHastClass);
            }
            var CodeBlockComponent = userComponents.__codeBlock || userComponents.code;
            if (CodeBlockComponent) {
                return jsx(CodeBlockComponent, _object_spread_props(_object_spread({}, rest), {
                    language: language,
                    children: codeProps.children,
                    node: hastPreNode
                }));
            }
            var defaultDom = jsxs('pre', _object_spread_props(_object_spread({}, rest), {
                children: [
                    children
                ]
            }));
            return applyEleRender('pre', _object_spread({
                node: hastPreNode,
                children: children
            }, rest), defaultDom);
        },
        img: function img(props) {
            var node = props.node, src = props.src, alt = props.alt, width = props.width, height = props.height, rest = _object_without_properties(props, [
                "node",
                "src",
                "alt",
                "width",
                "height"
            ]);
            var imgWidth = width ? Number(width) || width : 400;
            var defaultDom = jsx('div', {
                'data-be': 'image',
                'data-testid': 'markdown-image',
                style: {
                    position: 'relative',
                    userSelect: 'none',
                    width: '100%',
                    maxWidth: '100%',
                    boxSizing: 'border-box'
                },
                children: jsx('div', {
                    style: {
                        padding: 4,
                        userSelect: 'none',
                        display: 'flex',
                        flexDirection: 'column',
                        width: '100%',
                        maxWidth: '100%',
                        boxSizing: 'border-box'
                    },
                    'data-testid': 'image-container',
                    'data-be': 'image-container',
                    children: jsx(Image, {
                        src: src,
                        alt: alt || 'image',
                        width: imgWidth,
                        height: height,
                        preview: {
                            getContainer: function getContainer() {
                                return document.body;
                            }
                        },
                        referrerPolicy: 'no-referrer',
                        draggable: false,
                        style: {
                            maxWidth: '100%',
                            height: 'auto',
                            display: 'block'
                        }
                    })
                })
            });
            return applyEleRender('img', _object_spread({
                node: node,
                src: src,
                alt: alt,
                width: width,
                height: height
            }, rest), defaultDom);
        },
        // 视频：对齐 ReadonlyMedia 的 video 处理
        video: function video(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('div', {
                'data-be': 'media',
                'data-testid': 'markdown-video',
                style: {
                    position: 'relative',
                    width: '100%',
                    maxWidth: '100%',
                    margin: '0.5em 0'
                },
                children: jsx('video', _object_spread_props(_object_spread({}, rest), {
                    controls: true,
                    style: {
                        maxWidth: '100%',
                        borderRadius: 8
                    },
                    children: children
                }))
            });
            return applyEleRender('video', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        // 音频：对齐 ReadonlyMedia 的 audio 处理
        audio: function audio(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var defaultDom = jsx('div', {
                'data-be': 'media',
                'data-testid': 'markdown-audio',
                style: {
                    position: 'relative',
                    width: '100%',
                    margin: '0.5em 0'
                },
                children: jsx('audio', _object_spread_props(_object_spread({}, rest), {
                    controls: true,
                    style: {
                        width: '100%'
                    },
                    children: children
                }))
            });
            return applyEleRender('audio', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        // iframe
        iframe: function iframe(props) {
            var node = props.node, rest = _object_without_properties(props, [
                "node"
            ]);
            var defaultDom = jsx('div', {
                'data-testid': 'markdown-iframe',
                style: {
                    position: 'relative',
                    width: '100%',
                    margin: '0.5em 0'
                },
                children: jsx('iframe', _object_spread_props(_object_spread({}, rest), {
                    style: {
                        width: '100%',
                        minHeight: 300,
                        border: '1px solid var(--color-gray-border-light, #e8e8e8)',
                        borderRadius: 8
                    }
                }))
            });
            return applyEleRender('iframe', _object_spread({
                node: node
            }, rest), defaultDom);
        },
        hr: function hr(props) {
            var node = props.node, rest = _object_without_properties(props, [
                "node"
            ]);
            var defaultDom = jsx('hr', _object_spread_props(_object_spread({}, rest), {
                'data-be': 'hr',
                'data-testid': 'markdown-hr'
            }));
            return applyEleRender('hr', _object_spread({
                node: node
            }, rest), defaultDom);
        },
        // 脚注引用 sup > a（remark-gfm 有定义时生成）— 与 Slate FncLeaf 对齐
        sup: function sup(props) {
            var node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            var meta = extractFootnoteRefFromSupChildren(children);
            if (meta) {
                return jsx(FncRefForMarkdown, {
                    fncProps: fncProps,
                    linkConfig: linkConfig,
                    identifier: meta.identifier,
                    url: meta.url,
                    children: children
                });
            }
            var defaultDom = jsx('span', _object_spread_props(_object_spread({}, rest), {
                'data-fnc': 'fnc',
                'data-testid': 'markdown-footnote-ref',
                className: "".concat(contentCls, "-fnc"),
                style: {
                    fontSize: 12,
                    cursor: 'pointer'
                },
                children: children
            }));
            return applyEleRender('sup', _object_spread({
                node: node,
                children: children
            }, rest), defaultDom);
        },
        span: function span(props) {
            var _node = props.node, children = props.children, rest = _object_without_properties(props, [
                "node",
                "children"
            ]);
            if (rest['data-fnc'] === 'fnc') {
                var raw = rest['data-fnc-name'];
                var identifier = raw !== undefined && raw !== null && String(raw).length > 0 ? String(raw) : extractChildrenText(children) || '?';
                return jsx(FncRefForMarkdown, {
                    fncProps: fncProps,
                    linkConfig: linkConfig,
                    identifier: identifier,
                    children: children
                });
            }
            return jsx('span', _object_spread_props(_object_spread({}, rest), {
                children: children
            }));
        },
        section: function section(props) {
            var _node = props.node, children = props.children, className = props.className, rest = _object_without_properties(props, [
                "node",
                "children",
                "className"
            ]);
            var isFootnotes = className === 'footnotes' || typeof (rest === null || rest === void 0 ? void 0 : rest['data-footnotes']) !== 'undefined';
            if (isFootnotes) {
                return jsx('div', _object_spread_props(_object_spread({}, rest), {
                    'data-be': 'footnoteDefinition',
                    'data-testid': 'markdown-footnote-section',
                    style: {
                        fontSize: 12,
                        borderTop: '1px solid var(--color-gray-border-light, #e8e8e8)',
                        marginTop: 16,
                        paddingTop: 8
                    },
                    children: children
                }));
            }
            return jsx('section', _object_spread_props(_object_spread({}, rest), {
                className: className,
                children: children
            }));
        },
        think: ThinkBlockRendererComponent,
        thinking: ThinkBlockRendererComponent,
        answer: function answer(props) {
            var _node = props.node, children = props.children;
            return jsx(Fragment, {
                children: children
            });
        }
    }, userComponents);
};
var ERROR_FALLBACK_STYLE = {
    margin: '0.5em 0',
    padding: '0.5em 0.75em',
    background: 'var(--ant-color-error-bg, #fff2f0)',
    border: '1px solid var(--ant-color-error-border, #ffccc7)',
    borderRadius: 4,
    fontSize: '0.85em',
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word'
};
/** markdown 片段 → React 元素；解析失败时降级为原文 <pre> 兜底，避免内容静默丢失。 */ var renderMarkdownBlock = function renderMarkdownBlock(blockContent, processor, components) {
    if (!blockContent.trim()) return null;
    try {
        var mdast = processor.parse(blockContent);
        var hast = processor.runSync(mdast);
        return toJsxRuntime(hast, {
            Fragment: Fragment,
            jsx: jsx,
            jsxs: jsxs,
            components: components,
            passNode: true
        });
    } catch (error) {
        debugInfo('[MarkdownRenderer] renderMarkdownBlock failed', {
            error: (error === null || error === void 0 ? void 0 : error.message) || String(error),
            blockContent: blockContent
        });
        return jsx('pre', {
            'data-testid': 'markdown-block-error-fallback',
            style: ERROR_FALLBACK_STYLE,
            children: blockContent
        });
    }
};
var LIST_ITEM_PATTERN = /^(\s*)([-+*]|\d+[.)]) /;
var BLOCKQUOTE_PATTERN = /^\s*>/;
var HTML_COMMENT_PATTERN = /^\s*<!--/;
var FOOTNOTE_DEF_PATTERN = /^\s*\[\^/;
/** GFM 表格行：以 `|` 开头并以 `|` 结尾，至少一段内容（含分隔行 `| --- |`） */ var TABLE_LINE_PATTERN = /^\s*\|.*\|\s*$/;
/** 按单空行拆块，保留围栏代码块、列表、blockquote、HTML 注释+表格、脚注定义、GFM 表格的连续性 */ var splitMarkdownBlocks = function splitMarkdownBlocks(content) {
    var lines = content.split('\n');
    var blocks = [];
    var current = [];
    var fenceState = _object_spread({}, INITIAL_FENCE_STATE);
    var inList = false;
    var inBlockquote = false;
    var inTable = false;
    var pendingBlankLines = 0;
    var lastNonEmptyLine = function lastNonEmptyLine() {
        for(var i = current.length - 1; i >= 0; i--){
            if (current[i] !== '') return current[i];
        }
        return '';
    };
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = lines[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var line = _step.value;
            fenceState = updateFenceStateForLine(fenceState, line);
            if (fenceState.inFenced) {
                if (pendingBlankLines > 0) {
                    for(var i = 0; i < pendingBlankLines; i++)current.push('');
                    pendingBlankLines = 0;
                }
                current.push(line);
                continue;
            }
            if (line === '') {
                if (current.length > 0) {
                    pendingBlankLines++;
                }
                continue;
            }
            if (pendingBlankLines > 0) {
                var nextIsListItem = LIST_ITEM_PATTERN.test(line);
                var nextIsBlockquote = BLOCKQUOTE_PATTERN.test(line);
                var nextIsTableLine = TABLE_LINE_PATTERN.test(line);
                var nextIsContinuation = inList && (nextIsListItem || /^\s+\S/.test(line)) || inBlockquote && nextIsBlockquote || inTable && nextIsTableLine;
                var prevIsHtmlComment = HTML_COMMENT_PATTERN.test(lastNonEmptyLine());
                var nextIsFootnoteDef = FOOTNOTE_DEF_PATTERN.test(line);
                if (current.length > 0 && !nextIsContinuation && !prevIsHtmlComment && !nextIsFootnoteDef) {
                    blocks.push(current.join('\n'));
                    current = [];
                    inList = false;
                    inBlockquote = false;
                    inTable = false;
                } else {
                    for(var i1 = 0; i1 < pendingBlankLines; i1++)current.push('');
                }
                pendingBlankLines = 0;
            }
            inList = LIST_ITEM_PATTERN.test(line) || inList && /^\s+\S/.test(line);
            inBlockquote = BLOCKQUOTE_PATTERN.test(line);
            inTable = TABLE_LINE_PATTERN.test(line) || inTable && /^\s+\S/.test(line);
            current.push(line);
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    if (current.length > 0) {
        blocks.push(current.join('\n'));
    }
    if (blocks.length === 0) {
        blocks.push('');
    }
    return blocks;
};
export { buildEditorAlignedComponents, createHastProcessor, renderMarkdownBlock, splitMarkdownBlocks };
