nyariv / SandboxJS

Safe eval runtime
https://nyariv.github.io/SandboxJS/
MIT License
104 stars 5 forks source link

Reuse compiled code #20

Open AStaroverov opened 8 months ago

AStaroverov commented 8 months ago

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?

nyariv commented 8 months ago

Please provide sample code on how you are using different contexts

AStaroverov commented 8 months ago

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 commented 8 months ago

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;
    };
gustavotoyota commented 2 months ago

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?