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 _assert_this_initialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _call_super(_this, derived, args) {
    derived = _get_prototype_of(derived);
    return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
}
function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
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 _get_prototype_of(o) {
    _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _get_prototype_of(o);
}
function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            writable: true,
            configurable: true
        }
    });
    if (superClass) _set_prototype_of(subClass, superClass);
}
function _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
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 _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 _possible_constructor_return(self, call) {
    if (call && (_type_of(call) === "object" || typeof call === "function")) {
        return call;
    }
    return _assert_this_initialized(self);
}
function _set_prototype_of(o, p) {
    _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _set_prototype_of(o, p);
}
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 _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
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);
}
function _is_native_reflect_construct() {
    try {
        var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
    } catch (_) {}
    return (_is_native_reflect_construct = function() {
        return !!result;
    })();
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { merge } from "lodash-es";
import Mustache from "mustache";
import React, { Component, useEffect, useMemo, useRef, useState } from "react";
import partialParse from "../../MarkdownEditor/editor/parser/json-parse";
import { createSandbox, DEFAULT_SANDBOX_CONFIG } from "../../Utils/proxySandbox";
import { mdDataSchemaValidator } from "../validator";
import { TemplateEngine } from "./templateEngine";
export * from "./templateEngine";
/**
 * 创建沙箱实例
 */ var createSandboxInstance = function(sandboxConfig) {
    var _sandboxConfig_allowDOM, _sandboxConfig_strictMode;
    return createSandbox(_object_spread_props(_object_spread({}, DEFAULT_SANDBOX_CONFIG), {
        allowDOM: (_sandboxConfig_allowDOM = sandboxConfig.allowDOM) !== null && _sandboxConfig_allowDOM !== void 0 ? _sandboxConfig_allowDOM : true,
        allowedGlobals: sandboxConfig.allowedGlobals || DEFAULT_SANDBOX_CONFIG.allowedGlobals,
        forbiddenGlobals: sandboxConfig.forbiddenGlobals || DEFAULT_SANDBOX_CONFIG.forbiddenGlobals,
        strictMode: (_sandboxConfig_strictMode = sandboxConfig.strictMode) !== null && _sandboxConfig_strictMode !== void 0 ? _sandboxConfig_strictMode : true,
        timeout: sandboxConfig.timeout || 3000
    }));
};
/**
 * 创建沙箱上下文
 */ var createSandboxContext = function(shadowRoot) {
    return {
        shadowRoot: shadowRoot,
        safeWindow: {
            devicePixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio : 1,
            innerWidth: typeof window !== 'undefined' ? window.innerWidth : 1024,
            innerHeight: typeof window !== 'undefined' ? window.innerHeight : 768
        }
    };
};
/**
 * 执行不安全的脚本（沙箱禁用时）
 */ var executeUnsafeScript = function(script, shadowRoot) {
    console.warn('沙箱已禁用，使用不安全的脚本执行方式');
    var scriptFn = new Function('shadowRoot', 'window', script.textContent || '');
    try {
        scriptFn(shadowRoot, {
            devicePixelRatio: window.devicePixelRatio
        });
    } catch (evalError) {
        console.error('执行脚本错误:', evalError);
    }
};
/**
 * 执行外部脚本
 */ var executeExternalScript = function(script, shadowRoot) {
    console.warn('外部脚本暂时不通过沙箱执行:', script.src);
    try {
        shadowRoot === null || shadowRoot === void 0 ? void 0 : shadowRoot.appendChild(script);
    } catch (appendError) {
        console.error('Error appending external script:', appendError);
    }
};
/**
 * 在沙箱中执行脚本
 */ var executeSandboxedScript = function(script, shadowRoot, sandboxConfig) {
    return _async_to_generator(function() {
        var sandbox, result, evalError;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    sandbox = createSandboxInstance(sandboxConfig);
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        3,
                        4,
                        5
                    ]);
                    return [
                        4,
                        sandbox.execute(script.textContent || '', createSandboxContext(shadowRoot))
                    ];
                case 2:
                    result = _state.sent();
                    if (!result.success && result.error) {
                        console.error('沙箱脚本执行错误:', result.error);
                    }
                    return [
                        3,
                        5
                    ];
                case 3:
                    evalError = _state.sent();
                    console.error('沙箱执行失败:', evalError);
                    return [
                        3,
                        5
                    ];
                case 4:
                    sandbox.destroy();
                    return [
                        7
                    ];
                case 5:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 执行内联脚本
 */ var executeInlineScript = function(script, shadowRoot, sandboxConfig) {
    return _async_to_generator(function() {
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (!sandboxConfig.enabled) {
                        executeUnsafeScript(script, shadowRoot);
                        return [
                            2
                        ];
                    }
                    return [
                        4,
                        executeSandboxedScript(script, shadowRoot, sandboxConfig)
                    ];
                case 1:
                    _state.sent();
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 执行脚本（内联或外部）
 */ var executeScript = function(script, shadowRoot, sandboxConfig) {
    return _async_to_generator(function() {
        var scriptError;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    _state.trys.push([
                        0,
                        3,
                        ,
                        4
                    ]);
                    if (!(!script.src && script.textContent)) return [
                        3,
                        2
                    ];
                    return [
                        4,
                        executeInlineScript(script, shadowRoot, sandboxConfig)
                    ];
                case 1:
                    _state.sent();
                    return [
                        2
                    ];
                case 2:
                    if (script.src) {
                        executeExternalScript(script, shadowRoot);
                    }
                    return [
                        3,
                        4
                    ];
                case 3:
                    scriptError = _state.sent();
                    console.error('Script execution error:', scriptError);
                    return [
                        3,
                        4
                    ];
                case 4:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * ErrorBoundary 组件 - 错误边界组件
 *
 * 用于捕获SchemaRenderer渲染过程中的错误，提供错误处理和回退显示。
 *
 * @component
 * @description 错误边界组件，捕获渲染错误并提供回退显示
 */ var ErrorBoundary = /*#__PURE__*/ function(Component) {
    "use strict";
    _inherits(ErrorBoundary, Component);
    function ErrorBoundary(props) {
        _class_call_check(this, ErrorBoundary);
        var _this;
        _this = _call_super(this, ErrorBoundary, [
            props
        ]);
        _this.state = {
            hasError: false,
            error: null
        };
        return _this;
    }
    _create_class(ErrorBoundary, [
        {
            key: "componentDidCatch",
            value: function componentDidCatch(error, errorInfo) {
                console.error('SchemaRenderer error:', error, errorInfo);
            }
        },
        {
            key: "render",
            value: function render() {
                if (this.state.hasError) {
                    if (this.props.fallback) {
                        return this.props.fallback;
                    }
                    return /*#__PURE__*/ React.createElement("div", {
                        style: {
                            padding: '10px',
                            border: '1px solid #f5c2c7',
                            borderRadius: '4px',
                            background: '#f8d7da',
                            color: '#842029'
                        }
                    }, /*#__PURE__*/ React.createElement("p", null, "Something went wrong rendering this component."));
                }
                return this.props.children;
            }
        }
    ], [
        {
            key: "getDerivedStateFromError",
            value: function getDerivedStateFromError(error) {
                return {
                    hasError: true,
                    error: error
                };
            }
        }
    ]);
    return ErrorBoundary;
}(Component);
/**
 * SchemaRenderer 组件 - Schema渲染器组件
 *
 * 该组件根据JSON Schema和模板引擎渲染动态内容，支持模板语法、数据验证、错误处理等。
 * 提供安全的内容渲染、模板解析、错误边界等功能。
 *
 * @component
 * @description Schema渲染器组件，根据Schema和模板渲染动态内容
 * @param {SchemaRendererProps} props - 组件属性
 * @param {LowCodeSchema} props.schema - 渲染Schema定义
 * @param {Record<string, any>} props.values - 渲染数据值
 * @param {Object} [props.config] - 渲染配置
 * @param {string[]} [props.config.ALLOWED_TAGS] - 允许的HTML标签
 * @param {string[]} [props.config.ALLOWED_ATTR] - 允许的HTML属性
 * @param {React.ReactNode} [props.fallbackContent] - 回退内容
 * @param {boolean} [props.useDefaultValues=true] - 是否使用默认值
 * @param {boolean} [props.debug=true] - 是否启用调试模式
 *
 * @example
 * ```tsx
 * <SchemaRenderer
 *   schema={{
 *     component: {
 *       type: 'div',
 *       template: '<h1>{{title}}</h1><p>{{content}}</p>'
 *     }
 *   }}
 *   values={{
 *     title: '欢迎',
 *     content: '这是一个动态渲染的内容'
 *   }}
 *   config={{
 *     ALLOWED_TAGS: ['h1', 'p', 'div'],
 *     ALLOWED_ATTR: ['class', 'style']
 *   }}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的动态内容组件
 *
 * @remarks
 * - 根据Schema和模板引擎渲染内容
 * - 支持Mustache模板语法
 * - 提供数据验证功能
 * - 包含错误边界处理
 * - 支持安全的内容渲染
 * - 提供调试模式
 * - 支持默认值处理
 * - 响应式布局适配
 */ export var SchemaRenderer = function(param) {
    var schema = param.schema, values = param.values, config = param.config, fallbackContent = param.fallbackContent, _param_debug = param.debug, debug = _param_debug === void 0 ? true : _param_debug, _param_useDefaultValues = param.useDefaultValues, useDefaultValues = _param_useDefaultValues === void 0 ? true : _param_useDefaultValues, onRenderSuccess = param.onRenderSuccess, _param_sandboxConfig = param.sandboxConfig, sandboxConfig = _param_sandboxConfig === void 0 ? {
        enabled: true,
        allowDOM: true,
        timeout: 3000,
        strictMode: true
    } : _param_sandboxConfig;
    var _useState = _sliced_to_array(useState(null), 2), renderError = _useState[0], setRenderError = _useState[1];
    // 安全地获取 schema 属性
    var safeSchema = schema || {};
    var safeComponent = safeSchema.component || {};
    var initialValues = safeSchema.initialValues || {};
    // 验证 schema
    var validationResult = useMemo(function() {
        try {
            return mdDataSchemaValidator.validate(safeSchema);
        } catch (error) {
            console.error('Schema validation error:', error);
            return {
                valid: false,
                errors: [
                    {
                        message: 'Schema validation failed'
                    }
                ]
            };
        }
    }, [
        safeSchema
    ]);
    // 从 schema 中提取数据和模板
    var _safeComponent_properties = safeComponent.properties, properties = _safeComponent_properties === void 0 ? {} : _safeComponent_properties, _safeComponent_type = safeComponent.type, type = _safeComponent_type === void 0 ? 'html' : _safeComponent_type;
    var templateHtml = safeComponent.schema || '';
    // 准备模板数据
    var templateData = useMemo(function() {
        try {
            var defaultValues = useDefaultValues ? Object.entries(properties || {}).reduce(function(data, param) {
                var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
                if (value && 'default' in value) {
                    data[key] = value.default;
                }
                return data;
            }, {}) : {};
            // 先合并 values
            var mergedData = merge(defaultValues, initialValues || {}, values || {});
            // 类型转换：如果 properties 定义为 array/object，但 values 里是 string，则尝试转换
            Object.entries(properties || {}).forEach(function(param) {
                var _param = _sliced_to_array(param, 2), key = _param[0], property = _param[1];
                var val = mergedData[key];
                if (property.type === 'array' && typeof val === 'string') {
                    try {
                        // 尝试 JSON.parse，否则用逗号分割
                        mergedData[key] = partialParse(val);
                        if (!Array.isArray(mergedData[key])) {
                            mergedData[key] = val.split(',').map(function(s) {
                                return s.trim();
                            });
                        }
                    } catch (unused) {
                        mergedData[key] = val.split(',').map(function(s) {
                            return s.trim();
                        });
                    }
                }
                if (property.type === 'object' && typeof val === 'string') {
                    try {
                        try {
                            mergedData[key] = partialParse(val);
                        } catch (error) {
                            mergedData[key] = val;
                        }
                    } catch (unused) {
                        mergedData[key] = {};
                    }
                }
            });
            // 添加 fallback 值：如果数据在 properties 定义但是 mergedData 中没有
            var dataWithFallbacks = _object_spread({}, mergedData);
            Object.entries(properties || {}).forEach(function(param) {
                var _param = _sliced_to_array(param, 2), key = _param[0], property = _param[1];
                if (!(key in dataWithFallbacks) || dataWithFallbacks[key] === undefined || dataWithFallbacks[key] === null) {
                    switch(property.type){
                        case 'array':
                            dataWithFallbacks[key] = [];
                            break;
                        case 'string':
                            dataWithFallbacks[key] = '-';
                            break;
                        case 'number':
                            dataWithFallbacks[key] = '-';
                            break;
                        case 'object':
                            dataWithFallbacks[key] = {};
                            break;
                        default:
                            dataWithFallbacks[key] = '-';
                            break;
                    }
                }
            });
            return dataWithFallbacks;
        } catch (error) {
            console.error('Error preparing template data:', error);
            return values || {};
        }
    }, [
        properties,
        values,
        useDefaultValues,
        initialValues
    ]);
    // 使用模板引擎渲染
    var renderedHtml = useMemo(function() {
        try {
            if (type === 'html') {
                return TemplateEngine.render(templateHtml, templateData);
            }
            if (type === 'mustache') {
                return Mustache.render(templateHtml, templateData);
            }
            return templateHtml;
        } catch (error) {
            console.error('模板渲染错误:', error);
            setRenderError("Template rendering error: ".concat(_instanceof(error, Error) ? error.message : String(error)));
            return '';
        }
    }, [
        templateHtml,
        templateData,
        type,
        config
    ]);
    // 应用主题样式
    var containerStyle = useMemo(function() {
        try {
            var _ref, _ref1, _safeSpacing_width;
            var _safeTypography_fontSizes, _safeTypography_lineHeights;
            var safeTheme = safeSchema.theme || {};
            var safeTypography = safeTheme.typography || {};
            var safeSpacing = safeTheme.spacing || {};
            return {
                fontFamily: safeTypography.fontFamily,
                fontSize: "".concat((_ref = (_safeTypography_fontSizes = safeTypography.fontSizes) === null || _safeTypography_fontSizes === void 0 ? void 0 : _safeTypography_fontSizes[2]) !== null && _ref !== void 0 ? _ref : '14', "px"),
                lineHeight: (_ref1 = (_safeTypography_lineHeights = safeTypography.lineHeights) === null || _safeTypography_lineHeights === void 0 ? void 0 : _safeTypography_lineHeights.normal) !== null && _ref1 !== void 0 ? _ref1 : 1.6,
                width: (_safeSpacing_width = safeSpacing.width) !== null && _safeSpacing_width !== void 0 ? _safeSpacing_width : 'max-content',
                margin: '1em'
            };
        } catch (error) {
            console.error('Error applying theme styles:', error);
            return {
                fontSize: '13px',
                lineHeight: 1.6,
                width: 'max-content'
            };
        }
    }, [
        safeSchema.theme
    ]);
    var containerRef = useRef(null);
    useEffect(function() {
        if (!containerRef.current || !renderedHtml) return;
        try {
            // 获取或创建Shadow DOM
            var shadowRoot = containerRef.current.shadowRoot;
            if (!shadowRoot) {
                try {
                    shadowRoot = containerRef.current.attachShadow({
                        mode: 'open'
                    });
                } catch (error) {
                    console.error('Failed to create shadow root:', error);
                    // Fallback to direct innerHTML if shadow DOM is not supported
                    containerRef.current.innerHTML = renderedHtml;
                    return;
                }
            }
            // 创建一个临时容器来解析HTML
            var tempContainer = document.createElement('div');
            tempContainer.innerHTML = renderedHtml;
            // 清空shadowRoot内容
            shadowRoot.innerHTML = '';
            // 添加样式
            try {
                var _ref, _ref1;
                var _safeTypography_fontSizes, _safeTypography_lineHeights;
                var style = document.createElement('style');
                var safeTheme = safeSchema.theme || {};
                var safeTypography = safeTheme.typography || {};
                style.innerHTML = "\n:host {\n  display: block;\n  font-family: ".concat(safeTypography.fontFamily || 'inherit', ";\n  font-size: ").concat((_ref = (_safeTypography_fontSizes = safeTypography.fontSizes) === null || _safeTypography_fontSizes === void 0 ? void 0 : _safeTypography_fontSizes[2]) !== null && _ref !== void 0 ? _ref : '14', "px;\n  line-height: ").concat((_ref1 = (_safeTypography_lineHeights = safeTypography.lineHeights) === null || _safeTypography_lineHeights === void 0 ? void 0 : _safeTypography_lineHeights.normal) !== null && _ref1 !== void 0 ? _ref1 : 1.6, ";\n}\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, u, i, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed, \nfigure, figcaption, footer, header, hgroup, \nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n	margin: 0;\n	padding: 0;\n	border: 0;\n	font-size: 100%;\n	font: inherit;\n	vertical-align: baseline;\n}\n/* HTML5 display-role reset for older browsers */\narticle, aside, details, figcaption, figure, \nfooter, header, hgroup, menu, nav, section {\n	display: block;\n}\nbody {\n	line-height: 1;\n}\nol, ul {\n	list-style: none;\n}\nblockquote, q {\n	quotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n	content: '';\n	content: none;\n}\ntable {\n	border-collapse: collapse;\n	border-spacing: 0;\n}\ndiv {\n  white-space: normal;\n  overflow-wrap: normal;\n}\n\na {\n  text-decoration: none;\n  white-space: normal;\n  overflow-wrap: normal;\n}\n\na:hover {\n  text-decoration: underline;\n}\n\na:visited {\n  color: inherit;\n}\n\na:active {\n  color: inherit;\n}\n\n        ");
                shadowRoot.appendChild(style);
            } catch (styleError) {
                console.error('Error applying styles:', styleError);
            }
            try {
                // 提取所有的script标签
                var scripts = [];
                var scriptElements = tempContainer.querySelectorAll('script');
                scriptElements.forEach(function(oldScript) {
                    try {
                        var // 移除原始script标签
                        _oldScript_parentNode;
                        (_oldScript_parentNode = oldScript.parentNode) === null || _oldScript_parentNode === void 0 ? void 0 : _oldScript_parentNode.removeChild(oldScript);
                        // 创建新的script标签
                        var newScript = document.createElement('script');
                        // 复制属性
                        Array.from(oldScript.attributes).forEach(function(attr) {
                            newScript.setAttribute(attr.name, attr.value);
                        });
                        // 复制内容
                        newScript.textContent = oldScript.textContent;
                        scripts.push(newScript);
                    } catch (scriptError) {
                        console.error('Error processing script:', scriptError);
                    }
                });
                // 将其他内容添加到Shadow DOM
                Array.from(tempContainer.childNodes).forEach(function(node) {
                    try {
                        shadowRoot === null || shadowRoot === void 0 ? void 0 : shadowRoot.appendChild(node.cloneNode(true));
                    } catch (nodeError) {
                        console.error('Error appending node:', nodeError);
                    }
                });
                // 添加并执行脚本
                scripts.forEach(function(script) {
                    return _async_to_generator(function() {
                        return _ts_generator(this, function(_state) {
                            switch(_state.label){
                                case 0:
                                    return [
                                        4,
                                        executeScript(script, shadowRoot, sandboxConfig)
                                    ];
                                case 1:
                                    _state.sent();
                                    return [
                                        2
                                    ];
                            }
                        });
                    })();
                });
            } catch (contentError) {
                console.error('Error processing content:', contentError);
                // Fallback - at least show the HTML content
                try {
                    shadowRoot.innerHTML = renderedHtml;
                } catch (fallbackError) {
                    console.error('Even fallback rendering failed:', fallbackError);
                }
            }
            onRenderSuccess === null || onRenderSuccess === void 0 ? void 0 : onRenderSuccess(renderedHtml);
        } catch (error) {
            console.error('Critical rendering error:', error);
            setRenderError("Critical rendering error: ".concat(_instanceof(error, Error) ? error.message : String(error)));
        }
    }, [
        renderedHtml,
        safeSchema.theme
    ]);
    // 如果渲染过程中出现错误，显示错误信息
    if (renderError && debug) {
        return fallbackContent || /*#__PURE__*/ React.createElement("div", {
            style: {
                padding: '16px',
                border: '1px solid #f5c2c7',
                borderRadius: '8px',
                background: '#f8d7da',
                color: '#842029',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                margin: '10px 0'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                alignItems: 'center',
                marginBottom: '8px'
            }
        }, /*#__PURE__*/ React.createElement("svg", {
            width: "20",
            height: "20",
            viewBox: "0 0 24 24",
            fill: "none",
            xmlns: "http://www.w3.org/2000/svg",
            style: {
                marginRight: '8px'
            }
        }, /*#__PURE__*/ React.createElement("path", {
            d: "M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",
            stroke: "#842029",
            strokeWidth: "2"
        }), /*#__PURE__*/ React.createElement("path", {
            d: "M12 8V12",
            stroke: "#842029",
            strokeWidth: "2",
            strokeLinecap: "round"
        }), /*#__PURE__*/ React.createElement("circle", {
            cx: "12",
            cy: "16",
            r: "1",
            fill: "#842029"
        })), /*#__PURE__*/ React.createElement("h3", {
            style: {
                margin: 0,
                fontSize: '16px',
                fontWeight: 600
            }
        }, "渲染错误")), /*#__PURE__*/ React.createElement("pre", {
            style: {
                whiteSpace: 'pre-wrap',
                background: 'rgba(255,255,255,0.5)',
                padding: '8px',
                borderRadius: '4px',
                fontSize: '13px',
                margin: 0
            }
        }, renderError));
    }
    // Schema 验证失败，显示错误信息
    if (!(validationResult === null || validationResult === void 0 ? void 0 : validationResult.valid) && debug) {
        console.error('Schema validation failed:', validationResult.errors);
        return fallbackContent || /*#__PURE__*/ React.createElement("div", {
            style: {
                padding: '16px',
                border: '1px solid #f5c2c7',
                borderRadius: '8px',
                background: '#f8d7da',
                color: '#842029',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                margin: '10px 0'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                alignItems: 'center',
                marginBottom: '12px'
            }
        }, /*#__PURE__*/ React.createElement("svg", {
            width: "20",
            height: "20",
            viewBox: "0 0 24 24",
            fill: "none",
            xmlns: "http://www.w3.org/2000/svg",
            style: {
                marginRight: '8px'
            }
        }, /*#__PURE__*/ React.createElement("path", {
            d: "M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",
            stroke: "#842029",
            strokeWidth: "2"
        }), /*#__PURE__*/ React.createElement("path", {
            d: "M12 8V12",
            stroke: "#842029",
            strokeWidth: "2",
            strokeLinecap: "round"
        }), /*#__PURE__*/ React.createElement("circle", {
            cx: "12",
            cy: "16",
            r: "1",
            fill: "#842029"
        })), /*#__PURE__*/ React.createElement("h3", {
            style: {
                margin: 0,
                fontSize: '16px',
                fontWeight: 600
            }
        }, "Schema 验证失败")), /*#__PURE__*/ React.createElement("div", {
            style: {
                background: 'rgba(255,255,255,0.5)',
                padding: '12px',
                borderRadius: '6px',
                fontSize: '13px'
            }
        }, Array.isArray(validationResult.errors) ? /*#__PURE__*/ React.createElement("ul", {
            style: {
                margin: '0',
                paddingLeft: '20px',
                listStyleType: 'circle'
            }
        }, validationResult.errors.map(function(error, index) {
            return /*#__PURE__*/ React.createElement("li", {
                key: index,
                style: {
                    marginBottom: '8px'
                }
            }, /*#__PURE__*/ React.createElement("div", {
                style: {
                    fontWeight: 500
                }
            }, error.property || error.path ? /*#__PURE__*/ React.createElement("span", {
                style: {
                    color: '#d63939'
                }
            }, (error.property || error.path).toString().replace('instance.', ''), ":") : null, /*#__PURE__*/ React.createElement("span", {
                style: {
                    marginLeft: error.property || error.path ? '4px' : '0'
                }
            }, error.message)), error.schema ? /*#__PURE__*/ React.createElement("div", {
                style: {
                    fontSize: '13px',
                    color: '#5c636a',
                    marginTop: '4px',
                    paddingLeft: '12px'
                }
            }, "预期: ", JSON.stringify(error.schema)) : null);
        })) : /*#__PURE__*/ React.createElement("pre", {
            style: {
                whiteSpace: 'pre-wrap',
                margin: 0
            }
        }, JSON.stringify(validationResult.errors, null, 2))));
    }
    return /*#__PURE__*/ React.createElement(ErrorBoundary, {
        fallback: fallbackContent
    }, /*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        className: "schemaRenderer",
        "data-testid": "schema-renderer",
        style: containerStyle
    }));
};
