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_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
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_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
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, { useContext } from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
import remarkFrontmatter from "remark-frontmatter";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import { visit } from "unist-util-visit";
import { remarkDirectiveContainer } from "../MarkdownEditor/editor/parser/remarkDirectiveContainer";
import remarkDirectiveContainersOnly from "../MarkdownEditor/editor/parser/remarkDirectiveContainersOnly";
import { convertParagraphToImage, fixStrongWithSpecialChars, protectJinjaDollarInText } from "../MarkdownEditor/editor/parser/remarkParse";
import { REMARK_REHYPE_DIRECTIVE_HANDLERS } from "../MarkdownEditor/editor/utils/markdownToHtml";
import { parseChineseCurrencyToNumber } from "../Plugins/chart/utils";
import { ToolUseBarThink } from "../ToolUseBarThink";
import AnimationText from "./AnimationText";
import { FncRefForMarkdown, extractFootnoteRefFromSupChildren } from "./FncRefForMarkdown";
import { INITIAL_FENCE_STATE, updateFenceStateForLine } from "./streaming/fenceTracker";
import { StreamingAnimationContext } from "./StreamingAnimationContext";
var INLINE_MATH_WITH_SINGLE_DOLLAR = {
    singleDollarTextMath: true
};
var FRONTMATTER_LANGUAGES = [
    'yaml'
];
var REMARK_DIRECTIVE_CONTAINER_OPTIONS = {
    className: 'markdown-container',
    titleElement: {
        className: [
            'markdown-container__title'
        ]
    }
};
var remarkRehypePlugin = remarkRehype;
var FOOTNOTE_REF_PATTERN = /\[\^([^\]]+)\]/g;
var CHART_COMMENT_PATTERN = /^<!--\s*(\[[\s\S]*\]|\{[\s\S]*\})\s*-->$/;
var extractCellText = function extractCellText1(cell) {
    if (!(cell === null || cell === void 0 ? void 0 : cell.children)) return '';
    return cell.children.map(function(child) {
        if (child.type === 'text') return child.value || '';
        if (child.children) return extractCellText(child);
        return '';
    }).join('').trim();
};
/**
 * 从 mdast table 节点提取列名和数据
 */ var extractTableData = function extractTableData(tableNode) {
    var _loop = function(i) {
        var row = tableNode.children[i];
        if (!(row === null || row === void 0 ? void 0 : row.children)) return "continue";
        var record = {
            key: "row-".concat(i)
        };
        row.children.forEach(function(cell, j) {
            if (j < columns.length) {
                var val = extractCellText(cell);
                if (val === '') {
                    record[columns[j].dataIndex] = val;
                } else {
                    var num = Number(val);
                    if (Number.isFinite(num)) {
                        record[columns[j].dataIndex] = num;
                    } else {
                        var cn = parseChineseCurrencyToNumber(val);
                        record[columns[j].dataIndex] = cn !== null ? cn : val;
                    }
                }
            }
        });
        dataSource.push(record);
    };
    var _tableNode_children, _headerRow_children;
    if (!((_tableNode_children = tableNode.children) === null || _tableNode_children === void 0 ? void 0 : _tableNode_children.length)) return null;
    var headerRow = tableNode.children[0];
    if (!(headerRow === null || headerRow === void 0 ? void 0 : (_headerRow_children = headerRow.children) === null || _headerRow_children === void 0 ? void 0 : _headerRow_children.length)) return null;
    var columns = headerRow.children.map(function(cell) {
        var text = extractCellText(cell);
        return {
            title: text,
            dataIndex: text,
            key: text
        };
    });
    var dataSource = [];
    for(var i = 1; i < tableNode.children.length; i++)_loop(i);
    return {
        columns: columns,
        dataSource: dataSource
    };
};
/**
 * remark 插件：将 "HTML 注释（图表配置）+ 表格" 组合转为 chart 代码块。
 *
 * 在 MarkdownEditor 中，parseTableOrChart 负责此逻辑。
 * 在 MarkdownRenderer 中，此插件在 mdast 层面完成等价转换。
 *
 * 匹配模式：
 * ```
 * <!-- [{"chartType":"line","x":"month","y":"value",...}] -->
 * | month | value |
 * |-------|-------|
 * | 2024  | 100   |
 * ```
 */ var remarkChartFromComment = function remarkChartFromComment() {
    return function(tree) {
        var children = tree.children;
        if (!children || !Array.isArray(children)) return;
        var toRemove = [];
        for(var i = 0; i < children.length - 1; i++){
            var _node_value;
            var node = children[i];
            var next = children[i + 1];
            if (node.type !== 'html' || next.type !== 'table') continue;
            var match = (_node_value = node.value) === null || _node_value === void 0 ? void 0 : _node_value.match(CHART_COMMENT_PATTERN);
            if (!match) continue;
            var chartConfig = void 0;
            try {
                chartConfig = JSON.parse(match[1]);
            } catch (unused) {
                continue;
            }
            if (!Array.isArray(chartConfig)) chartConfig = [
                chartConfig
            ];
            var hasChartType = chartConfig.some(function(c) {
                return c.chartType && c.chartType !== 'table';
            });
            if (!hasChartType) continue;
            var tableData = extractTableData(next);
            if (!tableData) continue;
            var chartJson = JSON.stringify({
                config: chartConfig,
                columns: tableData.columns,
                dataSource: tableData.dataSource
            });
            children[i] = {
                type: 'code',
                lang: 'chart',
                value: chartJson
            };
            toRemove.push(i + 1);
            i++;
        }
        for(var j = toRemove.length - 1; j >= 0; j--){
            children.splice(toRemove[j], 1);
        }
    };
};
/**
 * rehype 插件：将文本中残留的 [^N] 模式转为 fnc 标记元素。
 *
 * remark-gfm 只在有对应 footnoteDefinition 时才会转换 footnoteReference，
 * 但 AI 对话场景中 [^1] 常用作内联引用（无底部定义）。
 * 此插件在 hast 层面补充处理这些"裸引用"。
 */ var rehypeFootnoteRef = function rehypeFootnoteRef() {
    return function(tree) {
        visit(tree, 'text', function(node, index, parent) {
            if (!parent || index === undefined) return;
            var value = node.value;
            if (!FOOTNOTE_REF_PATTERN.test(value)) return;
            FOOTNOTE_REF_PATTERN.lastIndex = 0;
            var children = [];
            var lastIndex = 0;
            var match;
            while((match = FOOTNOTE_REF_PATTERN.exec(value)) !== null){
                if (match.index > lastIndex) {
                    children.push({
                        type: 'text',
                        value: value.slice(lastIndex, match.index)
                    });
                }
                children.push({
                    type: 'element',
                    tagName: 'span',
                    properties: {
                        'data-fnc': 'fnc',
                        'data-fnc-name': match[1]
                    },
                    children: [
                        {
                            type: 'text',
                            value: match[1]
                        }
                    ]
                });
                lastIndex = match.index + match[0].length;
            }
            if (lastIndex < value.length) {
                children.push({
                    type: 'text',
                    value: value.slice(lastIndex)
                });
            }
            if (children.length > 0) {
                var _parent_children;
                (_parent_children = parent.children).splice.apply(_parent_children, [
                    index,
                    1
                ].concat(_to_consumable_array(children)));
                return index + children.length;
            }
        });
    };
};
var createHastProcessor = function createHastProcessor(extraRemarkPlugins, config) {
    var processor = unified();
    processor.use(remarkParse).use(remarkGfm, {
        singleTilde: false
    }).use(fixStrongWithSpecialChars).use(convertParagraphToImage).use(protectJinjaDollarInText).use(remarkMath, INLINE_MATH_WITH_SINGLE_DOLLAR).use(remarkFrontmatter, FRONTMATTER_LANGUAGES).use(remarkDirectiveContainersOnly).use(remarkDirectiveContainer, REMARK_DIRECTIVE_CONTAINER_OPTIONS).use(remarkChartFromComment).use(remarkRehypePlugin, {
        allowDangerousHtml: true,
        handlers: REMARK_REHYPE_DIRECTIVE_HANDLERS
    }).use(rehypeRaw).use(rehypeKatex, {
        strict: 'ignore'
    }).use(rehypeFootnoteRef);
    if (extraRemarkPlugins) {
        extraRemarkPlugins.forEach(function(entry) {
            if (Array.isArray(entry)) {
                var _processor;
                var _entry = _to_array(entry), plugin = _entry[0], pluginOptions = _entry.slice(1);
                (_processor = processor).use.apply(_processor, [
                    plugin
                ].concat(_to_consumable_array(pluginOptions)));
            } else {
                processor.use(entry);
            }
        });
    }
    if (config === null || config === void 0 ? void 0 : config.markedConfig) {
        config.markedConfig.forEach(function(entry) {
            if (Array.isArray(entry)) {
                var _processor;
                var _entry = _to_array(entry), plugin = _entry[0], pluginOptions = _entry.slice(1);
                (_processor = processor).use.apply(_processor, [
                    plugin
                ].concat(_to_consumable_array(pluginOptions)));
            } else {
                processor.use(entry);
            }
        });
    }
    return processor;
};
var extractLanguageFromClassName = function extractLanguageFromClassName(className) {
    if (!className) return undefined;
    var flat = typeof className === 'string' ? className : className.map(String).join(' ');
    var classes = flat.split(/\s+/).filter(Boolean);
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = classes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var cls = _step.value;
            var match = cls.match(/^language-(.+)$/);
            if (match) return match[1];
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return undefined;
};
var extractChildrenText = function extractChildrenText1(children) {
    var _children_props;
    if (typeof children === 'string') return children;
    if (typeof children === 'number') return String(children);
    if (Array.isArray(children)) return children.map(extractChildrenText).join('');
    if (React.isValidElement(children) && ((_children_props = children.props) === null || _children_props === void 0 ? void 0 : _children_props.children)) {
        return extractChildrenText(children.props.children);
    }
    return '';
};
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
    /** 仅当 streaming、末块动画上下文允许且未显式关闭段落动画时包 AnimationText */ var StreamAnimWrap = function StreamAnimWrap(param) {
        var children = param.children;
        var _ref;
        var ctx = useContext(StreamingAnimationContext);
        var animateBlock = (_ref = ctx === null || ctx === void 0 ? void 0 : ctx.animateBlock) !== null && _ref !== void 0 ? _ref : true;
        var allow = !!streaming && animateBlock && streamingParagraphAnimation !== false;
        if (!allow) return children;
        return jsx(AnimationText, {
            children: children
        });
    };
    StreamAnimWrap.displayName = 'StreamAnimWrap';
    var wrapAnimation = function wrapAnimation(children) {
        return jsx(StreamAnimWrap, {
            children: children
        });
    };
    /**
   * 应用 eleRender 拦截：若用户返回非 undefined 值则使用，否则使用 defaultDom。
   * 不对 table-cell/table-row 等子结构元素（th/td/tr/thead/tbody）进行拦截，
   * 与 Slate 模式保持一致。
   */ var applyEleRender = function applyEleRender(tagName, props, defaultDom) {
        var skip = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
        if (!eleRender || skip) 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);
};
/** markdown 片段 → React 元素 */ 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 (unused) {
        return null;
    }
};
var LIST_ITEM_PATTERN = /^(\s*)([-+*]|\d+[.)]) /;
var BLOCKQUOTE_PATTERN = /^\s*>/;
var HTML_COMMENT_PATTERN = /^\s*<!--/;
var FOOTNOTE_DEF_PATTERN = /^\s*\[\^/;
/** 按单空行拆块，保留围栏代码块、列表、blockquote、HTML 注释+表格、脚注定义的连续性 */ 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 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 nextIsContinuation = inList && (nextIsListItem || /^\s+\S/.test(line)) || inBlockquote && nextIsBlockquote;
                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;
                } 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);
            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 };
