SandboxJS icon indicating copy to clipboard operation
SandboxJS copied to clipboard

Reuse compiled code

Open AStaroverov opened this issue 1 year ago • 4 comments

After attempt use compiled code with different contexts I catching error

ReferenceError: plus is not defined

and my code

function plus(n,u){return n+u};function minus(n,u){return n-u};var a=plus(value,10);return minus(a,5);.

In documentation I didn't see nothing about this restriction.

So its bug on not?

AStaroverov avatar Oct 17 '23 16:10 AStaroverov

Please provide sample code on how you are using different contexts

nyariv avatar Oct 18 '23 08:10 nyariv

for example

const body = 'function plus(n,u){return n+u};function minus(n,u){return n-u};var a=plus(value,10);return minus(a,5);'
const s = sandbox.compile(body, true);

console.log(s({value: 1}).run());
console.log(s({value: 2}).run());

AStaroverov avatar Oct 18 '23 09:10 AStaroverov

I found that after first run context.tree will be modified, that broke second call.

This workaround help me

    const parsed = Sandbox.parse(body);
    const context = sandbox.createContext(sandbox.context, parsed);
    const tree = context.tree;
    return (scope) => {
        context.tree = structuredClone(tree);
        return sandbox.executeTree(context, [scope]).result;
    };

AStaroverov avatar Oct 18 '23 10:10 AStaroverov

Just bumped into this problem. The code:

function printValue(value) {
  console.log(value)
}

printValue(row)

Executed with: exec({ row }).run() The above only works in the first execution, and in the others it throws printValue is not defined. This works normally, though:

const printValue = (value) => {
  console.log(value)
}

printValue(row)

So SandboxJS doesn't work well with hoisted functions?

gustavotoyota avatar Apr 14 '24 19:04 gustavotoyota