NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
1.98k stars 353 forks source link

What does "Expecting native value or pseudo object" means? #191

Closed cosbgn closed 4 years ago

cosbgn commented 4 years ago

I have a simple function which looks like this:

const my_data = {"message":"hello world"}
const code = "return my_data.message"

try {
        const Interpreter = require('js-interpreter');
        const initFunc = function(inter, globalObject) {
            inter.setProperty(globalObject, 'my_data', my_data);
        };
        const function_code = `var x = function(){${code}}; x()`
        const myInterpreter = new Interpreter(function_code, initFunc);
        myInterpreter.run()
        return myInterpreter.value
    } 
catch(e) {
    return e.message
}

That returns Expecting native value or pseudo object instead of hello world - Why?

cpcallen commented 4 years ago

You have violated the type specification for .setProperty, which requires that its second argument be an Interpreter.Value—which is either an Interpreter.Object (a 'pseudo object') or a primitive.

As it happens, it appears that this is not being caught by .setProperty itself, which only verifies the type of its first argument, but later when .getProperty is later called in response to evaluating my_data.message: at that point, the value stored in my_data is invalid and this is fortunately at last caught.

byte-voyager commented 3 years ago
  // return canvas context
  getCanvasContext() {
    return window.vizzz.ctxScratch
  }
// run code
var context = ArtistApi.getCanvasContext();
print(context);
context.beginPath()

Result:

[object CanvasRenderingContext2D]
Expecting native value or pseudo object

How to return canvas context in native function?

cpcallen commented 3 years ago

How to return canvas context in native function?

You cannot and must not; it violates the sandbox.

You will need to wrap your canvas context objects in Interpreter.Object instances (or instances of a subclass of Interpreter.Object). See for example how the interpreter handles native Date and RegExp objects in .initDate and .initRegExp respectively.