/**
 * 此文件包含大量相互依赖的函数，为了保持代码的可读性和逻辑分组，
 * 我们允许函数在定义前使用（函数提升）
 */ /* eslint-disable @typescript-eslint/no-use-before-define */ /* eslint-disable @typescript-eslint/no-unused-expressions */ 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 _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
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 _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _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 json5 from "json5";
//@ts-ignore
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
import { remark } from "remark";
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 { fixStrongWithSpecialChars } from "./remarkParse";
import { htmlToFragmentList } from "../plugins/insertParsedHtmlNodes";
import { EditorUtils } from "../utils";
import partialJsonParse from "./json-parse";
import mdastParser from "./remarkParse";
// 常量定义
var EMPTY_LINE_DISTANCE_THRESHOLD = 4; // 两个元素之间的行距阈值
var EMPTY_LINE_CALCULATION_OFFSET = 2; // 计算空行数量时的偏移量
var EMPTY_LINE_DIVISOR = 2; // 计算空行数量的除数
var MIN_TABLE_CELL_LENGTH = 5; // 表格单元格最小长度
var INLINE_MATH_SUFFIX_PATTERN = '(?:%|[kKmMbB]|千|万|亿|兆|万亿|百万|亿万)?';
var INLINE_MATH_CURRENCY_PATTERN = new RegExp("^[+-]?\\d{1,3}(?:,\\d{3})*(?:\\.\\d+)?".concat(INLINE_MATH_SUFFIX_PATTERN, "$"));
var INLINE_MATH_SIMPLE_NUMBER_PATTERN = new RegExp("^[+-]?\\d+(?:\\.\\d+)?".concat(INLINE_MATH_SUFFIX_PATTERN, "$"));
var shouldTreatInlineMathAsText = function(rawValue) {
    var trimmedValue = rawValue.trim();
    if (!trimmedValue) {
        return true;
    }
    if (/[=^_\\{}]/.test(trimmedValue)) {
        return false;
    }
    return INLINE_MATH_CURRENCY_PATTERN.test(trimmedValue) || INLINE_MATH_SIMPLE_NUMBER_PATTERN.test(trimmedValue);
};
// 处理schema类型语言的辅助函数
var processSchemaLanguage = function(element, value) {
    var json = [];
    try {
        json = json5.parse(value || '[]');
    } catch (error) {
        try {
            json = partialJsonParse(value || '[]');
        } catch (error) {
            json = value;
            console.error('parse schema error', error);
        }
    }
    return _object_spread_props(_object_spread({}, element), {
        type: 'apaasify',
        value: json,
        children: [
            {
                text: value
            }
        ]
    });
};
// 语言类型处理策略配置
var LANGUAGE_HANDLERS = {
    mermaid: function(element) {
        return _object_spread_props(_object_spread({}, element), {
            type: 'mermaid'
        });
    },
    schema: processSchemaLanguage,
    apaasify: processSchemaLanguage,
    apassify: processSchemaLanguage,
    katex: function(element) {
        return _object_spread_props(_object_spread({}, element), {
            type: 'katex'
        });
    },
    'agentar-card': processSchemaLanguage
};
var advancedNumericCheck = function(value) {
    var numericPattern = /^[-+]?[0-9,]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
    return typeof value === 'number' || typeof value === 'string' && numericPattern.test(value);
};
var isNumericValue = function(value) {
    return typeof value === 'number' || !isNaN(parseFloat(value)) && isFinite(value) || advancedNumericCheck(value);
};
/**
 * 判断是否包含不完整输入
 * 如果一行中包含可能尚未完成的数字输入，返回 true
 */ var hasIncompleteNumericInput = function(values) {
    // 检查是否有可能是正在输入的不完整数字
    // 例如: '12.' 或 '0.' 或 '-' 或 仅有一个数字字符的情况
    return values.some(function(val) {
        if (typeof val !== 'string') return false;
        return val.endsWith('.') && /\d/.test(val) || // 以小数点结尾
        val === '-' || // 只有负号
        val === '+' || // 只有正号
        val.length === 1 && /\d/.test(val) // 只有一个数字
        ;
    });
};
var getColumnAlignment = function(data, columns) {
    if (!data.length) return [];
    // 缓存上一次的对齐结果，避免频繁切换
    var prevAlignments = [];
    return columns.map(function(col, index) {
        var values = data.map(function(row) {
            return row[col.dataIndex];
        }).filter(Boolean);
        values === null || values === void 0 ? void 0 : values.pop();
        // 如果检测到可能正在输入的数字，保持当前对齐状态
        if (hasIncompleteNumericInput(values)) {
            return prevAlignments[index] || null;
        }
        var alignment = values.every(isNumericValue) ? 'right' : null;
        prevAlignments[index] = alignment;
        return alignment;
    });
};
var stringifyObj = remark().use(remarkParse).use(fixStrongWithSpecialChars).use(remarkMath, {
    singleDollarTextMath: false
}).use(remarkRehype, {
    allowDangerousHtml: true
}).use(rehypeRaw).use(rehypeKatex).use(remarkGfm).use(remarkFrontmatter, [
    'yaml'
]);
var myRemark = {
    stringify: function(obj) {
        var mdStr = stringifyObj.stringify(obj);
        return mdStr;
    }
};
/**
 * 检测和解析 think 标签
 * @param str - 要检测的字符串
 * @returns think 标签的内容，如果不是 think 标签则返回 null
 */ var findThinkElement = function(str) {
    try {
        // 匹配 <think>内容</think> 格式
        var thinkMatch = str.match(/^\s*<think>([\s\S]*?)<\/think>\s*$/);
        if (thinkMatch) {
            return {
                content: thinkMatch[1].trim()
            };
        }
        return null;
    } catch (e) {
        return null;
    }
};
/**
 * 检测和解析 answer 标签
 * @param str - 要检测的字符串
 * @returns answer 标签的内容，如果不是 answer 标签则返回 null
 */ var findAnswerElement = function(str) {
    try {
        // 匹配 <answer>内容</answer> 格式
        var answerMatch = str.match(/^\s*<answer>([\s\S]*?)<\/answer>\s*$/);
        if (answerMatch) {
            return {
                content: answerMatch[1].trim()
            };
        }
        return null;
    } catch (e) {
        return null;
    }
};
/**
 * 从 HTML 字符串中提取媒体元素属性
 */ var extractMediaAttributes = function(str) {
    var _str_match, _str_match1, _str_match2, _str_match3, _str_match4;
    return {
        height: (_str_match = str.match(/height="(\d+)"/)) === null || _str_match === void 0 ? void 0 : _str_match[1],
        width: (_str_match1 = str.match(/width="(\d+)"/)) === null || _str_match1 === void 0 ? void 0 : _str_match1[1],
        align: (_str_match2 = str.match(/data-align="(\w+)"/)) === null || _str_match2 === void 0 ? void 0 : _str_match2[1],
        alt: (_str_match3 = str.match(/alt="([^"\n]+)"/)) === null || _str_match3 === void 0 ? void 0 : _str_match3[1],
        controls: str.match(/controls/),
        autoplay: str.match(/autoplay/),
        loop: str.match(/loop/),
        muted: str.match(/muted/),
        poster: (_str_match4 = str.match(/poster="([^"\n]+)"/)) === null || _str_match4 === void 0 ? void 0 : _str_match4[1]
    };
};
/**
 * 构建媒体元素对象
 */ var buildMediaElement = function(url, tagName, attrs) {
    return {
        url: url,
        height: attrs.height ? +attrs.height : undefined,
        width: attrs.width ? +attrs.width : undefined,
        align: attrs.align,
        alt: attrs.alt,
        tagName: tagName,
        controls: !!attrs.controls,
        autoplay: !!attrs.autoplay,
        loop: !!attrs.loop,
        muted: !!attrs.muted,
        poster: attrs.poster
    };
};
/**
 * 从字符串中提取视频源 URL
 */ var extractVideoSource = function(str, tagName) {
    // 首先尝试从标签本身获取 src 属性
    var url = str.match(/src="([^"\n]+)"/);
    // 如果是 video 标签且没有找到 src，尝试从 source 标签中获取
    if (tagName === 'video' && !url) {
        var sourceMatch = str.match(/<source[^>]*src="([^"\n]+)"[^>]*>/);
        if (sourceMatch) {
            url = sourceMatch;
        }
    }
    return url === null || url === void 0 ? void 0 : url[1];
};
/**
 * 查找并解析媒体元素（img/video/iframe）
 */ var findImageElement = function(str) {
    try {
        // 首先尝试匹配包含 source 标签的 video 格式
        var videoWithSourceMatch = str.match(/^\s*<video[^>\n]*>[\s\S]*?<source[^>]*src="([^"\n]+)"[^>]*>[\s\S]*?<\/video>\s*$/);
        if (videoWithSourceMatch) {
            var attrs = extractMediaAttributes(str);
            return buildMediaElement(videoWithSourceMatch[1], 'video', attrs);
        }
        // 尝试匹配各种媒体标签格式
        var patterns = [
            /^\s*<(img|video|iframe)[^>\n]*>.*?<\/(?:img|video|iframe)>\s*$/,
            /^\s*<(img|video|iframe)[^>\n]*\/?>(.*<\/(?:img|video|iframe)>)?\s*$/,
            /^\s*<(img|video|iframe)[^>\n]*\/>\s*$/,
            /^\s*<(img|video|iframe)[^>\n]*>\s*$/
        ];
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            for(var _iterator = patterns[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var pattern = _step.value;
                var match = str.match(pattern);
                if (match) {
                    var _match__match;
                    var tagName = (_match__match = match[0].match(/<(img|video|iframe)/)) === null || _match__match === void 0 ? void 0 : _match__match[1];
                    var url = extractVideoSource(match[0], tagName);
                    var attrs1 = extractMediaAttributes(match[0]);
                    return buildMediaElement(url, tagName, attrs1);
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        return null;
    } catch (e) {
        console.error('Failed to parse media element:', e);
        return null;
    }
};
/**
 * 根据媒体元素信息创建编辑器节点
 */ var createMediaNodeFromElement = function(mediaElement) {
    if (!mediaElement) return null;
    // 根据标签类型确定媒体类型
    var mediaTypeMap = {
        video: 'video',
        iframe: 'iframe',
        img: 'image'
    };
    var mediaType = mediaTypeMap[mediaElement.tagName] || 'image';
    return EditorUtils.createMediaNode(decodeURIComponentUrl(mediaElement.url || ''), mediaType, {
        align: mediaElement.align,
        alt: mediaElement.alt,
        height: mediaElement.height,
        width: mediaElement.width,
        controls: mediaElement.controls,
        autoplay: mediaElement.autoplay,
        loop: mediaElement.loop,
        muted: mediaElement.muted,
        poster: mediaElement.poster
    });
};
var findAttachment = function(str) {
    try {
        var match = str.match(/^\s*<a[^>\n]*download[^>\n]*\/?>(.*<\/a>:?)?\s*$/);
        if (match) {
            var url = match[0].match(/href="([^"\n]+)"/);
            var size = match[0].match(/data-size="(\d+)"/);
            if (url) {
                return {
                    url: url[1],
                    size: Number((size === null || size === void 0 ? void 0 : size[1]) || 0)
                };
            }
        }
        return null;
    } catch (e) {
        return null;
    }
};
var parseText = function(els) {
    var leaf = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        data: {}
    };
    var leafs = [];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = els[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var n = _step.value;
            if (n.type === 'strong') leafs = leafs.concat(parseText(n.children, _object_spread_props(_object_spread({}, leaf), {
                bold: true
            })));
            if (n.type === 'emphasis') leafs = leafs.concat(parseText(n.children, _object_spread_props(_object_spread({}, leaf), {
                italic: true
            })));
            if (n.type === 'delete') leafs = leafs.concat(parseText(n.children, _object_spread_props(_object_spread({}, leaf), {
                strikethrough: true
            })));
            if (n.type === 'link') {
                leafs = leafs.concat(parseText(n.children, _object_spread_props(_object_spread({}, leaf), {
                    url: n === null || n === void 0 ? void 0 : n.url
                })));
            }
            if (n.type === 'inlineCode') leafs.push(_object_spread_props(_object_spread({}, leaf), {
                text: n.value,
                code: true
            }));
            if (n.type === 'inlineMath') {
                var inlineMathValue = typeof n.value === 'string' ? n.value : '';
                if (shouldTreatInlineMathAsText(inlineMathValue)) {
                    leafs.push(_object_spread_props(_object_spread({}, leaf), {
                        text: "$".concat(inlineMathValue, "$")
                    }));
                    continue;
                }
                // 处理内联数学公式，返回一个特殊的节点而不是叶子节点
                leafs.push(_object_spread_props(_object_spread({}, leaf), {
                    type: 'inline-katex',
                    children: [
                        {
                            text: inlineMathValue
                        }
                    ]
                }));
                continue; // 跳过后面的默认处理
            }
            // @ts-ignore
            leafs.push(_object_spread_props(_object_spread({}, leaf), {
                text: n.value || ''
            }));
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return leafs;
};
var parseTableOrChart = function(table, preNode, plugins) {
    var _table_children, _tableHeader_children, _table_children_slice, _table_children1, _table_align, _config_at, _config_at1;
    var keyMap = new Map();
    // @ts-ignore
    var config = // @ts-ignore
    (preNode === null || preNode === void 0 ? void 0 : preNode.type) === 'code' && // @ts-ignore
    (preNode === null || preNode === void 0 ? void 0 : preNode.language) === 'html' && (// @ts-ignore
    preNode === null || preNode === void 0 ? void 0 : preNode.otherProps) ? preNode === null || preNode === void 0 ? void 0 : preNode.otherProps : {};
    var tableHeader = table === null || table === void 0 ? void 0 : (_table_children = table.children) === null || _table_children === void 0 ? void 0 : _table_children.at(0);
    var columns = (tableHeader === null || tableHeader === void 0 ? void 0 : (_tableHeader_children = tableHeader.children) === null || _tableHeader_children === void 0 ? void 0 : _tableHeader_children.map(function(node) {
        var _myRemark_stringify;
        return (_myRemark_stringify = myRemark.stringify({
            type: 'root',
            children: [
                node
            ]
        })) === null || _myRemark_stringify === void 0 ? void 0 : _myRemark_stringify.replace(/\n/g, '').trim();
    }).map(function(title) {
        return (title === null || title === void 0 ? void 0 : title.replaceAll('\\', '')) || ' ';
    }).map(function(title, index) {
        if (keyMap.has(title)) {
            var _title_replace_replace_replace, _title_replace_replace, _title_replace;
            keyMap.set(title, keyMap.get(title) + '_' + index);
            return {
                title: title === null || title === void 0 ? void 0 : (_title_replace = title.replace(/\n/g, '')) === null || _title_replace === void 0 ? void 0 : (_title_replace_replace = _title_replace.replace(/\\(?=")/g, '')) === null || _title_replace_replace === void 0 ? void 0 : (_title_replace_replace_replace = _title_replace_replace.replace(/\\_/g, '')) === null || _title_replace_replace_replace === void 0 ? void 0 : _title_replace_replace_replace.trim(),
                dataIndex: title + '_' + index,
                key: title + '_' + index
            };
        }
        keyMap.set(title, title);
        return {
            title: title,
            dataIndex: title,
            key: title
        };
    })) || [];
    var dataSource = (table === null || table === void 0 ? void 0 : (_table_children1 = table.children) === null || _table_children1 === void 0 ? void 0 : (_table_children_slice = _table_children1.slice(1)) === null || _table_children_slice === void 0 ? void 0 : _table_children_slice.map(function(row) {
        var _row_children;
        return (_row_children = row.children) === null || _row_children === void 0 ? void 0 : _row_children.reduce(function(acc, cell, index) {
            var _myRemark_stringify_replace_replace_replace, _myRemark_stringify_replace_replace, _myRemark_stringify_replace, _myRemark_stringify;
            // 如果数据列数超出表头列数，舍弃多余的数据
            if (index >= columns.length) {
                return acc;
            }
            acc[columns[index].dataIndex] = (_myRemark_stringify = myRemark.stringify({
                type: 'root',
                children: [
                    cell
                ]
            })) === null || _myRemark_stringify === void 0 ? void 0 : (_myRemark_stringify_replace = _myRemark_stringify.replace(/\n/g, '')) === null || _myRemark_stringify_replace === void 0 ? void 0 : (_myRemark_stringify_replace_replace = _myRemark_stringify_replace.replace(/\\(?=")/g, '')) === null || _myRemark_stringify_replace_replace === void 0 ? void 0 : (_myRemark_stringify_replace_replace_replace = _myRemark_stringify_replace_replace.replace(/\\_/g, '')) === null || _myRemark_stringify_replace_replace_replace === void 0 ? void 0 : _myRemark_stringify_replace_replace_replace.trim();
            return acc;
        }, {});
    })) || [];
    if ((_table_align = table.align) === null || _table_align === void 0 ? void 0 : _table_align.every(function(item) {
        return !item;
    })) {
        var aligns = getColumnAlignment(dataSource, columns);
        table.align = aligns;
    }
    var aligns1 = table.align;
    var isChart = (config === null || config === void 0 ? void 0 : config.chartType) || (config === null || config === void 0 ? void 0 : (_config_at1 = config.at) === null || _config_at1 === void 0 ? void 0 : (_config_at = _config_at1.call(config, 0)) === null || _config_at === void 0 ? void 0 : _config_at.chartType);
    /**
   * 如果是分栏，将表格转换为分栏节点
   */ // 计算合并单元格信息
    var mergeCells = config.mergeCells || [];
    // 创建合并单元格映射，用于快速查找
    var mergeMap = new Map();
    mergeCells === null || mergeCells === void 0 ? void 0 : mergeCells.forEach(function(param) {
        var row = param.row, col = param.col, rowSpan = param.rowSpan, rowspan = param.rowspan, colSpan = param.colSpan, colspan = param.colspan;
        var rawRowSpan = rowSpan || rowspan;
        var rawColSpan = colSpan || colspan;
        // 主单元格
        mergeMap.set("".concat(row, "-").concat(col), {
            rowSpan: rawRowSpan,
            colSpan: rawColSpan
        });
        // 被合并的单元格标记为隐藏
        for(var r = row; r < row + rawRowSpan; r++){
            for(var c = col; c < col + rawColSpan; c++){
                if (r !== row || c !== col) {
                    mergeMap.set("".concat(r, "-").concat(c), {
                        rowSpan: 1,
                        colSpan: 1,
                        hidden: true
                    });
                }
            }
        }
    });
    var children = table.children.map(function(r, l) {
        return {
            type: 'table-row',
            align: (aligns1 === null || aligns1 === void 0 ? void 0 : aligns1[l]) || undefined,
            children: r.children.map(function(c, i) {
                var _c_children;
                var mergeInfo = mergeMap.get("".concat(l, "-").concat(i));
                return _object_spread_props(_object_spread({
                    type: 'table-cell',
                    align: (aligns1 === null || aligns1 === void 0 ? void 0 : aligns1[i]) || undefined,
                    title: l === 0,
                    rows: l,
                    cols: i
                }, (mergeInfo === null || mergeInfo === void 0 ? void 0 : mergeInfo.rowSpan) && mergeInfo.rowSpan > 1 ? {
                    rowSpan: mergeInfo.rowSpan
                } : {}, (mergeInfo === null || mergeInfo === void 0 ? void 0 : mergeInfo.colSpan) && mergeInfo.colSpan > 1 ? {
                    colSpan: mergeInfo.colSpan
                } : {}, (mergeInfo === null || mergeInfo === void 0 ? void 0 : mergeInfo.hidden) ? {
                    hidden: true
                } : {}), {
                    children: ((_c_children = c.children) === null || _c_children === void 0 ? void 0 : _c_children.length) ? [
                        {
                            type: 'paragraph',
                            children: parseNodes(c.children, plugins, false, c)
                        }
                    ] : [
                        {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }
                    ]
                });
            })
        };
    });
    var otherProps = _object_spread_props(_object_spread({}, isChart ? {
        config: config
    } : config), {
        columns: columns,
        dataSource: dataSource.map(function(item) {
            item === null || item === void 0 ? true : delete item.chartType;
            return _object_spread({}, item);
        })
    });
    var node = {
        type: isChart ? 'chart' : 'table',
        children: children,
        otherProps: otherProps
    };
    return EditorUtils.wrapperCardNode(node);
};
/**
 * 处理标题节点
 * @param currentElement - 当前处理的标题元素，包含depth和children属性
 * @returns 返回格式化的标题节点对象
 */ var handleHeading = function(currentElement, plugins) {
    var _currentElement_children;
    return {
        type: 'head',
        level: currentElement.depth,
        children: ((_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length) ? parseNodes(currentElement.children, plugins, false, currentElement) : [
            {
                text: ''
            }
        ]
    };
};
export var decodeURIComponentUrl = function(url) {
    try {
        return decodeURIComponent(url);
    } catch (e) {
        console.error('Failed to decode URI component:', e);
        return url;
    }
};
/**
 * 处理HTML节点
 * @param currentElement - 当前处理的HTML元素
 * @param parent - 父级元素，用于判断上下文
 * @param htmlTag - HTML标签栈，用于跟踪嵌套的HTML标签
 * @returns 返回包含解析后元素和上下文属性的对象
 */ var handleHtml = function(currentElement, parent, htmlTag) {
    var _currentElement_value, _currentElement_value_trim, _currentElement_value1, _currentElement_value_trim1;
    var value = (currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value = currentElement.value) === null || _currentElement_value === void 0 ? void 0 : _currentElement_value.replace('<!--', '').replace('-->', '').trim()) || '{}';
    var contextProps = {};
    if (value && (currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value1 = currentElement.value) === null || _currentElement_value1 === void 0 ? void 0 : (_currentElement_value_trim = _currentElement_value1.trim()) === null || _currentElement_value_trim === void 0 ? void 0 : _currentElement_value_trim.endsWith('-->')) && (currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value_trim1 = currentElement.value.trim()) === null || _currentElement_value_trim1 === void 0 ? void 0 : _currentElement_value_trim1.startsWith('<!--'))) {
        try {
            contextProps = json5.parse(value);
        } catch (e) {
            try {
                contextProps = partialJsonParse(value);
            } catch (parseError) {
                console.warn('Failed to parse HTML comment as JSON or partial JSON:', {
                    value: value,
                    error: parseError
                });
            }
            console.warn('HTML comment parse fallback attempted:', e);
        }
    }
    var el;
    if (!parent || [
        'listItem',
        'blockquote'
    ].includes(parent.type)) {
        // 检查是否为 <think> 标签
        var thinkElement = findThinkElement(currentElement.value);
        if (thinkElement) {
            // 将 <think> 标签转换为 think 类型的代码块
            el = {
                type: 'code',
                language: 'think',
                value: thinkElement.content,
                children: [
                    {
                        text: thinkElement.content
                    }
                ]
            };
        } else {
            // 检查是否为 <answer> 标签
            var answerElement = findAnswerElement(currentElement.value);
            if (answerElement) {
                // 将 <answer> 标签的内容作为普通文本
                el = {
                    text: answerElement.content
                };
            } else {
                var mediaElement = findImageElement(currentElement.value);
                if (mediaElement) {
                    el = createMediaNodeFromElement(mediaElement);
                } else if (currentElement.value === '<br/>') {
                    el = {
                        type: 'paragraph',
                        children: [
                            {
                                text: ''
                            }
                        ]
                    };
                } else if (currentElement.value.match(/^<\/(img|video|iframe)>/)) {
                    // 如果是媒体标签的结束标签，跳过处理
                    el = null;
                } else {
                    // 检查是否为注释（注释需要特殊处理以提取配置）
                    var isComment = currentElement.value.trim().startsWith('<!--') && currentElement.value.trim().endsWith('-->');
                    // 检查是否为标准 HTML 元素或注释
                    if (isComment || isStandardHtmlElement(currentElement.value)) {
                        // 标准 HTML 元素或注释：按原逻辑处理
                        el = currentElement.value.match(/<\/?(table|div|ul|li|ol|p|strong)[^\n>]*?>/) ? htmlToFragmentList(currentElement.value, '') : {
                            type: 'code',
                            language: 'html',
                            render: true,
                            value: currentElement.value,
                            children: [
                                {
                                    text: currentElement.value
                                }
                            ]
                        };
                    } else {
                        // 非标准元素（如自定义标签）：当作普通文本处理
                        el = {
                            text: currentElement.value
                        };
                    }
                }
            }
        }
    } else {
        el = processInlineHtml(currentElement, htmlTag);
    }
    if (el && !Array.isArray(el)) {
        // 只有非文本节点才设置 isConfig 和 otherProps
        if (!('text' in el && Object.keys(el).length === 1)) {
            var _currentElement_value_trim2, _currentElement_value2;
            el.isConfig = currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value2 = currentElement.value) === null || _currentElement_value2 === void 0 ? void 0 : (_currentElement_value_trim2 = _currentElement_value2.trim()) === null || _currentElement_value_trim2 === void 0 ? void 0 : _currentElement_value_trim2.startsWith('<!--');
            el.otherProps = contextProps;
        }
    }
    return {
        el: el,
        contextProps: contextProps
    };
};
/**
 * 处理内联HTML元素
 * @param currentElement - 当前处理的HTML元素
 * @param htmlTag - HTML标签栈
 * @returns 返回处理后的元素对象，如果是标签则返回null
 */ var processInlineHtml = function(currentElement, htmlTag) {
    var breakMatch = currentElement.value.match(/<br\/?>/);
    if (breakMatch) {
        return {
            type: 'break',
            children: [
                {
                    text: '\n'
                }
            ]
        };
    }
    // 检查是否为 <answer> 标签（内联场景）
    var answerElement = findAnswerElement(currentElement.value);
    if (answerElement) {
        // 将 <answer> 标签的内容作为普通文本
        return {
            text: answerElement.content
        };
    }
    // 检查是否为非标准 HTML 元素，如果是则直接当作文本
    if (!isStandardHtmlElement(currentElement.value)) {
        return {
            text: currentElement.value
        };
    }
    var htmlMatch = currentElement.value.match(/<\/?(b|i|del|font|code|span|sup|sub|strong|a)[^\n>]*?>/);
    if (htmlMatch) {
        var _htmlMatch = _sliced_to_array(htmlMatch, 2), str = _htmlMatch[0], tag = _htmlMatch[1];
        if (str.startsWith('</') && htmlTag.length && htmlTag[htmlTag.length - 1].tag === tag) {
            htmlTag.pop();
        }
        if (!str.startsWith('</')) {
            processHtmlTag(str, tag, htmlTag);
        }
        return null;
    } else {
        var mediaElement = findImageElement(currentElement.value);
        if (mediaElement) {
            return createMediaNodeFromElement(mediaElement);
        } else {
            return {
                text: currentElement.value
            };
        }
    }
};
/**
 * 处理HTML标签并添加到标签栈中
 * @param str - HTML标签字符串
 * @param tag - 标签名称
 * @param htmlTag - HTML标签栈
 */ var processHtmlTag = function(str, tag, htmlTag) {
    if (tag === 'span') {
        try {
            var styles = str.match(/style="([^"\n]+)"/);
            if (styles) {
                var stylesMap = new Map(styles[1].split(';').map(function(item) {
                    return item.split(':').map(function(item) {
                        return item.trim();
                    });
                }));
                if (stylesMap.get('color')) {
                    htmlTag.push({
                        tag: tag,
                        color: stylesMap.get('color')
                    });
                }
            }
        } catch (e) {
            console.warn('Failed to parse span style attribute:', {
                str: str,
                error: e
            });
        }
    } else if (tag === 'a') {
        var url = str.match(/href="([\w:./_\-#\\]+)"/);
        if (url) {
            htmlTag.push({
                tag: tag,
                url: url[1]
            });
        }
    } else if (tag === 'font') {
        var color = str.match(/color="([^"\n]+)"/);
        if (!color) {
            color = str.match(/color=([^"\n]+)/);
        }
        if (color) {
            htmlTag.push({
                tag: tag,
                color: color[1].replaceAll('>', '')
            });
        }
    } else {
        htmlTag.push({
            tag: tag
        });
    }
};
/**
 * 处理图片节点
 * @param currentElement - 当前处理的图片元素，包含url和alt属性
 * @returns 返回格式化的图片节点对象
 */ var handleImage = function(currentElement) {
    return EditorUtils.createMediaNode(decodeURIComponent(currentElement === null || currentElement === void 0 ? void 0 : currentElement.url), 'image', {
        alt: currentElement.alt
    });
};
/**
 * 处理内联数学公式
 * @param currentElement - 当前处理的内联数学公式元素
 * @returns 返回格式化的内联KaTeX节点对象
 */ var handleInlineMath = function(currentElement) {
    var inlineMathValue = typeof (currentElement === null || currentElement === void 0 ? void 0 : currentElement.value) === 'string' ? currentElement.value : '';
    if (shouldTreatInlineMathAsText(inlineMathValue)) {
        return {
            type: 'paragraph',
            children: [
                {
                    text: "$".concat(inlineMathValue, "$")
                }
            ]
        };
    }
    return {
        type: 'inline-katex',
        children: [
            {
                text: inlineMathValue
            }
        ]
    };
};
/**
 * 处理数学公式块
 * @param currentElement - 当前处理的数学公式块元素
 * @returns 返回格式化的KaTeX块节点对象
 */ var handleMath = function(currentElement) {
    return {
        type: 'katex',
        language: 'latex',
        katex: true,
        value: currentElement.value,
        children: [
            {
                text: ''
            }
        ]
    };
};
/**
 * 处理列表节点
 * @param currentElement - 当前处理的列表元素，包含ordered、start等属性
 * @returns 返回格式化的列表节点对象
 */ var handleList = function(currentElement, plugins) {
    var _el_children;
    var el = {
        type: 'list',
        order: currentElement.ordered,
        start: currentElement.start,
        children: parseNodes(currentElement.children, plugins, false, currentElement)
    };
    el.task = (_el_children = el.children) === null || _el_children === void 0 ? void 0 : _el_children.some(function(s) {
        return typeof s.checked === 'boolean';
    });
    return el;
};
/**
 * 处理脚注引用
 * @param currentElement - 当前处理的脚注引用元素
 * @returns 返回格式化的脚注引用节点对象
 */ var handleFootnoteReference = function(currentElement) {
    var _currentElement_identifier;
    return {
        text: "".concat((_currentElement_identifier = currentElement.identifier) === null || _currentElement_identifier === void 0 ? void 0 : _currentElement_identifier.toUpperCase()),
        identifier: currentElement.identifier,
        type: 'footnoteReference'
    };
};
/**
 * 处理脚注定义
 * @param currentElement - 当前处理的脚注定义元素
 * @returns 返回格式化的脚注定义节点对象
 */ var handleFootnoteDefinition = function(currentElement, plugins) {
    var _parseNodes, _linkNode_children;
    var linkNode = (_parseNodes = parseNodes(currentElement.children, plugins, false, currentElement)) === null || _parseNodes === void 0 ? void 0 : _parseNodes.at(0);
    var cellNode = linkNode === null || linkNode === void 0 ? void 0 : (_linkNode_children = linkNode.children) === null || _linkNode_children === void 0 ? void 0 : _linkNode_children.at(0);
    return {
        value: cellNode === null || cellNode === void 0 ? void 0 : cellNode.text,
        url: cellNode === null || cellNode === void 0 ? void 0 : cellNode.url,
        type: 'footnoteDefinition',
        identifier: currentElement.identifier,
        children: [
            cellNode
        ]
    };
};
/**
 * 处理列表项节点
 * @param currentElement - 当前处理的列表项元素
 * @returns 返回格式化的列表项节点对象，包含复选框状态和提及信息
 */ var handleListItem = function(currentElement, plugins) {
    var _currentElement_children, _currentElement_children__children_, _currentElement_children__children, _currentElement_children_, _currentElement_children1, _currentElement_children__children1, _currentElement_children_1, _currentElement_children2, _children__children_;
    var children = ((_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length) ? parseNodes(currentElement.children, plugins, false, currentElement) : [
        {
            type: 'paragraph',
            children: [
                {
                    text: ''
                }
            ]
        }
    ];
    var mentions = undefined;
    if (((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : (_currentElement_children_ = _currentElement_children1[0]) === null || _currentElement_children_ === void 0 ? void 0 : (_currentElement_children__children = _currentElement_children_.children) === null || _currentElement_children__children === void 0 ? void 0 : (_currentElement_children__children_ = _currentElement_children__children[0]) === null || _currentElement_children__children_ === void 0 ? void 0 : _currentElement_children__children_.type) === 'link' && ((_currentElement_children2 = currentElement.children) === null || _currentElement_children2 === void 0 ? void 0 : (_currentElement_children_1 = _currentElement_children2[0]) === null || _currentElement_children_1 === void 0 ? void 0 : (_currentElement_children__children1 = _currentElement_children_1.children) === null || _currentElement_children__children1 === void 0 ? void 0 : _currentElement_children__children1.length) > 1) {
        var _children__children, _children_;
        var item = children === null || children === void 0 ? void 0 : (_children_ = children[0]) === null || _children_ === void 0 ? void 0 : (_children__children = _children_.children) === null || _children__children === void 0 ? void 0 : _children__children[0];
        var label = item === null || item === void 0 ? void 0 : item.text;
        if (label) {
            var _item_url, _children__children1, _children_1, _children_2;
            mentions = [
                {
                    avatar: item === null || item === void 0 ? void 0 : item.url,
                    name: label,
                    id: new URLSearchParams('?' + (item === null || item === void 0 ? void 0 : (_item_url = item.url) === null || _item_url === void 0 ? void 0 : _item_url.split('?')[1])).get('id') || undefined
                }
            ];
            children === null || children === void 0 ? true : (_children_1 = children[0]) === null || _children_1 === void 0 ? true : (_children__children1 = _children_1.children) === null || _children__children1 === void 0 ? true : delete _children__children1[0];
            if (children === null || children === void 0 ? void 0 : (_children_2 = children[0]) === null || _children_2 === void 0 ? void 0 : _children_2.children) {
                var _children__children2, _children_3;
                children[0].children = children === null || children === void 0 ? void 0 : (_children_3 = children[0]) === null || _children_3 === void 0 ? void 0 : (_children__children2 = _children_3.children) === null || _children__children2 === void 0 ? void 0 : _children__children2.filter(Boolean);
            }
        }
    }
    if (children[0].type === 'paragraph' && ((_children__children_ = children[0].children[0]) === null || _children__children_ === void 0 ? void 0 : _children__children_.text)) {
        var _children__children_1;
        var text = (_children__children_1 = children[0].children[0]) === null || _children__children_1 === void 0 ? void 0 : _children__children_1.text;
        var m = text.match(/^\[([x\s])]/);
        if (m) {
            children[0].children[0].text = text.replace(/^\[([x\s])]/, '');
            return {
                type: 'list-item',
                checked: m ? m[1] === 'x' : undefined,
                children: children,
                mentions: mentions
            };
        }
    }
    return {
        type: 'list-item',
        checked: currentElement.checked,
        children: children,
        mentions: mentions
    };
};
/**
 * 处理附件链接
 */ var handleAttachmentLink = function(currentElement) {
    var text = currentElement.children.map(function(n) {
        return n.value || '';
    }).join('');
    var attach = findAttachment(text);
    if (!attach) return null;
    var name = text.match(/>(.*)<\/a>/);
    return {
        type: 'attach',
        url: decodeURIComponentUrl(attach === null || attach === void 0 ? void 0 : attach.url),
        size: attach.size,
        children: [
            {
                type: 'card-before',
                children: [
                    {
                        text: ''
                    }
                ]
            },
            {
                type: 'card-after',
                children: [
                    {
                        text: ''
                    }
                ]
            }
        ],
        name: name ? name[1] : attach === null || attach === void 0 ? void 0 : attach.url
    };
};
/**
 * 处理链接卡片
 */ var handleLinkCard = function(currentElement, config) {
    var _currentElement_children;
    var link = currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.at(0);
    return _object_spread_props(_object_spread({}, config), {
        type: 'link-card',
        url: decodeURIComponentUrl(link === null || link === void 0 ? void 0 : link.url),
        children: [
            {
                type: 'card-before',
                children: [
                    {
                        text: ''
                    }
                ]
            },
            {
                type: 'card-after',
                children: [
                    {
                        text: ''
                    }
                ]
            }
        ],
        name: link.title
    });
};
/**
 * 处理段落中的子元素
 */ var processParagraphChildren = function(currentElement, plugins) {
    var elements = [];
    var textNodes = [];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = (currentElement.children || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var currentChild = _step.value;
            if (currentChild.type === 'image') {
                // 将累积的文本节点生成段落
                if (textNodes.length) {
                    elements.push({
                        type: 'paragraph',
                        children: parseNodes(textNodes, plugins, false, currentElement)
                    });
                    textNodes = [];
                }
                // 添加图片节点
                elements.push(EditorUtils.createMediaNode(decodeURIComponentUrl(currentChild === null || currentChild === void 0 ? void 0 : currentChild.url), 'image', {
                    alt: currentChild.alt
                }));
            } else if (currentChild.type === 'html') {
                // 跳过媒体标签的结束标签
                if (currentChild.value.match(/^<\/(img|video|iframe)>/)) {
                    continue;
                }
                var mediaElement = findImageElement(currentChild.value);
                if (mediaElement) {
                    var node = createMediaNodeFromElement(mediaElement);
                    if (node) {
                        elements.push(node);
                    }
                } else {
                    textNodes.push({
                        type: 'html',
                        value: currentChild.value
                    });
                }
            } else {
                textNodes.push(currentChild);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    // 处理剩余的文本节点
    if (textNodes.length) {
        elements.push({
            type: 'paragraph',
            children: parseNodes(textNodes, plugins, false, currentElement)
        });
    }
    return elements;
};
/**
 * 处理段落节点
 * @param currentElement - 当前处理的段落元素
 * @param config - 配置对象，包含样式和行为设置
 * @param plugins - 插件数组
 * @returns 返回格式化的段落节点对象或元素数组
 */ var handleParagraph = function(currentElement, config, plugins) {
    var _currentElement_children, _currentElement_children_at, _currentElement_children1;
    // 检查是否是附件链接
    if (((_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children[0].type) === 'html' && currentElement.children[0].value.startsWith('<a')) {
        var attachNode = handleAttachmentLink(currentElement);
        if (attachNode) return attachNode;
    }
    // 检查是否是链接卡片
    if ((currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : (_currentElement_children_at = _currentElement_children1.at(0)) === null || _currentElement_children_at === void 0 ? void 0 : _currentElement_children_at.type) === 'link' && config.type === 'card') {
        return handleLinkCard(currentElement, config);
    }
    // 处理混合内容段落
    return processParagraphChildren(currentElement, plugins);
};
/**
 * 处理内联代码节点
 * @param currentElement - 当前处理的内联代码元素
 * @returns 返回格式化的内联代码节点对象，支持占位符和初始值
 */ var handleInlineCode = function(currentElement) {
    var _currentElement_value, _currentElement_value1;
    var hasPlaceHolder = (_currentElement_value = currentElement.value) === null || _currentElement_value === void 0 ? void 0 : _currentElement_value.match(/\$\{(.*?)\}/);
    var values = hasPlaceHolder ? hasPlaceHolder[1].split(';').map(function(item) {
        var values = item === null || item === void 0 ? void 0 : item.split(':');
        return _define_property({}, (values === null || values === void 0 ? void 0 : values.at(0)) || '', values === null || values === void 0 ? void 0 : values.at(1));
    }).reduce(function(acc, item) {
        return _object_spread({}, acc, item);
    }, {}) : undefined;
    return {
        text: values ? (values === null || values === void 0 ? void 0 : values.initialValue) || ' ' : currentElement.value,
        tag: (_currentElement_value1 = currentElement.value) === null || _currentElement_value1 === void 0 ? void 0 : _currentElement_value1.startsWith('${'),
        placeholder: (values === null || values === void 0 ? void 0 : values.placeholder) || undefined,
        initialValue: (values === null || values === void 0 ? void 0 : values.initialValue) || undefined,
        code: true
    };
};
/**
 * 处理分割线节点
 * @returns 返回格式化的分割线节点对象
 */ var handleThematicBreak = function() {
    return {
        type: 'hr',
        children: [
            {
                text: ''
            }
        ]
    };
};
/**
 * 处理代码块节点
 * @param currentElement - 当前处理的代码块元素，包含语言和内容
 * @returns 返回格式化的代码块节点对象，根据语言类型进行特殊处理
 */ var handleCode = function(currentElement) {
    var _currentElement_value_trim;
    var baseCodeElement = {
        type: 'code',
        language: currentElement.lang === 'apaasify' ? 'apaasify' : currentElement.lang,
        render: currentElement.meta === 'render',
        value: currentElement.value,
        isConfig: currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value_trim = currentElement.value.trim()) === null || _currentElement_value_trim === void 0 ? void 0 : _currentElement_value_trim.startsWith('<!--'),
        children: [
            {
                text: currentElement.value
            }
        ]
    };
    var handler = LANGUAGE_HANDLERS[currentElement.lang];
    return handler ? handler(baseCodeElement, currentElement.value) : baseCodeElement;
};
/**
 * 处理YAML节点
 * @param currentElement - 当前处理的YAML元素
 * @returns 返回格式化的YAML代码块节点对象
 */ var handleYaml = function(currentElement) {
    return {
        type: 'code',
        language: 'yaml',
        value: currentElement.value,
        frontmatter: true,
        children: [
            {
                text: currentElement.value
            }
        ]
    };
};
/**
 * 处理引用块节点
 * @param currentElement - 当前处理的引用块元素
 * @returns 返回格式化的引用块节点对象
 */ var handleBlockquote = function(currentElement, plugins) {
    var _currentElement_children;
    return {
        type: 'blockquote',
        children: ((_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length) ? parseNodes(currentElement.children, plugins, false, currentElement) : [
            {
                type: 'paragraph',
                children: [
                    {
                        text: ''
                    }
                ]
            }
        ]
    };
};
/**
 * 处理定义节点
 * @param currentElement - 当前处理的定义元素，包含标签和URL
 * @returns 返回格式化的定义段落节点对象
 */ var handleDefinition = function(currentElement) {
    return {
        type: 'paragraph',
        children: [
            {
                text: "[".concat(currentElement.label, "]: ") + (currentElement.url ? "".concat(currentElement.url) : '')
            }
        ]
    };
};
/**
 * 处理文本和内联元素节点
 * @param currentElement - 当前处理的文本或内联元素
 * @param htmlTag - HTML标签栈，用于应用样式
 * @returns 返回格式化的文本或内联元素节点对象
 */ var handleTextAndInlineElements = function(currentElement, htmlTag, plugins) {
    if (currentElement.type === 'text' && htmlTag.length) {
        var el = {
            text: currentElement.value
        };
        if (currentElement.value) {
            applyHtmlTagsToElement(el, htmlTag);
        }
        return el;
    }
    if ([
        'strong',
        'link',
        'text',
        'emphasis',
        'delete',
        'inlineCode'
    ].includes(currentElement.type)) {
        var _currentElement_children;
        if (currentElement.type === 'text') {
            return {
                text: currentElement.value
            };
        }
        var leaf = {};
        applyInlineFormatting(leaf, currentElement);
        applyHtmlTagsToElement(leaf, htmlTag);
        if (currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.some(function(n) {
            return n.type === 'html';
        })) {
            var _parseNodes;
            return _object_spread_props(_object_spread({}, (_parseNodes = parseNodes(currentElement === null || currentElement === void 0 ? void 0 : currentElement.children, plugins, false, currentElement)) === null || _parseNodes === void 0 ? void 0 : _parseNodes.at(0)), {
                url: leaf.url
            });
        } else {
            var _currentElement_children1;
            return parseText(((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : _currentElement_children1.length) ? currentElement.children : [
                {
                    value: (leaf === null || leaf === void 0 ? void 0 : leaf.url) || ''
                }
            ], leaf);
        }
    }
    if (currentElement.type === 'break') {
        return {
            text: '\n'
        };
    }
    return {
        text: ''
    };
};
/**
 * 应用内联格式到叶子节点
 * @param leaf - 目标叶子节点对象
 * @param currentElement - 当前处理的元素，包含格式信息
 */ var applyInlineFormatting = function(leaf, currentElement) {
    if (currentElement.type === 'strong') leaf.bold = true;
    if (currentElement.type === 'emphasis') leaf.italic = true;
    if (currentElement.type === 'delete') leaf.strikethrough = true;
    if (currentElement.type === 'link') {
        try {
            leaf.url = currentElement === null || currentElement === void 0 ? void 0 : currentElement.url;
        } catch (error) {
            leaf.url = currentElement === null || currentElement === void 0 ? void 0 : currentElement.url;
        }
    }
};
/**
 * 应用HTML标签样式到元素
 * @param el - 目标元素对象
 * @param htmlTag - HTML标签数组，包含样式信息
 */ var applyHtmlTagsToElement = function(el, htmlTag) {
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = htmlTag[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var t = _step.value;
            if (t.tag === 'font') {
                el.color = t.color;
            }
            if (t.tag === 'sup') el.identifier = el.text;
            if (t.tag === 'sub') el.identifier = el.text;
            if (t.tag === 'code') el.code = true;
            if (t.tag === 'i') el.italic = true;
            if (t.tag === 'b' || t.tag === 'strong') el.bold = true;
            if (t.tag === 'del') el.strikethrough = true;
            if ((t.tag === 'span' || t.tag === 'font') && t.color) el.highColor = t.color;
            if (t.tag === 'a' && (t === null || t === void 0 ? void 0 : t.url)) {
                el.url = t === null || t === void 0 ? void 0 : t.url;
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
};
/**
 * 应用上下文属性和配置到元素
 * @param el - 目标元素或元素数组
 * @param contextProps - 上下文属性对象
 * @param config - 配置对象
 * @returns 返回应用了属性和配置的元素
 */ var applyContextPropsAndConfig = function(el, contextProps, config) {
    if (Array.isArray(el)) {
        return el.map(function(item) {
            if (Object.keys(contextProps || {}).length) {
                item.contextProps = contextProps;
            }
            if (Object.keys(config || {}).length && !item.otherProps) {
                item.otherProps = config;
            }
            return item;
        });
    } else {
        if (Object.keys(contextProps || {}).length) {
            el.contextProps = contextProps;
        }
        if (Object.keys(config || {}).length && !el.otherProps) {
            el.otherProps = config;
        }
        return el;
    }
};
/**
 * 根据行间距添加空行元素
 * @param els - 目标元素数组
 * @param preNode - 前一个节点
 * @param currentElement - 当前处理的元素
 * @param top - 是否为顶级解析
 */ var addEmptyLinesIfNeeded = function(els, preNode, currentElement, top) {
    if (preNode && top) {
        var _currentElement_position, _preNode_position;
        var distance = (((_currentElement_position = currentElement.position) === null || _currentElement_position === void 0 ? void 0 : _currentElement_position.start.line) || 0) - (((_preNode_position = preNode.position) === null || _preNode_position === void 0 ? void 0 : _preNode_position.end.line) || 0);
        if (distance >= EMPTY_LINE_DISTANCE_THRESHOLD) {
            var lines = Math.floor((distance - EMPTY_LINE_CALCULATION_OFFSET) / EMPTY_LINE_DIVISOR);
            Array.from(new Array(lines)).forEach(function() {
                els.push({
                    type: 'paragraph',
                    children: [
                        {
                            text: ''
                        }
                    ]
                });
            });
        }
    }
};
/**
 * 元素处理器映射表
 */ var elementHandlers = {
    heading: {
        handler: function(el, plugins) {
            return handleHeading(el, plugins);
        }
    },
    html: {
        handler: function() {
            return null;
        },
        needsHtmlResult: true
    },
    image: {
        handler: function(el) {
            return handleImage(el);
        }
    },
    inlineMath: {
        handler: function(el) {
            return handleInlineMath(el);
        }
    },
    math: {
        handler: function(el) {
            return handleMath(el);
        }
    },
    list: {
        handler: function(el, plugins) {
            return handleList(el, plugins);
        }
    },
    footnoteReference: {
        handler: function(el) {
            return handleFootnoteReference(el);
        }
    },
    footnoteDefinition: {
        handler: function(el, plugins) {
            return handleFootnoteDefinition(el, plugins);
        }
    },
    listItem: {
        handler: function(el, plugins) {
            return handleListItem(el, plugins);
        }
    },
    paragraph: {
        handler: function(el, plugins, config) {
            return handleParagraph(el, config, plugins);
        }
    },
    inlineCode: {
        handler: function(el) {
            return handleInlineCode(el);
        }
    },
    thematicBreak: {
        handler: function() {
            return handleThematicBreak();
        }
    },
    code: {
        handler: function(el) {
            return handleCode(el);
        }
    },
    yaml: {
        handler: function(el) {
            return handleYaml(el);
        }
    },
    blockquote: {
        handler: function(el, plugins) {
            return handleBlockquote(el, plugins);
        }
    },
    table: {
        handler: function(el, plugins, config, parent, htmlTag, preElement) {
            return parseTableOrChart(el, preElement, plugins);
        }
    },
    definition: {
        handler: function(el) {
            return handleDefinition(el);
        }
    }
};
/**
 * 处理单个元素
 */ var handleSingleElement = function(currentElement, config, plugins, parent, htmlTag, preElement) {
    var elementType = currentElement.type;
    var handlerInfo = elementHandlers[elementType];
    // 特殊处理 html 类型
    if (handlerInfo === null || handlerInfo === void 0 ? void 0 : handlerInfo.needsHtmlResult) {
        var htmlResult = handleHtml(currentElement, parent, htmlTag);
        return {
            el: htmlResult.el,
            contextProps: htmlResult.contextProps
        };
    }
    // 使用处理器映射表
    if (handlerInfo) {
        return {
            el: handlerInfo.handler(currentElement, plugins || [], config, parent, htmlTag, preElement)
        };
    }
    // 默认处理
    return {
        el: handleTextAndInlineElements(currentElement, htmlTag, plugins || [])
    };
};
/**
 * 解析Markdown节点块为Slate节点数组
 * 这是核心的解析函数，负责将各种类型的Markdown节点转换为对应的Slate编辑器节点
 *
 * @param nodes - 要解析的Markdown节点数组
 * @param top - 是否为顶级解析，影响空行处理逻辑
 * @param parent - 父级节点，用于上下文判断
 * @returns 返回解析后的Slate节点数组
 *
 * @example
 * ```typescript
 * const markdownNodes = [
 *   { type: 'heading', depth: 1, children: [...] },
 *   { type: 'paragraph', children: [...] }
 * ];
 * const slateNodes = parseNodes(markdownNodes, true);
 * ```
 */ /**
 * 解析 Markdown AST 节点为 Slate 节点
 * - 当有插件时，优先使用插件处理
 * - 插件未处理时，使用默认处理逻辑
 */ var parseNodes = function(nodes, plugins) {
    var _loop = function(i) {
        var currentElement = nodes[i];
        var el = null;
        var pluginHandled = false;
        var config = (preElement === null || preElement === void 0 ? void 0 : preElement.type) === 'code' && (preElement === null || preElement === void 0 ? void 0 : preElement.language) === 'html' && (preElement === null || preElement === void 0 ? void 0 : preElement.otherProps) ? preElement === null || preElement === void 0 ? void 0 : preElement.otherProps : {};
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            // 首先尝试使用插件处理
            for(var _iterator = plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var plugin = _step.value;
                var _plugin_parseMarkdown;
                var rule = (_plugin_parseMarkdown = plugin.parseMarkdown) === null || _plugin_parseMarkdown === void 0 ? void 0 : _plugin_parseMarkdown.find(function(r) {
                    return r.match(currentElement);
                });
                if (rule) {
                    var converted = rule.convert(currentElement);
                    // 检查转换结果是否为 NodeEntry<Text> 格式
                    if (Array.isArray(converted) && converted.length === 2) {
                        // NodeEntry<Text> 格式: [node, path]
                        el = converted[0];
                    } else {
                        // Elements 格式
                        el = converted;
                    }
                    pluginHandled = true;
                    break;
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        // 如果插件没有处理，使用默认处理逻辑
        if (!pluginHandled) {
            // 使用统一的处理函数
            var result = handleSingleElement(currentElement, config, plugins, parent, htmlTag, preElement);
            el = result.el;
            if (result.contextProps) {
                contextProps = _object_spread({}, contextProps, result.contextProps);
            }
        }
        addEmptyLinesIfNeeded(els, preNode, currentElement, top);
        if (el) {
            var _els;
            el = applyContextPropsAndConfig(el, contextProps, config);
            Array.isArray(el) ? (_els = els).push.apply(_els, _to_consumable_array(el)) : els.push(el);
        }
        preNode = currentElement;
        preElement = el;
    };
    var top = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false, parent = arguments.length > 3 ? arguments[3] : void 0;
    if (!(nodes === null || nodes === void 0 ? void 0 : nodes.length)) return [
        {
            type: 'paragraph',
            children: [
                {
                    text: ''
                }
            ]
        }
    ];
    var els = [];
    var preNode = null;
    var preElement = null;
    var htmlTag = [];
    var contextProps = {};
    for(var i = 0; i < nodes.length; i++)_loop(i);
    return els;
};
var tableRegex = /^\|.*\|\s*\n\|[-:| ]+\|/m;
/**
 * 标准 HTML 元素列表
 * 这些标签会被正常解析为 HTML，其他标签会被当作普通文本处理
 */ var STANDARD_HTML_ELEMENTS = new Set([
    // 文档结构
    'html',
    'head',
    'body',
    'title',
    'meta',
    'link',
    'style',
    'script',
    // 内容分区
    'header',
    'nav',
    'main',
    'section',
    'article',
    'aside',
    'footer',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    // 文本内容
    'div',
    'p',
    'hr',
    'pre',
    'blockquote',
    // 列表
    'ul',
    'ol',
    'li',
    'dl',
    'dt',
    'dd',
    // 表格
    'table',
    'thead',
    'tbody',
    'tfoot',
    'tr',
    'th',
    'td',
    'caption',
    'colgroup',
    'col',
    // 表单
    'form',
    'input',
    'textarea',
    'button',
    'select',
    'option',
    'label',
    'fieldset',
    'legend',
    // 内联文本语义
    'a',
    'em',
    'strong',
    'small',
    'mark',
    'del',
    'ins',
    'sub',
    'sup',
    'i',
    'b',
    'u',
    's',
    'code',
    'kbd',
    'samp',
    'var',
    'span',
    'br',
    'wbr',
    // 图片和多媒体
    'img',
    'video',
    'audio',
    'source',
    'track',
    'iframe',
    'embed',
    'object',
    'param',
    'picture',
    // 其他
    'canvas',
    'svg',
    'math',
    'details',
    'summary',
    'dialog',
    'menu',
    'menuitem',
    // 字体
    'font'
]);
/**
 * 检查 HTML 标签是否为标准元素
 * @param htmlString - HTML 字符串
 * @returns 是否为标准 HTML 元素
 */ function isStandardHtmlElement(htmlString) {
    // 提取标签名（支持开始标签和结束标签）
    var tagMatch = htmlString.match(/<\/?(\w+)/);
    if (!tagMatch) return false;
    var tagName = tagMatch[1].toLowerCase();
    return STANDARD_HTML_ELEMENTS.has(tagName);
}
/**
 * 预处理特殊标签（think/answer），将其转换为代码块格式
 * @param markdown - 原始 Markdown 字符串
 * @param tagName - 标签名称（think 或 answer）
 * @returns 处理后的 Markdown 字符串
 */ function preprocessSpecialTags(markdown, tagName) {
    var tagRegex = new RegExp("<".concat(tagName, ">([\\s\\S]*?)<\\/").concat(tagName, ">"), 'g');
    return markdown === null || markdown === void 0 ? void 0 : markdown.replace(tagRegex, function(match, content) {
        var trimmedContent = content.trim();
        // 如果内容中包含代码块标记（三个反引号），需要进行转义
        // 策略：使用特殊标记替换代码块，保持原始格式
        var processedContent = trimmedContent === null || trimmedContent === void 0 ? void 0 : trimmedContent.replace(/```(\w*)\n?([\s\S]*?)```/g, function(_, lang, code) {
            // 使用特殊标记包裹，保留语言和代码内容
            // 格式：【CODE_BLOCK:lang】code【/CODE_BLOCK】
            var marker = '\u200B'; // 零宽空格，用于标记
            return "".concat(marker, "【CODE_BLOCK:").concat(lang || '', "】\n").concat(code, "\n【/CODE_BLOCK】").concat(marker);
        });
        // 构建对应类型的代码块
        return "```".concat(tagName, "\n").concat(processedContent, "\n```");
    });
}
/**
 * 预处理 <think> 标签，将其转换为 ```think 代码块格式
 * @param markdown - 原始 Markdown 字符串
 * @returns 处理后的 Markdown 字符串
 */ function preprocessThinkTags(markdown) {
    return preprocessSpecialTags(markdown, 'think');
}
/**
 * 预处理所有非标准 HTML 标签，提取其内容（删除标签本身）
 * @param markdown - 原始 Markdown 字符串
 * @returns 处理后的 Markdown 字符串
 */ function preprocessNonStandardHtmlTags(markdown) {
    var result = markdown;
    var hasNonStandardTags = true;
    // 循环处理，直到没有非标准标签（处理嵌套情况）
    while(hasNonStandardTags){
        var before = result;
        // 匹配所有 HTML 标签对：<tagname>content</tagname>
        result = result.replace(/<(\w+)>([\s\S]*?)<\/\1>/g, function(match, tagName, content) {
            // 检查是否为标准 HTML 元素
            if (STANDARD_HTML_ELEMENTS.has(tagName.toLowerCase())) {
                // 标准元素保持不变
                return match;
            }
            // 非标准元素只保留内容（不 trim，保持原始格式）
            return content;
        });
        // 如果没有变化，说明处理完成
        hasNonStandardTags = before !== result;
    }
    return result;
}
function preprocessMarkdownTableNewlines(markdown) {
    // 检查是否包含表格
    if (!tableRegex.test(markdown)) return markdown; // 如果没有表格，直接返回原始字符串
    // 处理表格结尾的换行符：
    // 1. 如果只有一个换行符，改成两个
    // 2. 如果有两个以上换行符，改成两个
    // 3. 如果已经是两个换行符，保持不变
    var processedMarkdown = markdown.replace(/(\|[^|\n]*\|)\n(?!\n|\|)/g, '$1\n\n').replace(/(\|[^|\n]*\|)\n{3,}(?!\|)/g, '$1\n\n');
    // 如果包含表格，处理换行符
    return processedMarkdown === null || processedMarkdown === void 0 ? void 0 : processedMarkdown.split('\n\n').map(function(line) {
        if (line.includes('```')) return line; // 如果包含代码块，直接返回原始字符串
        // 检查是否包含表格
        if (!tableRegex.test(line)) return line; // 如果没有表格，直接返回原始字符串
        // 匹配所有表格的行（确保我们在表格行内匹配换行符）
        return line.replace(/\|([^|]+)\|/g, function(match) {
            var _match_replaceAll;
            if (((_match_replaceAll = match.replaceAll('\n', '')) === null || _match_replaceAll === void 0 ? void 0 : _match_replaceAll.length) < MIN_TABLE_CELL_LENGTH) return match;
            // 只替换每个表格单元格内的换行符
            return match.split('\n').join('<br>');
        });
    }).join('\n\n');
}
/**
 * 解析Markdown字符串并返回解析后的结构和链接信息。
 *
 * @param md - 要解析的Markdown字符串。
 * @param plugins - 可选的Markdown编辑器插件数组，用于扩展解析功能。
 * @returns 一个包含解析后的元素数组和链接信息的对象。
 *
 * @property schema - 解析后的元素数组。
 * @property links - 包含路径和目标链接的对象数组。
 */ export var parserMarkdownToSlateNode = function(md, plugins) {
    // 先预处理 <think> 标签，再预处理其他非标准 HTML 标签，最后处理表格换行
    var thinkProcessed = preprocessThinkTags(md || '');
    var nonStandardProcessed = preprocessNonStandardHtmlTags(thinkProcessed);
    var processedMarkdown = mdastParser.parse(preprocessMarkdownTableNewlines(nonStandardProcessed));
    var markdownRoot = processedMarkdown.children;
    var pluginList = plugins || [];
    var schema = parseNodes(markdownRoot, pluginList, true);
    return {
        schema: schema === null || schema === void 0 ? void 0 : schema.filter(function(item) {
            var _item_children;
            if (item.type === 'paragraph' && ((_item_children = item.children) === null || _item_children === void 0 ? void 0 : _item_children.length) === 1) {
                if (item.children[0].text === '\n') {
                    return false;
                }
                return true;
            }
            return true;
        }),
        links: []
    };
};
