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 _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
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
        };
    }
}
import { createSandbox, runInSandbox } from "./ProxySandbox";
// 导出主要的沙箱类和工具函数
export { ProxySandbox, createSandbox, runInSandbox } from "./ProxySandbox";
// 导出安全上下文管理器
export { SecurityContextManager, createSecurityContextManager, runInSecureContext } from "./SecurityContextManager";
/**
 * 默认的沙箱配置
 */ export var DEFAULT_SANDBOX_CONFIG = {
    allowedGlobals: [
        'console',
        'Math',
        'Date',
        'JSON',
        'parseInt',
        'parseFloat',
        'String',
        'Number',
        'Boolean',
        'Array',
        'Object',
        'RegExp'
    ],
    forbiddenGlobals: [
        'eval',
        'Function',
        'constructor',
        'prototype',
        '__proto__',
        'document',
        'window',
        'global',
        'globalThis',
        'XMLHttpRequest',
        'fetch',
        'localStorage',
        'sessionStorage'
    ],
    allowConsole: true,
    allowTimers: false,
    timeout: 3000,
    strictMode: true,
    allowDOM: false,
    maxMemoryUsage: 5 * 1024 * 1024
};
/**
 * 默认的安全上下文配置
 */ export var DEFAULT_SECURITY_CONFIG = _object_spread_props(_object_spread({}, DEFAULT_SANDBOX_CONFIG), {
    permissions: {
        network: false,
        fileSystem: false,
        media: false,
        geolocation: false,
        notifications: false
    },
    limits: {
        maxExecutionTime: 3000,
        maxMemoryUsage: 5 * 1024 * 1024,
        maxCallStackDepth: 50,
        maxLoopIterations: 1000
    },
    monitoring: {
        enablePerformanceMonitoring: true,
        enableErrorTracking: true,
        enableResourceMonitoring: true
    }
});
/**
 * 沙箱工厂函数 - 创建配置好的沙箱实例
 */ export function createConfiguredSandbox() {
    var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 'basic';
    switch(type){
        case 'basic':
            return createSandbox(DEFAULT_SANDBOX_CONFIG);
        case 'secure':
            return createSandbox(_object_spread_props(_object_spread({}, DEFAULT_SANDBOX_CONFIG), {
                allowConsole: false,
                allowTimers: false,
                timeout: 2000,
                strictMode: true
            }));
        case 'restricted':
            return createSandbox({
                allowedGlobals: [
                    'Math',
                    'JSON',
                    'String',
                    'Number'
                ],
                forbiddenGlobals: [
                    'console',
                    'eval',
                    'Function',
                    'constructor',
                    'prototype',
                    '__proto__',
                    'document',
                    'window',
                    'global',
                    'globalThis'
                ],
                allowConsole: false,
                allowTimers: false,
                timeout: 1000,
                strictMode: true,
                allowDOM: false,
                maxMemoryUsage: 1024 * 1024
            });
        default:
            return createSandbox(DEFAULT_SANDBOX_CONFIG);
    }
}
/**
 * 快速执行简单代码的便捷函数
 */ export function quickExecute(code, customGlobals, injectedParams) {
    return _async_to_generator(function() {
        var result;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    return [
                        4,
                        runInSandbox(code, _object_spread_props(_object_spread({}, DEFAULT_SANDBOX_CONFIG), {
                            customGlobals: customGlobals
                        }), injectedParams)
                    ];
                case 1:
                    result = _state.sent();
                    if (!result.success) {
                        throw result.error || new Error('Code execution failed');
                    }
                    return [
                        2,
                        result.result
                    ];
            }
        });
    })();
}
/**
 * 执行数学表达式的安全计算器
 */ export function safeMathEval(expression) {
    return _async_to_generator(function() {
        var mathOnlyConfig, safePattern, result, value;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    // 只允许数学运算和基本函数
                    mathOnlyConfig = {
                        allowedGlobals: [
                            'Math'
                        ],
                        forbiddenGlobals: [
                            'console',
                            'eval',
                            'Function',
                            'constructor'
                        ],
                        allowConsole: false,
                        allowTimers: false,
                        timeout: 1000,
                        strictMode: true,
                        customGlobals: {
                            // 预定义安全的数学函数
                            abs: Math.abs,
                            ceil: Math.ceil,
                            floor: Math.floor,
                            round: Math.round,
                            max: Math.max,
                            min: Math.min,
                            pow: Math.pow,
                            sqrt: Math.sqrt,
                            sin: Math.sin,
                            cos: Math.cos,
                            tan: Math.tan,
                            PI: Math.PI,
                            E: Math.E
                        }
                    };
                    // 验证表达式只包含安全字符
                    safePattern = /^[0-9+\-*/.() \t\n,a-zA-Z_$]+$/;
                    if (!safePattern.test(expression)) {
                        throw new Error('Expression contains unsafe characters');
                    }
                    return [
                        4,
                        runInSandbox("return ".concat(expression), mathOnlyConfig)
                    ];
                case 1:
                    result = _state.sent();
                    if (!result.success) {
                        throw result.error || new Error('Math evaluation failed');
                    }
                    value = result.result;
                    if (typeof value !== 'number' || !isFinite(value)) {
                        throw new Error('Result is not a valid number');
                    }
                    return [
                        2,
                        value
                    ];
            }
        });
    })();
}
/**
 * 沙箱状态检查工具
 */ export var SandboxHealthChecker = /*#__PURE__*/ function() {
    "use strict";
    function SandboxHealthChecker() {
        _class_call_check(this, SandboxHealthChecker);
    }
    _create_class(SandboxHealthChecker, [
        {
            /**
   * 检查浏览器环境是否支持沙箱功能
   */ key: "checkEnvironmentSupport",
            value: function checkEnvironmentSupport() {
                var issues = [];
                var recommendations = [];
                // 检查 Proxy 支持
                if (typeof Proxy === 'undefined') {
                    issues.push('Proxy is not supported in this environment');
                    recommendations.push('Use a modern browser that supports ES6 Proxy');
                }
                // 检查 Performance API
                if (typeof performance === 'undefined') {
                    issues.push('Performance API is not available');
                    recommendations.push('Performance monitoring will be disabled');
                }
                // 检查 Worker 支持（可选）
                if (typeof Worker === 'undefined') {
                    recommendations.push('Web Workers not supported - consider using for heavy computations');
                }
                return {
                    supported: issues.length === 0,
                    issues: issues,
                    recommendations: recommendations
                };
            }
        },
        {
            key: "testBasicFunctionality",
            value: /**
   * 测试沙箱基本功能
   */ function testBasicFunctionality() {
                return _async_to_generator(function() {
                    var results, errors, basicResult, error, error1, error2, passed;
                    return _ts_generator(this, function(_state) {
                        switch(_state.label){
                            case 0:
                                results = {};
                                errors = [];
                                _state.label = 1;
                            case 1:
                                _state.trys.push([
                                    1,
                                    3,
                                    ,
                                    4
                                ]);
                                return [
                                    4,
                                    quickExecute('return 1 + 1')
                                ];
                            case 2:
                                basicResult = _state.sent();
                                results.basicExecution = basicResult === 2;
                                return [
                                    3,
                                    4
                                ];
                            case 3:
                                error = _state.sent();
                                results.basicExecution = false;
                                errors.push("Basic execution failed: ".concat(error));
                                return [
                                    3,
                                    4
                                ];
                            case 4:
                                _state.trys.push([
                                    4,
                                    6,
                                    ,
                                    7
                                ]);
                                // 测试全局对象隔离
                                return [
                                    4,
                                    quickExecute('window = {}; return true')
                                ];
                            case 5:
                                _state.sent();
                                results.globalIsolation = false; // 应该抛出错误
                                return [
                                    3,
                                    7
                                ];
                            case 6:
                                error1 = _state.sent();
                                results.globalIsolation = true; // 正确阻止了访问
                                return [
                                    3,
                                    7
                                ];
                            case 7:
                                _state.trys.push([
                                    7,
                                    9,
                                    ,
                                    10
                                ]);
                                // 测试超时机制
                                return [
                                    4,
                                    runInSandbox('while(true) {}', {
                                        timeout: 100
                                    })
                                ];
                            case 8:
                                _state.sent();
                                results.timeoutMechanism = false; // 应该超时
                                return [
                                    3,
                                    10
                                ];
                            case 9:
                                error2 = _state.sent();
                                results.timeoutMechanism = _instanceof(error2, Error) && error2.message.includes('timeout');
                                return [
                                    3,
                                    10
                                ];
                            case 10:
                                passed = Object.values(results).every(Boolean);
                                return [
                                    2,
                                    {
                                        passed: passed,
                                        results: results,
                                        errors: errors
                                    }
                                ];
                        }
                    });
                })();
            }
        }
    ], [
        {
            key: "getInstance",
            value: function getInstance() {
                if (!SandboxHealthChecker.instance) {
                    SandboxHealthChecker.instance = new SandboxHealthChecker();
                }
                return SandboxHealthChecker.instance;
            }
        }
    ]);
    return SandboxHealthChecker;
}();
_define_property(SandboxHealthChecker, "instance", null);
/**
 * 导出健康检查器实例
 */ export var sandboxHealthChecker = SandboxHealthChecker.getInstance();
