"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryEval = void 0;
var sdk_1 = require("@builder6/sdk");
var safe_dynamic_require_1 = require("./safe-dynamic-require");
var is_debug_1 = require("./is-debug");
var string_to_function_1 = require("./string-to-function");
var should_force_browser_runtime_in_node_1 = require("./should-force-browser-runtime-in-node");
var tryEval = function (str, data, errors) {
    if (data === void 0) { data = {}; }
    var value = str;
    if (!(typeof value === 'string' && value.trim())) {
        return;
    }
    var useReturn = !(value.includes(';') || value.includes(' return '));
    var fn = function () {
        /* Intentionally empty */
    };
    try {
        if (sdk_1.Builder.isBrowser) {
            // tslint:disable-next-line:no-function-constructor-with-string-args
            // TODO: VM in node......
            fn = new Function('state', 
            // TODO: remove the with () {} - make a page v3 that doesn't use this
            "var rootState = state;\n        if (typeof Proxy !== 'undefined') {\n          rootState = new Proxy(rootState, {\n            set: function () {\n              return false;\n            },\n            get: function (target, key) {\n              if (key === 'state') {\n                return state;\n              }\n              return target[key]\n            }\n          });\n        }\n        with (rootState) {\n          ".concat(useReturn ? "return (".concat(str, ");") : str, ";\n        }"));
        }
    }
    catch (error) {
        if (sdk_1.Builder.isBrowser) {
            console.warn('Could not compile javascript', error);
        }
        else {
            // Add to req.options.errors to return to client
        }
    }
    try {
        if (sdk_1.Builder.isBrowser || (0, should_force_browser_runtime_in_node_1.shouldForceBrowserRuntimeInNode)()) {
            return fn(data || {});
        }
        else {
            // Below is a hack to get certain code to *only* load in the server build, to not screw with
            // browser bundler's like rollup and webpack. Our rollup plugin strips these comments only
            // for the server build
            var ivm = (0, safe_dynamic_require_1.safeDynamicRequire)('isolated-vm');
            var context = (0, string_to_function_1.getIsolateContext)();
            var fnString = (0, string_to_function_1.makeFn)(str, useReturn, ['state']);
            var resultStr = context.evalClosureSync(fnString, [new ivm.Reference(data || {})]);
            try {
                // returning objects throw errors in isolated vm, so we stringify it and parse it back
                return JSON.parse(resultStr);
            }
            catch (_error) {
                return resultStr;
            }
        }
    }
    catch (error) {
        if (errors) {
            errors.push(error);
        }
        if (sdk_1.Builder.isBrowser) {
            console.warn('Builder custom code error:', error.message, 'in', str, error.stack);
        }
        else {
            if ((0, is_debug_1.isDebug)()) {
                console.debug('Builder custom code error:', error.message, 'in', str, error.stack);
            }
            // Add to req.options.errors to return to client
        }
    }
    return;
};
exports.tryEval = tryEval;
//# sourceMappingURL=try-eval.js.map