コード例 #1
0
async function test() {
  const foo = new SourceTextModule('export const a = 1;');
  await foo.link(common.mustNotCall());
  foo.instantiate();
  await foo.evaluate();

  {
    const s = new Script('import("foo")', {
      importModuleDynamically: common.mustCall((specifier, wrap) => {
        assert.strictEqual(specifier, 'foo');
        assert.strictEqual(wrap, s);
        return foo;
      }),
    });

    const result = s.runInThisContext();
    assert.strictEqual(foo.namespace, await result);
  }

  {
    const m = new SourceTextModule('import("foo")', {
      importModuleDynamically: common.mustCall((specifier, wrap) => {
        assert.strictEqual(specifier, 'foo');
        assert.strictEqual(wrap, m);
        return foo;
      }),
    });
    await m.link(common.mustNotCall());
    m.instantiate();
    const { result } = await m.evaluate();
    assert.strictEqual(foo.namespace, await result);
  }
}
コード例 #2
0
ファイル: JsFileLoader.js プロジェクト: alekitto/jymfony
    /**
     * @inheritdoc
     */
    load(resource) {
        const filePath = this._locator.locate(resource);
        const previousCurrentDir = this.currentDir;

        this.currentDir = path.dirname(filePath);

        const code = '(function (loader, __filename, __dirname) {\n'+fs.readFileSync(filePath)+'\n})';
        const script = new vm.Script(code, {
            filename: filePath,
            produceCachedData: false,
        });

        let collection;
        const result = script.runInThisContext({
            filename: filePath,
        })(this, filePath, this.currentDir);

        if (isFunction(result)) {
            const configurator = new RoutingConfigurator(new RouteCollection(), this, this.currentDir, filePath);
            result(configurator, this);

            collection = configurator.build();
        } else {
            collection = result;
        }

        collection.addResource(new FileResource(filePath));
        this.currentDir = previousCurrentDir;

        return collection;
    }
コード例 #3
0
ファイル: bot-vk.js プロジェクト: Raccoon666999/vkBot
 callScript(path, options) {
   try {
     let data = fs.readFileSync(path, {encoding: 'utf8'});
     let script = new vm.Script(data);
     script.runInThisContext()(options);
   } catch(e) {
     logger.error('[callSCript]', e);
   }
 }
コード例 #4
0
ファイル: main.js プロジェクト: ethereum/ethereum-console
	fs.readFile(jsScript, 'utf8', function (err, data) {
		if (err) {
			console.log(err);
			process.exit();
		} else {
			var script = new vm.Script(data);
			script.runInThisContext();
		}
	});
コード例 #5
0
function testRejectInvalid() {
  const source = getSource('invalid');

  const data = produce(source);

  // It should reject invalid code cache
  const script = new vm.Script(getSource('invalid_1'), {
    cachedData: data
  });
  assert(script.cachedDataRejected);
  assert.equal(script.runInThisContext()(), 'invalid_1');
}
コード例 #6
0
function testProduceConsume() {
  const source = getSource('original');

  const data = produce(source);

  // It should consume code cache
  const script = new vm.Script(source, {
    cachedData: data
  });
  assert(!script.cachedDataRejected);
  assert.equal(script.runInThisContext()(), 'original');
}
コード例 #7
0
ファイル: bootstrap.js プロジェクト: Jerry-goodboy/pkg
  Module.prototype._compile = function (content, filename_) {
    if (!insideSnapshot(filename_)) {
      return ancestor._compile.apply(this, arguments);
    }
    if (insideMountpoint(filename_)) {
      // DONT TRANSLATE! otherwise __dirname gets real name
      return ancestor._compile.apply(this, arguments);
    }

    var filename = normalizePath(filename_);
    // console.log("_compile", filename);
    var entity = VIRTUAL_FILESYSTEM[filename];

    if (!entity) {
      // let user try to "_compile" a packaged file
      return ancestor._compile.apply(this, arguments);
    }

    var entityBlob = entity[STORE_BLOB];
    var entityContent = entity[STORE_CONTENT];

    if (entityBlob) {
      var options = {
        filename: filename,
        lineOffset: 0,
        displayErrors: true,
        cachedData: payloadFileSync(entityBlob),
        sourceless: !entityContent
      };

      var Script = require('vm').Script;
      var code = entityContent
        ? require('module').wrap(payloadFileSync(entityContent))
        : undefined;

      var script = new Script(code, options);
      var wrapper = script.runInThisContext(options);
      if (!wrapper) process.exit(4); // for example VERSION_MISMATCH
      var dirname = require('path').dirname(filename);
      var rqfn = makeRequireFunction(this);
      var args = [ this.exports, rqfn, this, filename, dirname ];
      return wrapper.apply(this.exports, args);
    }

    if (entityContent) {
      if (entityBlob) throw new Error('UNEXPECTED-50');
      // content is already in utf8 and without BOM (that is expected
      // by stock _compile), but entityContent is still a Buffer
      return ancestor._compile.apply(this, arguments);
    }

    throw new Error('UNEXPECTED-55');
  };
コード例 #8
0
  /**
   * Gets a generated function to adapt the row to a document.
   * @param {ModelMappingInfo} info
   * @param {ResultSet} rs
   * @returns {Function}
   */
  static getSelectAdapter(info, rs) {
    const columns = rs.columns;
    if (!columns) {
      throw new Error('Expected ROWS result obtained VOID');
    }

    let scriptText = '(function rowAdapter(row, info) {\n' +
      '  const item = info.newInstance();\n';

    scriptText += columns.map(c => `  item['${info.getPropertyName(c.name)}'] = row['${c.name}'];`).join('\n');

    scriptText += '\n  return item;\n})';

    const script = new vm.Script(scriptText);
    return script.runInThisContext({ filename: 'gen-result-mapper.js'});
  }
コード例 #9
0
  _moduleCompile(filename, content) {
    // https://github.com/nodejs/node/blob/v7.5.0/lib/module.js#L511

    // Remove shebang
    var contLen = content.length;
    if (contLen >= 2) {
      if (content.charCodeAt(0) === 35/*#*/ &&
          content.charCodeAt(1) === 33/*!*/) {
        if (contLen === 2) {
          // Exact match
          content = '';
        } else {
          // Find end of shebang line and slice it off
          var i = 2;
          for (; i < contLen; ++i) {
            var code = content.charCodeAt(i);
            if (code === 10/*\n*/ || code === 13/*\r*/) break;
          }
          if (i === contLen) {
            content = '';
          } else {
            // Note that this actually includes the newline character(s) in the
            // new output. This duplicates the behavior of the regular
            // expression that was previously used to replace the shebang line
            content = content.slice(i);
          }
        }
      }
    }

    // create wrapper function
    var wrapper = Module.wrap(content);

    var invalidationKey = crypto
      .createHash('sha1')
      .update(content, 'utf8')
      .digest('hex');

    var buffer = this._cacheStore.get(filename, invalidationKey);

    var script = new vm.Script(wrapper, {
      filename: filename,
      lineOffset: 0,
      displayErrors: true,
      cachedData: buffer,
      produceCachedData: true,
    });

    if (script.cachedDataProduced) {
      this._cacheStore.set(filename, invalidationKey, script.cachedData);
    } else if (script.cachedDataRejected) {
      this._cacheStore.delete(filename);
    }

    var compiledWrapper = script.runInThisContext({
      filename: filename,
      lineOffset: 0,
      columnOffset: 0,
      displayErrors: true,
    });

    return compiledWrapper;
  }
コード例 #10
0
assert.throws(function() {
  script.runInThisContext(script);
});
コード例 #11
0
define(["require", "q", "./runtime-util"], function(rjs, Q, util) {
  var ourCajaVM;
  function unsafeCaja() {
    var compileExpr = function(src) {
      return function(env) {
        var define = env.define;
        return Function("define", src)(define);
      }
    };
    ourCajaVM = { compileExpr: compileExpr };
  }
  if(util.isBrowser()) {
    // caja.js had better be on the page already
    if(typeof caja === "undefined") {
      console.warn("Page was loaded without SES, so evals will be unguarded. Does this page load https://caja.appspot.com/caja.js?");
      unsafeCaja();
    }
    else {
      caja.initialize({
        debug: true,
        forceES5Mode: true
      });
      caja.load(undefined, undefined, function(frame) {
        ourCajaVM = {
          compileExpr: function(s) {
            return function(env) { frame.code("https://", "application/javascript", s).api(env).run(); }
          }
        };
      });
    }
  }
  else {
    var FS = require("fs");
    var VM = require("vm");

    var RUN_SES = false; // NOTE(joe): skipping on servers for now; SES isn't really there yet
    if(RUN_SES) {
      var source = FS.readFileSync(require.nodeRequire.resolve("ses/initSES.js"));
      var oldLog = console.log;
      console.log = function() { /* intentional no-op to suppress SES logging */ }
      var script = new VM.Script(source);
      script.runInThisContext();
      ourCajaVM = cajaVM;
      console.log = oldLog;
    } else {
      unsafeCaja();
    }
  }

  function safeEval(string, env) {
    var f = ourCajaVM.compileExpr(string);
    return f(env);
  }

  function loadClosure(runtime, mod, dependencies) {
    var deferred = Q.defer();
    try {
      var answer = mod.apply(null, dependencies);
      deferred.resolve(answer);
    } catch(e) {
      deferred.reject(e);
    }
    return deferred.promise;
  }


  function loadSingle(runtime, src, dependencies) {
    var deferred = Q.defer();
    try {
      safeEval(src, {
        define: function(_, body) {
          try {
            // NOTE(joe): dependencies should be empty list, or the whole
            // object should just be passed in here
            var moduleAsObject = body.apply(null, dependencies);
            // NOTE(joe): modules should be objects, but old ones are
            // functions
            if(typeof moduleAsObject === "function") {
              deferred.resolve(moduleAsObject);
            }
            else {
              deferred.resolve(moduleAsObject.theModule.apply(null, dependencies));
            }
          } catch(e) {
            deferred.reject(e);
          }
        }
      });
    }
    catch(e) {
      deferred.reject(e);
    }
    return deferred.promise;
  }

  function goodIdea(runtime, name, src) {
    var deferred = Q.defer();
    require.undef(name);
    try {
      safeEval(src, { define: function(deps, body) {
          define(name, deps, body);
          function success(val) {
            deferred.resolve(val);
          }
          // Since requirejs seems to not call our errback, use its global
          // error handler.
          var oldOnError = require.onError;
          require.onError = function(err) {
            require.onError = oldOnError;
            var names = [];
            for(var i = 0; i < err.requireModules.length; i++) {
              require.undef(err.requireModules[i]);
              names.push(err.requireModules[i]);
            }
            deferred.reject(runtime.makePyretFailException(runtime.ffi.makeModuleLoadFailureL(names)));
          };
          require([name], success);
        }
      });
    }
    catch(e) {
      deferred.reject(e);
    }
    return deferred.promise;
  }

  return {
    safeEval: safeEval,
    goodIdea: goodIdea,
    loadSingle: loadSingle,
    loadClosure: loadClosure
  }
});
コード例 #12
0
ファイル: chap3-4.js プロジェクト: safarishi/LearningNode2
var vm = require('vm');
var fs = require('fs');

global.count1 = 100;
var count2 = 100;

var script = new vm.Script(fs.readFileSync('script.js','utf8'));
script.runInThisContext({filename: 'count.vm'});

console.log(count1);
console.log(count2);
コード例 #13
0
assert.throws(function() {
  Script.runInThisContext('throw new Error(\'test\');');
});
コード例 #14
0
// Copyright & License details are available under JXCORE_LICENSE file


var common = require('../common');
var assert = require('assert');
var Script = require('vm').Script;

common.globalCheck = false;

common.debug('run a string');
var result = Script.runInThisContext('\'passed\';');
assert.equal('passed', result);

common.debug('thrown error');
assert.throws(function() {
  Script.runInThisContext('throw new Error(\'test\');');
});

hello = 5;
Script.runInThisContext('hello = 2');
assert.equal(2, hello);


common.debug('pass values');
code = 'foo = 1;' +
       'bar = 2;' +
       'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');';
foo = 2;
obj = { foo: 0, baz: 3 };
var baz = Script.runInThisContext(code);
assert.equal(0, obj.foo);
コード例 #15
0
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
const common = require('../common');
const assert = require('assert');
const Script = require('vm').Script;

common.globalCheck = false;

// Run a string
let script = new Script('\'passed\';');
const result = script.runInThisContext(script);
assert.strictEqual('passed', result);

// Thrown error
script = new Script('throw new Error(\'test\');');
assert.throws(() => {
  script.runInThisContext(script);
}, /^Error: test$/);

global.hello = 5;
script = new Script('hello = 2');
script.runInThisContext(script);
assert.strictEqual(2, global.hello);


// Pass values
コード例 #16
0
assert.throws(() => {
  script.runInThisContext(script);
}, /^Error: test$/);
コード例 #17
0
ファイル: test.js プロジェクト: double-m/com_marcellomessori
/* global before, describe, it, require, arraymultiplier, __dirname */

'use strict';

var fs = require('fs')
  , vm = require('vm')
  , chai = require('chai')
  , Browser = require('zombie')
  , expect = chai.expect;

var arraymultiplierBuf = fs.readFileSync(__dirname + '/../../app/scripts/arraymultiplier.js')
  , arraymultiplierScript = arraymultiplierBuf.toString()
    .replace(/\/*.*\//g, '')
    .replace(/\n/g, '')
  , evaluateArraymultiplierScript = new vm.Script(arraymultiplierScript);
evaluateArraymultiplierScript.runInThisContext();

describe('Scripts', function () {
  it('returns the product of three array items', function () {
    expect(arraymultiplier([1, 2, 3])).to.equal(6);
  });
});

describe('Headless A-B tests', function () {
  var browser = new Browser({site: 'http://localhost:9001'});

  before(function (done) {
    browser.visit('/', done);
  });

  it('should find h1 children', function () {