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 _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 _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 _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
        };
    }
}
/**
 * 安全上下文管理器
 *
 * 提供更细粒度的安全控制，管理沙箱内的执行上下文，
 * 包括变量作用域、API 权限、资源限制等。
 *
 * @author md-editor
 * @version 1.0.0
 */ import { ProxySandbox } from "./ProxySandbox";
/**
 * 安全上下文管理器类
 */ export var SecurityContextManager = /*#__PURE__*/ function() {
    "use strict";
    function SecurityContextManager() {
        var config = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
        _class_call_check(this, SecurityContextManager);
        _define_property(this, "contexts", new Map());
        _define_property(this, "config", void 0);
        _define_property(this, "globalMonitors", new Map());
        this.config = this.mergeDefaultConfig(config);
        this.initializeGlobalMonitors();
    }
    _create_class(SecurityContextManager, [
        {
            key: "mergeDefaultConfig",
            value: /**
   * 合并默认配置
   */ function mergeDefaultConfig(config) {
                var _config_allowConsole, _config_allowTimers, _config_strictMode, _config_allowDOM, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
                var _config_permissions, _config_permissions1, _config_permissions2, _config_permissions3, _config_permissions4, _config_limits, _config_limits1, _config_limits2, _config_limits3, _config_monitoring, _config_monitoring1, _config_monitoring2;
                return {
                    // 继承沙箱配置
                    allowedGlobals: config.allowedGlobals || [],
                    forbiddenGlobals: config.forbiddenGlobals || [],
                    allowConsole: (_config_allowConsole = config.allowConsole) !== null && _config_allowConsole !== void 0 ? _config_allowConsole : true,
                    allowTimers: (_config_allowTimers = config.allowTimers) !== null && _config_allowTimers !== void 0 ? _config_allowTimers : true,
                    timeout: config.timeout || 5000,
                    strictMode: (_config_strictMode = config.strictMode) !== null && _config_strictMode !== void 0 ? _config_strictMode : true,
                    customGlobals: config.customGlobals || {},
                    allowDOM: (_config_allowDOM = config.allowDOM) !== null && _config_allowDOM !== void 0 ? _config_allowDOM : false,
                    maxMemoryUsage: config.maxMemoryUsage || 10 * 1024 * 1024,
                    // 权限配置
                    permissions: {
                        network: (_ref = (_config_permissions = config.permissions) === null || _config_permissions === void 0 ? void 0 : _config_permissions.network) !== null && _ref !== void 0 ? _ref : false,
                        fileSystem: (_ref1 = (_config_permissions1 = config.permissions) === null || _config_permissions1 === void 0 ? void 0 : _config_permissions1.fileSystem) !== null && _ref1 !== void 0 ? _ref1 : false,
                        media: (_ref2 = (_config_permissions2 = config.permissions) === null || _config_permissions2 === void 0 ? void 0 : _config_permissions2.media) !== null && _ref2 !== void 0 ? _ref2 : false,
                        geolocation: (_ref3 = (_config_permissions3 = config.permissions) === null || _config_permissions3 === void 0 ? void 0 : _config_permissions3.geolocation) !== null && _ref3 !== void 0 ? _ref3 : false,
                        notifications: (_ref4 = (_config_permissions4 = config.permissions) === null || _config_permissions4 === void 0 ? void 0 : _config_permissions4.notifications) !== null && _ref4 !== void 0 ? _ref4 : false
                    },
                    // 资源限制
                    limits: {
                        maxExecutionTime: ((_config_limits = config.limits) === null || _config_limits === void 0 ? void 0 : _config_limits.maxExecutionTime) || 5000,
                        maxMemoryUsage: ((_config_limits1 = config.limits) === null || _config_limits1 === void 0 ? void 0 : _config_limits1.maxMemoryUsage) || 10 * 1024 * 1024,
                        maxCallStackDepth: ((_config_limits2 = config.limits) === null || _config_limits2 === void 0 ? void 0 : _config_limits2.maxCallStackDepth) || 100,
                        maxLoopIterations: ((_config_limits3 = config.limits) === null || _config_limits3 === void 0 ? void 0 : _config_limits3.maxLoopIterations) || 10000
                    },
                    // 监控配置
                    monitoring: {
                        enablePerformanceMonitoring: (_ref5 = (_config_monitoring = config.monitoring) === null || _config_monitoring === void 0 ? void 0 : _config_monitoring.enablePerformanceMonitoring) !== null && _ref5 !== void 0 ? _ref5 : true,
                        enableErrorTracking: (_ref6 = (_config_monitoring1 = config.monitoring) === null || _config_monitoring1 === void 0 ? void 0 : _config_monitoring1.enableErrorTracking) !== null && _ref6 !== void 0 ? _ref6 : true,
                        enableResourceMonitoring: (_ref7 = (_config_monitoring2 = config.monitoring) === null || _config_monitoring2 === void 0 ? void 0 : _config_monitoring2.enableResourceMonitoring) !== null && _ref7 !== void 0 ? _ref7 : true
                    }
                };
            }
        },
        {
            key: "initializeGlobalMonitors",
            value: /**
   * 初始化全局监控器
   */ function initializeGlobalMonitors() {
                if (this.config.monitoring.enablePerformanceMonitoring) {
                    this.globalMonitors.set('performance', this.createPerformanceMonitor());
                }
                if (this.config.monitoring.enableErrorTracking) {
                    this.globalMonitors.set('errorTracker', this.createErrorTracker());
                }
                if (this.config.monitoring.enableResourceMonitoring) {
                    this.globalMonitors.set('resourceMonitor', this.createResourceMonitor());
                }
            }
        },
        {
            key: "createPerformanceMonitor",
            value: /**
   * 创建性能监控器
   */ function createPerformanceMonitor() {
                return {
                    mark: function mark(name) {
                        if (typeof performance !== 'undefined' && performance.mark) {
                            performance.mark("sandbox-".concat(name));
                        }
                    },
                    measure: function measure(name, startMark, endMark) {
                        if (typeof performance !== 'undefined' && performance.measure) {
                            try {
                                performance.measure(name, "sandbox-".concat(startMark), "sandbox-".concat(endMark));
                            } catch (error) {
                                console.warn('Performance measurement failed:', error);
                            }
                        }
                    }
                };
            }
        },
        {
            key: "createErrorTracker",
            value: /**
   * 创建错误追踪器
   */ function createErrorTracker() {
                return {
                    captureError: function captureError(error, context) {
                        console.error("[Sandbox Error] ".concat(context, ":"), error);
                    // 这里可以集成第三方错误追踪服务
                    },
                    captureWarning: function captureWarning(message, context) {
                        console.warn("[Sandbox Warning] ".concat(context, ": ").concat(message));
                    }
                };
            }
        },
        {
            key: "createResourceMonitor",
            value: /**
   * 创建资源监控器
   */ function createResourceMonitor() {
                return {
                    checkMemoryUsage: function checkMemoryUsage() {
                        if (typeof performance !== 'undefined' && performance.memory) {
                            return performance.memory.usedJSHeapSize;
                        }
                        return 0;
                    },
                    checkCallStackDepth: function checkCallStackDepth(stack) {
                        if (stack) {
                            return stack.split('\n').length;
                        }
                        try {
                            throw new Error();
                        } catch (e) {
                            var _e_stack;
                            return ((_e_stack = e.stack) === null || _e_stack === void 0 ? void 0 : _e_stack.split('\n').length) || 0;
                        }
                    }
                };
            }
        },
        {
            /**
   * 创建新的执行上下文
   */ key: "createContext",
            value: function createContext(contextId) {
                var id = contextId || this.generateContextId();
                var context = {
                    id: id,
                    createdAt: Date.now(),
                    scope: {},
                    permissions: {
                        network: this.config.permissions.network,
                        fileSystem: this.config.permissions.fileSystem,
                        media: this.config.permissions.media,
                        geolocation: this.config.permissions.geolocation,
                        notifications: this.config.permissions.notifications
                    },
                    resourceUsage: {
                        memoryUsage: 0,
                        executionTime: 0,
                        callStackDepth: 0,
                        loopIterations: 0
                    }
                };
                this.contexts.set(id, context);
                return id;
            }
        },
        {
            key: "generateContextId",
            value: /**
   * 生成上下文 ID
   */ function generateContextId() {
                return "ctx_".concat(Date.now(), "_").concat(Math.random().toString(36).substr(2, 9));
            }
        },
        {
            /**
   * 获取执行上下文
   */ key: "getContext",
            value: function getContext(contextId) {
                return this.contexts.get(contextId);
            }
        },
        {
            /**
   * 删除执行上下文
   */ key: "deleteContext",
            value: function deleteContext(contextId) {
                return this.contexts.delete(contextId);
            }
        },
        {
            key: "executeInContext",
            value: /**
   * 在指定上下文中执行代码
   */ function executeInContext(_0, _1) {
                return _async_to_generator(function(contextId, code) {
                    var additionalScope, context, mergedScope, sandboxConfig, wrappedCode, sandbox, result;
                    var _arguments = arguments;
                    return _ts_generator(this, function(_state) {
                        switch(_state.label){
                            case 0:
                                additionalScope = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : {};
                                context = this.getContext(contextId);
                                if (!context) {
                                    throw new Error("Context ".concat(contextId, " not found"));
                                }
                                // 合并作用域
                                mergedScope = _object_spread({}, context.scope, additionalScope);
                                // 创建沙箱配置
                                sandboxConfig = {
                                    allowedGlobals: this.config.allowedGlobals,
                                    forbiddenGlobals: this.config.forbiddenGlobals,
                                    allowConsole: this.config.allowConsole,
                                    allowTimers: this.config.allowTimers,
                                    timeout: this.config.limits.maxExecutionTime,
                                    strictMode: this.config.strictMode,
                                    customGlobals: _object_spread(_object_spread_props(_object_spread({}, this.config.customGlobals, mergedScope), {
                                        // 添加上下文相关的全局变量
                                        __context: {
                                            id: contextId,
                                            permissions: context.permissions
                                        }
                                    }), this.config.monitoring.enablePerformanceMonitoring && {
                                        __performance: this.globalMonitors.get('performance')
                                    }),
                                    allowDOM: this.config.allowDOM,
                                    maxMemoryUsage: this.config.limits.maxMemoryUsage
                                };
                                // 包装代码以添加资源监控
                                wrappedCode = this.wrapCodeWithMonitoring(code);
                                // 创建沙箱并执行
                                sandbox = new ProxySandbox(sandboxConfig);
                                _state.label = 1;
                            case 1:
                                _state.trys.push([
                                    1,
                                    ,
                                    3,
                                    4
                                ]);
                                return [
                                    4,
                                    sandbox.execute(wrappedCode)
                                ];
                            case 2:
                                result = _state.sent();
                                // 更新上下文的资源使用情况
                                this.updateContextResourceUsage(context, result);
                                return [
                                    2,
                                    result
                                ];
                            case 3:
                                sandbox.destroy();
                                return [
                                    7
                                ];
                            case 4:
                                return [
                                    2
                                ];
                        }
                    });
                }).apply(this, arguments);
            }
        },
        {
            key: "wrapCodeWithMonitoring",
            value: /**
   * 包装代码以添加监控
   */ function wrapCodeWithMonitoring(code) {
                if (!this.config.monitoring.enableResourceMonitoring) {
                    return code;
                }
                // 对于简单的 return 语句，直接执行不包装
                // 这是一个简化的处理，对于复杂的监控需求，可以在未来版本中改进
                return code;
            }
        },
        {
            key: "updateContextResourceUsage",
            value: /**
   * 更新上下文的资源使用情况
   */ function updateContextResourceUsage(context, result) {
                context.resourceUsage.executionTime = result.executionTime;
                context.resourceUsage.memoryUsage = result.memoryUsage || 0;
                // 检查资源限制
                this.checkResourceLimits(context);
            }
        },
        {
            key: "checkResourceLimits",
            value: /**
   * 检查资源限制
   */ function checkResourceLimits(context) {
                var resourceUsage = context.resourceUsage;
                var limits = this.config.limits;
                if (resourceUsage.executionTime > limits.maxExecutionTime) {
                    throw new Error("Execution time limit exceeded: ".concat(resourceUsage.executionTime, "ms > ").concat(limits.maxExecutionTime, "ms"));
                }
                if (resourceUsage.memoryUsage > limits.maxMemoryUsage) {
                    throw new Error("Memory usage limit exceeded: ".concat(resourceUsage.memoryUsage, " > ").concat(limits.maxMemoryUsage));
                }
                if (resourceUsage.callStackDepth > limits.maxCallStackDepth) {
                    throw new Error("Call stack depth limit exceeded: ".concat(resourceUsage.callStackDepth, " > ").concat(limits.maxCallStackDepth));
                }
            }
        },
        {
            /**
   * 设置上下文变量
   */ key: "setContextVariable",
            value: function setContextVariable(contextId, name, value) {
                var context = this.getContext(contextId);
                if (!context) {
                    return false;
                }
                context.scope[name] = value;
                return true;
            }
        },
        {
            /**
   * 获取上下文变量
   */ key: "getContextVariable",
            value: function getContextVariable(contextId, name) {
                var context = this.getContext(contextId);
                return context === null || context === void 0 ? void 0 : context.scope[name];
            }
        },
        {
            /**
   * 清理所有上下文
   */ key: "clearAllContexts",
            value: function clearAllContexts() {
                this.contexts.clear();
            }
        },
        {
            /**
   * 获取所有上下文的统计信息
   */ key: "getStatistics",
            value: function getStatistics() {
                var contexts = Array.from(this.contexts.values());
                return {
                    totalContexts: contexts.length,
                    totalMemoryUsage: contexts.reduce(function(sum, ctx) {
                        return sum + ctx.resourceUsage.memoryUsage;
                    }, 0),
                    totalExecutionTime: contexts.reduce(function(sum, ctx) {
                        return sum + ctx.resourceUsage.executionTime;
                    }, 0),
                    averageExecutionTime: contexts.length > 0 ? contexts.reduce(function(sum, ctx) {
                        return sum + ctx.resourceUsage.executionTime;
                    }, 0) / contexts.length : 0,
                    oldestContext: contexts.reduce(function(oldest, ctx) {
                        return ctx.createdAt < oldest.createdAt ? ctx : oldest;
                    }, contexts[0])
                };
            }
        },
        {
            /**
   * 获取管理器配置
   */ key: "getConfig",
            value: function getConfig() {
                return this.config;
            }
        },
        {
            /**
   * 销毁管理器
   */ key: "destroy",
            value: function destroy() {
                this.clearAllContexts();
                this.globalMonitors.clear();
            }
        }
    ]);
    return SecurityContextManager;
}();
/**
 * 创建安全上下文管理器的工厂函数
 */ export function createSecurityContextManager(config) {
    return new SecurityContextManager(config);
}
/**
 * 快速在受控环境中执行代码的工具函数
 */ export function runInSecureContext(code, config, contextScope) {
    return _async_to_generator(function() {
        var manager, contextId;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    manager = createSecurityContextManager(config);
                    contextId = manager.createContext();
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        ,
                        3,
                        4
                    ]);
                    return [
                        4,
                        manager.executeInContext(contextId, code, contextScope)
                    ];
                case 2:
                    return [
                        2,
                        _state.sent()
                    ];
                case 3:
                    manager.destroy();
                    return [
                        7
                    ];
                case 4:
                    return [
                        2
                    ];
            }
        });
    })();
}
