// Create a new isolate limited to 128MB
const ivm = require('isolated-vm');

function createIsolate() {
    let context;
    const isolate = new ivm.Isolate({ memoryLimit: 128 });
 
    // Create a new context within this isolate. Each context has its own copy of all the builtin
    // Objects. So for instance if one context does Object.prototype.foo = 1 this would not affect any
    // other contexts.
    context = isolate.createContextSync();
    
    // Get a Reference{} to the global object within the context.
    const jail = context.global;
    
    // This make the global object available in the context as `global`. We use `derefInto()` here
    // because otherwise `global` would actually be a Reference{} object in the new isolate.
    jail.setSync('global', jail.derefInto());
    
    // We will create a basic `log` function for the new isolate to use.
    const logCallback = function(...args) {
        console.log(...args);
    };
    context.evalClosureSync(`global.console.log = function(...args) {
        $0.applyIgnored(undefined, args, { arguments: { copy: true } });
    }`, [ logCallback ], { arguments: { reference: true } });
    
    // And let's test it out:
    // context.evalSync('logging sync test.');
    return {isolate, context};
}


module.exports.createIsolate = createIsolate;

