var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _SandboxedRuntimeLite_instances, _SandboxedRuntimeLite_scope, _SandboxedRuntimeLite_runtime, _SandboxedRuntimeLite_vm, _SandboxedRuntimeLite_importObjectPtr, _SandboxedRuntimeLite_actor, _SandboxedRuntimeLite_intl, _SandboxedRuntimeLite_aborted, _SandboxedRuntimeLite_console, _SandboxedRuntimeLite_modules, _SandboxedRuntimeLite_pluginCallId, _SandboxedRuntimeLite_pluginReturnHandlers, _SandboxedRuntimeLite_localMetadata, _SandboxedRuntimeLite_dependencyMetadata, _SandboxedRuntimeLite_loadingIntl, _SandboxedRuntimeLite_importObject, _SandboxedRuntimeLite_eval, _SandboxedRuntimeLite_initConsole, _SandboxedRuntimeLite_initImporter, _SandboxedRuntimeLite_initCircuitBreaker, _SandboxedRuntimeLite_initPluginProxy, _SandboxedRuntimeLite_initRequire, _SandboxedRuntimeLite_initFetch, _SandboxedRuntimeLite_initIntlProxy, _SandboxedRuntimeLite_initIntlHydration, _SandboxedRuntimeLite_logErr, _SandboxedRuntimeLite_marshalValue, _SandboxedRuntimeLite_objectProxy, _SandboxedRuntimeLite_functionProxy, _SandboxedRuntimeLite_resolvePromise;
import { CircuitBreak, isCircuitBreaker } from '@devvit/shared-types/CircuitBreaker.js';
import releaseSync from '@jitl/quickjs-singlefile-browser-release-sync';
import { newQuickJSWASMModuleFromVariant, Scope, } from 'quickjs-emscripten-core';
import corejs from '../../dist/assets/corejs.js?raw';
import intlPolyfill from '../../dist/assets/intl-polyfill.js?raw';
import intlStub from '../../dist/assets/intl-stub.js?raw';
import protos from '../../dist/assets/protos.js?raw';
import { QueueConsole } from '../console/QueueConsole.js';
import { ActorResponse } from '../types/Commands.js';
import { inspect } from '../utils/inspect.js';
import { getDependencyMetadata } from '../utils/metadata.js';
import { box } from './RuntimeLite.js';
const wasmModule = newQuickJSWASMModuleFromVariant(releaseSync);
export class SandboxedRuntimeLite {
    /**
     * @arg modules Environment dependencies available via `require(id)` to
     *              bundles loaded. Unlike UnsandboxedRuntimeLite, values must be
     *              stringified JavaScript. @devvit/protos is provided by default.
     */
    constructor(modules = {}) {
        _SandboxedRuntimeLite_instances.add(this);
        _SandboxedRuntimeLite_scope.set(this, void 0);
        _SandboxedRuntimeLite_runtime.set(this, void 0);
        _SandboxedRuntimeLite_vm.set(this, void 0);
        _SandboxedRuntimeLite_importObjectPtr.set(this, void 0);
        _SandboxedRuntimeLite_actor.set(this, void 0);
        _SandboxedRuntimeLite_intl.set(this, void 0);
        _SandboxedRuntimeLite_aborted.set(this, false);
        _SandboxedRuntimeLite_console.set(this, box.console);
        _SandboxedRuntimeLite_modules.set(this, void 0);
        _SandboxedRuntimeLite_pluginCallId.set(this, 0);
        _SandboxedRuntimeLite_pluginReturnHandlers.set(this, {});
        _SandboxedRuntimeLite_localMetadata.set(this, {});
        _SandboxedRuntimeLite_dependencyMetadata.set(this, {});
        _SandboxedRuntimeLite_loadingIntl.set(this, false);
        _SandboxedRuntimeLite_importObject.set(this, (vm, obj) => {
            return vm
                .newString(typeof obj === 'string' ? obj : JSON.stringify(obj))
                .consume((inputPtr) => vm.callFunction(__classPrivateFieldGet(this, _SandboxedRuntimeLite_importObjectPtr, "f"), vm.null, inputPtr).unwrap());
        });
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_modules, {
            '@devvit/protos': protos,
            ...modules,
        }, "f");
    }
    enableAppLogging() {
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_console, new QueueConsole(), "f");
    }
    getCallState() {
        return { logs: __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs ?? [] };
    }
    async init() {
        box.log('[sandboxed runtime] init');
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_scope, new Scope(), "f");
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_runtime, __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage((await wasmModule).newRuntime({
            memoryLimitBytes: 1024 * 1024 * 1024, // 1GB temp limit
            maxStackSizeBytes: 0,
        })), "f");
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_vm, __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_runtime, "f").newContext()), "f");
        const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
        vm.runtime.setModuleLoader((module) => {
            const builtins = {
                'core-js': corejs,
                'intl-stub': intlStub,
                'intl-polyfill': intlPolyfill,
            };
            if (module in builtins) {
                return builtins[module];
            }
            if (module in __classPrivateFieldGet(this, _SandboxedRuntimeLite_modules, "f")) {
                return __classPrivateFieldGet(this, _SandboxedRuntimeLite_modules, "f")[module];
            }
            return '';
        });
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'globalThis.self = globalThis;');
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initConsole).call(this);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initIntlHydration).call(this);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'import("core-js");');
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'import("intl-stub");');
        await __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initRequire).call(this); // Warning: long operation
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initImporter).call(this);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initCircuitBreaker).call(this);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initPluginProxy).call(this);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_initFetch).call(this);
    }
    setPluginList(plugins) {
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, `const plugins = ${JSON.stringify(plugins)};`);
    }
    setLocalMetadata(meta) {
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_localMetadata, meta, "f");
    }
    loadBundle(bundle) {
        __classPrivateFieldSet(this, _SandboxedRuntimeLite_dependencyMetadata, getDependencyMetadata(bundle), "f");
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs = [];
        const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
        // language=JavaScript
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'const module = {};', bundle.code, 
        // to-do: don't pollute user code. This causes an error if the user also
        //        declares a local called "config".
        `const config = {
        assets: ${JSON.stringify(bundle.assets)},
        webviewAssets: ${JSON.stringify(bundle.webviewAssets)},
        use: (def) => {
          if (plugins.includes(def.fullName)) {
            const proxy = {};
            for(const method of Object.values(def.methods)) {
              proxy[method.name] = async (req, metadata) => {
                const result = await callPlugin(def.fullName, method.name, req, metadata);
                return JSON.parse(result);
              }
            }
            return proxy;
          } else {
            const circuitBreaker = {};
            for (const method of Object.values(def.methods)) {
              circuitBreaker[method.name] = () => {
                circuitBreak(method.name);
              };
            }
            return circuitBreaker;
          }
        },
        provides: () => {}
      };`, 
        /**
         * @deprecated This is used by older apps but is no longer needed with newer versions of public-api
         *             Apps using public-api 0.10.22 or newer no longer depend on this global.
         */
        `globalThis.devvit = { config: { assets: config.assets } };`);
        try {
            __classPrivateFieldSet(this, _SandboxedRuntimeLite_actor, __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage(vm
                .evalCode(`
            if (!module.exports?.default) throw Error('bundle missing default export')
            new module.exports.default(config);
          `)
                .unwrap()), "f");
        }
        catch (err) {
            __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_logErr).call(this, err);
            throw err;
        }
    }
    async call(method, args, meta) {
        return Scope.withScopeAsync(async (scope) => {
            const vm = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_runtime, "f").newContext());
            const actor = __classPrivateFieldGet(this, _SandboxedRuntimeLite_actor, "f");
            __classPrivateFieldSet(this, _SandboxedRuntimeLite_aborted, false, "f");
            __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs = [];
            if (!actor) {
                return {
                    error: new Error('No actor loaded'),
                    success: false,
                    value: undefined,
                };
            }
            const funcPtr = scope.manage(vm.getProp(actor, method));
            const argsPtr = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_importObject, "f").call(this, vm, args));
            // The order of metadata is intentional here:
            // - Use the local environment metadata first
            // - Allow per-call overrides with call metadata
            // - But do not allow `devvit-dependencies` to be overwritten
            const callMetadata = { ...__classPrivateFieldGet(this, _SandboxedRuntimeLite_localMetadata, "f"), ...meta, ...__classPrivateFieldGet(this, _SandboxedRuntimeLite_dependencyMetadata, "f") };
            const metaPtr = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_importObject, "f").call(this, vm, callMetadata));
            const result = vm.callFunction(funcPtr, actor, argsPtr, metaPtr);
            let resultPromisePtr;
            try {
                resultPromisePtr = scope.manage(result.unwrap());
            }
            catch (err) {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_logErr).call(this, err);
                return { error: err, success: false, value: undefined };
            }
            let resolved;
            try {
                resolved = await __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_resolvePromise).call(this, resultPromisePtr);
            }
            catch (err) {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_logErr).call(this, err);
                return { error: err, success: false, value: undefined };
            }
            let msgPtr;
            try {
                msgPtr = scope.manage(resolved);
            }
            catch (err) {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_logErr).call(this, err);
                return { error: err, success: false, value: undefined };
            }
            const response = vm.dump(msgPtr);
            if (__classPrivateFieldGet(this, _SandboxedRuntimeLite_aborted, "f")) {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs = [];
                // Do not use the response. The circuit break was uncleared which may
                // indicate that the break Error was caught unintentionally.
                return { error: CircuitBreak(method), success: false, value: undefined };
            }
            return { error: undefined, success: true, value: response };
        });
    }
    callBinary() {
        throw new Error('binary calls are unsupported');
    }
    onPluginResponse(id, result) {
        Scope.withScope((scope) => {
            const handler = __classPrivateFieldGet(this, _SandboxedRuntimeLite_pluginReturnHandlers, "f")[id];
            if (handler && handler.alive) {
                if (result.success) {
                    const value = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").newString(JSON.stringify(result.value)));
                    handler.resolve(value);
                }
                else {
                    const error = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").newError(result.error.message));
                    handler.reject(error);
                }
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").runtime.executePendingJobs().dispose();
            }
            handler.dispose();
            delete __classPrivateFieldGet(this, _SandboxedRuntimeLite_pluginReturnHandlers, "f")[id];
        });
    }
    quit() {
        box.log('[sandboxed runtime] quitting');
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").dispose();
        globalThis.close();
    }
}
_SandboxedRuntimeLite_scope = new WeakMap(), _SandboxedRuntimeLite_runtime = new WeakMap(), _SandboxedRuntimeLite_vm = new WeakMap(), _SandboxedRuntimeLite_importObjectPtr = new WeakMap(), _SandboxedRuntimeLite_actor = new WeakMap(), _SandboxedRuntimeLite_intl = new WeakMap(), _SandboxedRuntimeLite_aborted = new WeakMap(), _SandboxedRuntimeLite_console = new WeakMap(), _SandboxedRuntimeLite_modules = new WeakMap(), _SandboxedRuntimeLite_pluginCallId = new WeakMap(), _SandboxedRuntimeLite_pluginReturnHandlers = new WeakMap(), _SandboxedRuntimeLite_localMetadata = new WeakMap(), _SandboxedRuntimeLite_dependencyMetadata = new WeakMap(), _SandboxedRuntimeLite_loadingIntl = new WeakMap(), _SandboxedRuntimeLite_importObject = new WeakMap(), _SandboxedRuntimeLite_instances = new WeakSet(), _SandboxedRuntimeLite_eval = function _SandboxedRuntimeLite_eval(...args) {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    for (const code of args) {
        vm.evalCode(code, undefined).unwrap().dispose();
    }
}, _SandboxedRuntimeLite_initConsole = function _SandboxedRuntimeLite_initConsole() {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    const methods = Object.keys({
        debug: true,
        error: true,
        info: true,
        log: true,
        trace: true,
        warn: true,
    });
    Scope.withScope((scope) => {
        const consolePtr = scope.manage(vm.newObject());
        for (const method of methods) {
            const fnPtr = scope.manage(vm.newFunction(method, (...args) => {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f")[method](...args.map(vm.dump));
            }));
            vm.setProp(consolePtr, method, fnPtr);
        }
        vm.setProp(vm.global, 'console', consolePtr);
    });
}, _SandboxedRuntimeLite_initImporter = function _SandboxedRuntimeLite_initImporter() {
    __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'function importObject(objStr) { return JSON.parse(objStr); }');
    __classPrivateFieldSet(this, _SandboxedRuntimeLite_importObjectPtr, __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").getProp(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").global, 'importObject')), "f");
}, _SandboxedRuntimeLite_initCircuitBreaker = function _SandboxedRuntimeLite_initCircuitBreaker() {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    Scope.withScope((scope) => {
        const circuitBreakFn = scope.manage(vm.newFunction('circuitBreak', (...args) => {
            const method = args[0] ? vm.dump(args[0]) : 'unknown';
            box.log('[sandboxed runtime] circuit break: ', method);
            __classPrivateFieldSet(this, _SandboxedRuntimeLite_aborted, true, "f");
            __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs = [];
            throw CircuitBreak(method);
        }));
        vm.setProp(vm.global, 'circuitBreak', circuitBreakFn);
        // See WorkerBox.clearCircuitBreak.
        const clearCircuitBreakFn = scope.manage(vm.newFunction('clearCircuitBreak', () => {
            __classPrivateFieldSet(this, _SandboxedRuntimeLite_aborted, false, "f");
            box.log('[sandboxed runtime] circuit break cleared');
        }));
        vm.setProp(vm.global, 'clearCircuitBreak', clearCircuitBreakFn);
    });
}, _SandboxedRuntimeLite_initPluginProxy = function _SandboxedRuntimeLite_initPluginProxy() {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    Scope.withScope((scope) => {
        const callPluginFn = scope.manage(vm.newFunction('callPlugin', (...args) => {
            var _a;
            const [service, method, req, meta] = args.map(vm.dump);
            const id = __classPrivateFieldSet(this, _SandboxedRuntimeLite_pluginCallId, (_a = __classPrivateFieldGet(this, _SandboxedRuntimeLite_pluginCallId, "f"), ++_a), "f");
            const promise = vm.newPromise();
            __classPrivateFieldGet(this, _SandboxedRuntimeLite_pluginReturnHandlers, "f")[id] = promise;
            box.postMessage([ActorResponse.PLUGIN_CALL, id, service, method, req, meta]);
            return promise.handle;
        }));
        vm.setProp(vm.global, 'callPlugin', callPluginFn);
    });
}, _SandboxedRuntimeLite_initRequire = 
/**
 * Route `require()` calls to `import`s for pre-packaged dependencies like
 * @devvit/protos. Devvit apps are CJS for compute-go compatibility and to
 * force them to use require() (the unsandboxed runtime can't override
 * import).
 */
async function _SandboxedRuntimeLite_initRequire() {
    __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, `globalThis.__imports__ = {};`, 
    // language=javascript
    `function require(module) {
        for(const prefix of Object.keys(globalThis.__imports__)) {
          if (module.startsWith(prefix)) {
            return globalThis.__imports__[prefix];
          }
        }
      }`);
    const imports = Object.keys(__classPrivateFieldGet(this, _SandboxedRuntimeLite_modules, "f")).map((name) => `import('${name}').then((mod) => { globalThis.__imports__['${name}'] = mod; })`);
    const importPromise = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f")
        .evalCode(
    // language=javascript
    `Promise.all([${imports.join(',')}]);`)
        .unwrap();
    (await __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_resolvePromise).call(this, importPromise)).dispose();
    importPromise.dispose();
}, _SandboxedRuntimeLite_initFetch = function _SandboxedRuntimeLite_initFetch() {
    __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, "function fetch() { circuitBreak('fetch'); }");
}, _SandboxedRuntimeLite_initIntlProxy = function _SandboxedRuntimeLite_initIntlProxy() {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    __classPrivateFieldSet(this, _SandboxedRuntimeLite_intl, __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_objectProxy).call(this, Object.freeze(Intl))), "f");
    vm.setProp(vm.global, 'Intl', __classPrivateFieldGet(this, _SandboxedRuntimeLite_intl, "f"));
}, _SandboxedRuntimeLite_initIntlHydration = function _SandboxedRuntimeLite_initIntlHydration() {
    const importIntlPolyfill = __classPrivateFieldGet(this, _SandboxedRuntimeLite_scope, "f").manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").newFunction('importIntlPolyfill', () => {
        if (!__classPrivateFieldGet(this, _SandboxedRuntimeLite_loadingIntl, "f")) {
            __classPrivateFieldSet(this, _SandboxedRuntimeLite_loadingIntl, true, "f");
            const loadPolyfill = () => {
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'import("intl-polyfill").then(() => { globalThis.importIntlPolyfill = undefined; });');
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_runtime, "f").executePendingJobs();
            };
            // if the app isn't ready yet because we hit Intl during loadBundle,
            // we need to wait for Intl so the app can initialize correctly
            if (!__classPrivateFieldGet(this, _SandboxedRuntimeLite_actor, "f")) {
                loadPolyfill();
            }
            else {
                // if the actor is running, defer loading until the next frame so we
                // can circuit break without waiting for the import to complete
                setTimeout(loadPolyfill, 1);
                __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_eval).call(this, 'circuitBreak();');
            }
        }
    }));
    __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").setProp(__classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").global, 'importIntlPolyfill', importIntlPolyfill);
}, _SandboxedRuntimeLite_logErr = function _SandboxedRuntimeLite_logErr(err) {
    var _a;
    // Don't log circuit breaks. The runtime operates optimistically. When
    // it fails, all side-effects are rolled back. Logs should not be reported.
    if (!isCircuitBreaker(err)) {
        (_a = __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f")).logs ?? (_a.logs = []);
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_console, "f").logs.push({ method: 'error', args: [inspect(err)] });
    }
}, _SandboxedRuntimeLite_marshalValue = function _SandboxedRuntimeLite_marshalValue(value) {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    switch (typeof value) {
        case 'string':
            return vm.newString(value);
        case 'number':
            return vm.newNumber(value);
        case 'boolean':
            return value ? vm.true : vm.false;
        case 'bigint':
            return vm.newBigInt(value);
        case 'function':
            return __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_functionProxy).call(this, value);
        case 'object':
            if (Array.isArray(value)) {
                const result = vm.newArray();
                Scope.withScope((scope) => {
                    value.forEach((e, i) => vm.setProp(result, i, scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_marshalValue).call(this, e))));
                });
                return result;
            }
            else if (value === null) {
                return vm.null;
            }
            return __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_objectProxy).call(this, value);
    }
    return vm.undefined;
}, _SandboxedRuntimeLite_objectProxy = function _SandboxedRuntimeLite_objectProxy(obj) {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    const proxy = vm.newObject();
    const props = Object.getOwnPropertyNames(obj);
    let isStatic = true;
    if (props.length === 0) {
        isStatic = false;
        props.push(...Object.getOwnPropertyNames(Object.getPrototypeOf(obj)));
    }
    props
        .filter((prop) => !['length', 'name', 'prototype', 'constructor'].includes(prop))
        .forEach((propName) => Scope.withScope((scope) => {
        const objProps = obj;
        const prop = objProps[propName];
        const propType = typeof prop;
        let value = vm.undefined;
        if (propType === 'function') {
            value = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_functionProxy).call(this, (...args) => {
                const owner = isStatic ? null : obj;
                // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
                return prop.apply(owner, args.map(vm.dump));
            }));
        }
        else {
            value = scope.manage(__classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_marshalValue).call(this, prop));
        }
        vm.setProp(proxy, propName, value);
    }));
    return proxy;
}, _SandboxedRuntimeLite_functionProxy = function _SandboxedRuntimeLite_functionProxy(func) {
    const vm = __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f");
    return vm.newFunction(func.name, (...args) => {
        return __classPrivateFieldGet(this, _SandboxedRuntimeLite_instances, "m", _SandboxedRuntimeLite_marshalValue).call(this, func.call(null, ...args));
    });
}, _SandboxedRuntimeLite_resolvePromise = async function _SandboxedRuntimeLite_resolvePromise(promise) {
    // This quirky statement awaits the promise and executes pending jobs
    // without an extra local:
    // 1. Enqueue a promise with resolvePromise().
    // 2. Invoke executePendingJobs() directly (the await is on the outer
    //    promise).
    // 3. executePendingJobs() is synchronous so the result is automatically
    //    promisified but we don't care as we don't use it, only the result
    //    of resolvePromise().
    const [resolved] = await Promise.all([
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").resolvePromise(promise),
        __classPrivateFieldGet(this, _SandboxedRuntimeLite_vm, "f").runtime.executePendingJobs().dispose(),
    ]);
    return resolved.unwrap();
};
