function parseModule(filePath, moduleFilePath) { var source; // module might be passed as object containing full source if (typeof filePath === 'object') { source = filePath.source || ''; filePath = filePath.filePath; } filePath = utils.toUnixPath(filePath); //filePath = resolvePath(filePath); if (loadedPaths[filePath]) { return; } loadedPaths[filePath] = true; if (typeof filePath === 'string' && !source) { if (fs.existsSync(filePath)) { source = utils.getFileContents(filePath); } else { if (moduleFilePath) { currentReporter.fatal("Could not find module file: " + filePath + " in " + moduleFilePath + "."); } else { currentReporter.fatal("Could not find module file: " + filePath + "."); } return; } } if (options.version) { var version = options.version.split('.'); source = source.replace(/@@version@@/g, options.version); source = source.replace(/@@majorVersion@@/g, version.shift()); source = source.replace(/@@minorVersion@@/g, version.join('.')); } if (options.releaseDate) { source = source.replace(/@@releaseDate@@/g, options.releaseDate); } currentReporter.debug("Parsing module file: " + filePath); try { vm.runInNewContext(source, { define: function(id, deps, func) { var moduleFilePath = resolveId(id); deps.forEach(function(id) { var depFilePath = resolveId(id); if (options.moduleOverrides && options.moduleOverrides[id]) { depFilePath = options.moduleOverrides[id]; } if (!loadedPaths[depFilePath] && shouldLoadModule(id)) { parseModule(depFilePath, moduleFilePath); } }); modules.push({ filePath: filePath, source: source, id: id, deps: deps, isPublic: isExposed(id, source) }); } }); } catch(ex) { currentReporter.fatal(ex.toString()); } }
var nodeRepl = function(opts) { var readline = require('readline'), path = require('path'), vm = require('vm'), prettyPrint = require('./prettyprint').prettyPrint; var stdout = process.stdout; var stdin = process.openStdin(); var repl = readline.createInterface(stdin, stdout); var env = {}; var sources = {}; var aliases = {}; var sandbox = getSandbox(); var colorLog = function(color) { var args = [].slice.call(arguments, 1); if(opts.colorConsole) { args[0] = '\u001b[' + color + 'm' + args[0]; args[args.length - 1] = args[args.length - 1] + '\u001b[0m'; } console.log.apply(console, args); }; // Include the standard library var fs = require('fs'); var prelude = fs.readFileSync(path.dirname(__dirname) + '/lib/prelude.roy', 'utf8'); vm.runInNewContext(compile(prelude, env).output, sandbox, 'eval'); repl.setPrompt('roy> '); repl.on('close', function() { stdin.destroy(); }); repl.on('line', function(line) { var compiled; var output; var filename; var source; var tokens; var ast; // Check for a "metacommand" // e.g. ":q" or ":l test.roy" var metacommand = line.replace(/^\s+/, '').split(' '); try { switch(metacommand[0]) { case ":q": // Exit process.exit(); break; case ":l": // Load filename = metacommand[1]; source = getFileContents(filename); compiled = compile(source, env, aliases, {nodejs: true, filename: ".", run: true}); break; case ":t": if(metacommand[1] in env) { console.log(env[metacommand[1]].toString()); } else { colorLog(33, metacommand[1], "is not defined."); } break; case ":s": // Source if(sources[metacommand[1]]) { colorLog(33, metacommand[1], "=", prettyPrint(sources[metacommand[1]])); } else { if(metacommand[1]){ colorLog(33, metacommand[1], "is not defined."); }else{ console.log("Usage :s command "); console.log(":s [identifier] :: show original code about identifier."); } } break; case ":?": // Help colorLog(32, "Commands available from the prompt"); console.log(":l -- load and run an external file"); console.log(":q -- exit REPL"); console.log(":s -- show original code about identifier"); console.log(":t -- show the type of the identifier"); console.log(":? -- show help"); break; default: // The line isn't a metacommand // Remember the source if it's a binding tokens = lexer.tokenise(line); ast = parser.parse(tokens); ast[0].accept({ visitLet: function(n) { sources[n.name] = n.value; } }); // Just eval it compiled = compile(line, env, aliases, {nodejs: true, filename: ".", run: true}); break; } if(compiled) { output = vm.runInNewContext(compiled.output, sandbox, 'eval'); if(typeof output != 'undefined') { colorLog(32, (typeof output == 'object' ? JSON.stringify(output) : output) + " : " + compiled.type); } } } catch(e) { colorLog(31, (e.stack || e.toString())); } repl.prompt(); }); repl.prompt(); };
window.eval = function (code) { return vm.runInNewContext(code, window); };
b.bundle(function (err, src) { vm.runInNewContext(src, { t: t }); });
function evaluate(js, ctx) { var ctx = ctx || { window: {}, document: {} }; vm.runInNewContext('main =' + js + '(1)', ctx, 'main.vm'); vm.runInNewContext('require =' + js + '', ctx, 'require.vm'); return ctx; }
t(input, { ignoreErrors: true })(function (result) { var program = runInNewContext(result, {}, input); a(program.foo, 'bar'); }, a.never).done(d, d);
t(input, options)(function (result) { var program = runInNewContext(result, {}); a(program.x.name, 'x', "Same path require"); a(program.x.getZ().name, 'z', "Deferred call"); a(program.x.getZ(), program.x.getZ(), "Requiring same object twice, should return same object"); a(program.y.z.name, 'z', "Require within required module"); a(program.y.z.y.name, 'y', "Circular dependency"); a(program.dirjs, 'DIR.JS', "Directory with '.js' extension"); a(program.indexed.name, 'indexed', "Folder index"); a(program.included.a.name, 'included.a', "Manually included #1"); a(program.included.b.name, 'included.b', "Manually included #2"); a(program.outer.name, 'outer', "Require module up tree"); a(program.outerSubIndex.name, 'outer-index', "Require index from sibling directory"); a(program.pathFile.name, 'path.js', "Dir/file collision: file"); a(program.pathDir.name, 'path', "Dir/file collision: dir"); a(program.pathIndex.name, 'path', "Dir/file collision: dir/index"); a(program.commonPathPart.id, 'sub-longer-bar', "Common path part: main"); a(program.commonPathPart.sub.id, 'sub-foo', "Common path part: outer"); a(program.commonPathPart.subInner.id, 'sub-inner-inner', "Common path part: outer #2"); a(program.commonPathPart.subInner.outer.id, 'sub-longer-other', "Common path part: outer #3"); a(program.commonPathPart.sub.subOuter.id, 'sub-longer-inner-other', "Common path part: outer #5"); a(program.commonPathPart.sub.subOuter.outer.id, 'sub-inner-other', "Common path part: outer #4"); a(program.commonRootPathPart.id, 'sub-longer-bar', "Common path part: main"); a(program.commonRootPathPart.sub.id, 'sub-foo', "Common path part: outer"); a(program.commonRootPathPart.subInner.id, 'sub-inner-inner', "Common root path part: outer #2"); a(program.outerId, '__playground/lib/sub/inner/inner.js', "Inner module id"); a(program.commonRootPathPart.subInner.outer.id, 'sub-longer-other', "Common root path part: outer #3"); a(program.commonRootPathPart.sub.subOuter.id, 'sub-longer-inner-other', "Common root path part: outer #5"); a(program.commonRootPathPart.sub.subOuter.outer.id, 'sub-inner-other', "Common root path part: outer #4"); a(program.pathOther.name, 'path/other', "Dir/file collision: other"); a(program.pathOther.index.name, 'path', "'.' - index require"); a(program.pathOther.indexSlash.name, 'path', "'./' - index require (slash)"); a(program.pathOther.parentIndex, 'main.index', "'..' - parent index"); a(program.pathOther.parentIndexSlash, 'main.index', "'../' - parent index (slash)"); a(program.nlComment, 'nlComment', "New line / Comment"); a(program.external.other.name, 'external-other', "Require module from other package"); a(program.external.other.main, program.external.main, "Require dir by package.json"); a(program.external.main.name, 'external-main', "Require main module from other package"); a(program.external.main.modId, 'test/lib/chosen-one.js', "External package id"); a(program.external.main.module.name, 'module', "Require module within other package"); a(program.external.noMain.name, 'no-main', "Require from package that doesn't have main module"); a(program.nodeshim, 'path for web'); a.deep(program.json, { "raz": 0, "dwa": "trzy", "pięć": false, "cztery": null, "osiem:": undefined }, "JSON"); a(program.modId, '__playground/lib/program.js', "Module id"); a(program.circularOther, 'circTest', "Partially broken dependecy test"); options.output = output; return t(input, options)(lock.call(readFile, output, 'utf8'))( function (content) { a(result, content, "Write to file"); return unlink(output); } ); }).done(d, d);
resolve: function(value) { p(true, [value]); }, reject: function(reason) { p(false, [reason]); } }; } }; } var defs = {}; var ctx = { define: function(name, obj) { defs[name] = obj(); }, require: function(name) { return defs[name]; }, document: { addEventListener: function() {} }, window: {}, setTimeout: function(f, d) { setTimeout(f, d); }, console: console, TypeError: TypeError }; var src = fs.readFileSync("dist/minified-src.js"); vm.runInNewContext(src, ctx, "minified-src.js"); var MINI = ctx.require('minified'), _ = MINI._; promisesAplusTests.mocha(getAdapter(_.promise), function (err) { });
clean = require('gulp-clean'), replace = require('gulp-replace'), uglify = require('gulp-uglify'), htmlreplace = require('gulp-html-replace'); var SSH_CONFIG = { host: 'new.kenoshabowmen.com', port: 22, username: '******', privateKey: fs.readFileSync(process.env["HOME"] + '/.ssh/id_rsa') }; //TODO: read the tinymce plugins from a directory scan // Config var requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;'); requireJsOptimizerConfig = merge(requireJsRuntimeConfig, { out: 'scripts.js', baseUrl: './src', name: 'app/startup', paths: { requireLib: 'bower_modules/requirejs/require', "tinymce-themes": "bower_modules/tinymce/themes/modern/theme", "tinymce-advlist": "bower_modules/tinymce/plugins/advlist/plugin", "tinymce-autolink": "bower_modules/tinymce/plugins/autolink/plugin", "tinymce-lists": "bower_modules/tinymce/plugins/lists/plugin", "tinymce-link": "bower_modules/tinymce/plugins/link/plugin", "tinymce-image": "bower_modules/tinymce/plugins/image/plugin", "tinymce-charmap": "bower_modules/tinymce/plugins/charmap/plugin", "tinymce-preview": "bower_modules/tinymce/plugins/preview/plugin", "tinymce-anchor": "bower_modules/tinymce/plugins/anchor/plugin",
/** * A simple preprocessor that is based on the firefox preprocessor * see (https://developer.mozilla.org/en/Build/Text_Preprocessor). The main * difference is that this supports a subset of the commands and it supports * preproccesor commands in html style comments. * Currently Supported commands: * - if * - else * - endif * - include * - expand */ function preprocess(inFilename, outFilename, defines) { // TODO make this really read line by line. var lines = fs.readFileSync(inFilename).toString().split('\n'); var totalLines = lines.length; var out = ''; var i = 0; function readLine() { if (i < totalLines) { return lines[i++]; } return null; } var writeLine = typeof outFilename === 'function' ? outFilename : function(line) { out += line + '\n'; }; function include(file) { var realPath = fs.realpathSync(inFilename); var dir = path.dirname(realPath); preprocess(path.join(dir, file), writeLine, defines); } function expand(line) { line = line.replace(/__[\w]+__/g, function(variable) { variable = variable.substring(2, variable.length - 2); if (variable in defines) { return defines[variable]; } return ''; }); writeLine(line); } var s, state = 0, stack = []; var control = /^(?:\/\/|<!--)\s*#(if|else|endif|expand|include)(?:\s+(.*?)(?:-->)?$)?/; var lineNumber = 0; while ((s = readLine()) !== null) { ++lineNumber; var m = control.exec(s); if (m) { switch (m[1]) { case 'if': stack.push(state); try { state = vm.runInNewContext(m[2], defines) ? 3 : 1; } catch (e) { console.error('Could not evalute line \'' + m[2] + '\' at ' + fs.realpathSync(inFilename) + ':' + lineNumber); throw e; } break; case 'else': state = state === 1 ? 3 : 2; break; case 'endif': state = stack.pop(); break; case 'expand': if (state === 0 || state === 3) expand(m[2]); break; case 'include': if (state === 0 || state === 3) include(m[2]); break; } } else { if (state === 0) { writeLine(s); } else if (state === 3) { writeLine(s.replace(/^\/\/|^<!--|-->/g, ' ')); } } } if (state !== 0 || stack.length !== 0) throw new Error('Missing endif in preprocessor.'); if (typeof outFilename !== 'function') fs.writeFileSync(outFilename, out); }
var main = function (args) { args = args.slice(2); // ignore Node command and script file var opts = parseOptions(args); var anon = opts.anon; opts = opts.opts; if (opts.jshint) { delete opts.jshint; LINT.name = "JSHint"; LINT.filename = "jshint.js"; LINT.root = "JSHINT"; LINT.source.vsn = "master"; LINT.source.filename = "jshint.js"; LINT.source.path = "/jshint/jshint/"; } LINT.path = path.join(__dirname, LINT.source.vsn + "-" + LINT.filename); var verbose = false, noErrors = false, noWarnings= false; if (opts.verbose) { delete opts.verbose; verbose = true; } if (opts.noerrors) { delete opts.noerrors; noErrors= true; } if (opts.nowarnings) { delete opts.nowarnings; noWarnings= true; } if (opts.help || args.length === 0) { var readme = fs.readFileSync(path.join(__dirname, "README"), "utf-8"); exit(args.length > 0, readme); } if (opts.upgrade) { getJSLint(function (contents) { fs.writeFileSync(LINT.path, contents); main([null, null, "--version"]); // XXX: hacky!? exit(true); }); return; } var jslint; try { jslint = fs.readFileSync(LINT.path, "utf-8"); } catch (exc) { exit(false, "ERROR: " + LINT.path + " not found - " + "use `--upgrade` to initialize"); } if (opts.version) { var sandbox = {}; vm.runInNewContext(jslint, sandbox); exit(true, "JSLint Reporter v" + VERSION + "\n" + LINT.name + " v" + sandbox[LINT.root].edition); } if (verbose) { process.stderr.write("JSLint options: " + util.inspect(opts) + "\n"); } var doLint = function (filepath) { var src = fs.readFileSync(filepath, "utf-8"); var sandbox = { SRC: src, OPTS: opts }; var code = LINT.root + "(SRC, OPTS); var data = " + LINT.root + ".data();"; vm.runInNewContext(jslint + "\n" + code, sandbox); var data = sandbox.data; var implied = (data.implieds || []).map(function (item) { return transformWarning(item, "implied global"); }); var unused = (data.unused || []).map(function (item) { return transformWarning(item, "unused variable"); }); return (data.errors || []).concat(implied).concat(unused); }; var errors = []; var i; for (i = 0; i < anon.length; i += 1) { var filepath = anon[i]; var err = doLint(filepath); err = formatOutput(err, filepath, {noErrors:noErrors, noWarnings:noWarnings}); errors = errors.concat(err); } var pass = errors.length === 0; if (!pass) { util.print(errors.join("\n") + "\n"); if (verbose) { process.stderr.write(String(errors.length) + " errors\n"); } } exit(pass); };
function _require(currentDirectory, module) { if (Array.isArray(module) || /^\.\.?\//.test(module)) { let fn; let content; let p; if (Array.isArray(module)) { p = path.join(currentDirectory, module[0]); content = module .map(arg => { p = path.join(currentDirectory, arg); return fs.readFileSync(p, "utf-8"); }) .join("\n"); } else { p = path.join(currentDirectory, module); content = fs.readFileSync(p, "utf-8"); } if ( options.target === "web" || options.target === "webworker" ) { fn = vm.runInNewContext( "(function(require, module, exports, __dirname, __filename, it, beforeEach, afterEach, expect, jest, window) {" + content + "\n})", globalContext, p ); } else { fn = vm.runInThisContext( "(function(require, module, exports, __dirname, __filename, it, beforeEach, afterEach, expect, jest) {" + "global.expect = expect; " + content + "\n})", p ); } const m = { exports: {} }; fn.call( m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, _it, _beforeEach, _afterEach, expect, jest, globalContext ); return m.exports; } else if ( testConfig.modules && module in testConfig.modules ) { return testConfig.modules[module]; } else return require(module); }
function generate (str, opts) { var i; // the sandbox to use for the vm var sandbox = { dateRange: dateRange, dnsDomainIs: dnsDomainIs, dnsDomainLevels: dnsDomainLevels, dnsResolve: dnsResolve, isInNet: isInNet, isPlainHostName: isPlainHostName, isResolvable: isResolvable, localHostOrDomainIs: localHostOrDomainIs, myIpAddress: myIpAddress, shExpMatch: shExpMatch, timeRange: timeRange, weekdayRange: weekdayRange }; // copy the properties from the user-provided `sandbox` onto ours if (opts && opts.sandbox) { for (i in opts.sandbox) { sandbox[i] = opts.sandbox[i]; } } // construct the array of async function names to add `yield` calls to. // user-provided async functions added to the `sandbox` must have an // `async = true` property set on the function instance var names = []; for (i in sandbox) { if (sandbox[i].async) { names.push(i); sandbox[i] = thunkify(sandbox[i]); } } //console.log(names); // for `facebook/regenerator` sandbox.regeneratorRuntime = rg; // convert the JS FindProxyForURL function into a generator function var js = degenerator(str, names); // use `facebook/regenerator` for node < v0.11 support // TODO: don't use regenerator if native generators are supported... js = regenerator.compile(js, { includeRuntime: false }).code; // filename of the pac file for the vm var filename = opts && opts.filename ? opts.filename : 'proxy.pac'; // evaluate the JS string and extract the FindProxyForURL generator function var fn = vm.runInNewContext(js + ';FindProxyForURL', sandbox, filename); if ('function' != typeof fn) { throw new TypeError('PAC file JavaScript contents must define a `FindProxyForURL` function'); } // return the async resolver function var resolver = co(fn); return function FindProxyForURL (url, host, fn) { resolver(url, host, fn); }; }
var isPlainHostName = require('./isPlainHostName'); var isResolvable = require('./isResolvable'); var localHostOrDomainIs = require('./localHostOrDomainIs'); var myIpAddress = require('./myIpAddress'); var shExpMatch = require('./shExpMatch'); var timeRange = require('./timeRange'); var weekdayRange = require('./weekdayRange'); /** * Module exports. */ module.exports = generate; // cache the `facebook/regenerator` wrap function for the Generator object. var rg = vm.runInNewContext(regenerator.compile('', { includeRuntime: true }).code + ';regeneratorRuntime'); /** * Returns an asyncronous `FindProxyForURL` function from the * given JS string (from a PAC file). * * @param {String} str JS string * @param {Object} opts optional "options" object * @return {Function} async resolver function */ function generate (str, opts) { var i; // the sandbox to use for the vm var sandbox = {
t(input, options)(function (result) { var program = runInNewContext(result, browserContext, input); a(program.html, '<div>HTML</div>\n', "Same path require"); }).done(d, d);
var main = __dirname + '/main.js'; var b = browserify({ entry : main, watch : { interval : 50 }, }); b.on('syntaxError', function (err) { console.log('caught'); if (b.bundle() === src) { console.log('ok'); } else { console.log('fail'); } }); var src = b.bundle(); try { vm.runInNewContext(src, { console : { log : function (s) { console.log('log ' + s); } }, }); } catch (err) { console.log('error ' + err.toString()); }
t(input)(function (result) { var program = runInNewContext(result, {}, input); a(program.name, 'x', "Same path require"); a(program.getZ().name, 'z', "External name"); }).done(d, d);
$(function () { var res = vm.runInNewContext('a + 5', { a : 100 }); $('#res').text(res); });
t(input, { useStrict: true })(function (result) { var program = runInNewContext(result, {}, input); a(program, undefined); }).done(d, d);
b.bundle(function(err, src) { if (err) t.fail(err); vm.runInNewContext(src, {console: {log: log}}); });
function executeIntegrationRest() { logger.incoming.info('Post integration:', this.integration.name); logger.incoming.debug('@urlParams:', this.urlParams); logger.incoming.debug('@bodyParams:', this.bodyParams); if (this.integration.enabled !== true) { return { statusCode: 503, body: 'Service Unavailable' }; } const defaultValues = { channel: this.integration.channel, alias: this.integration.alias, avatar: this.integration.avatar, emoji: this.integration.emoji }; if (this.integration.scriptEnabled === true && this.integration.scriptCompiled && this.integration.scriptCompiled.trim() !== '') { let script; try { script = getIntegrationScript(this.integration); } catch (e) { logger.incoming.warn(e); return RocketChat.API.v1.failure(e.message); } const request = { url: { hash: this.request._parsedUrl.hash, search: this.request._parsedUrl.search, query: this.queryParams, pathname: this.request._parsedUrl.pathname, path: this.request._parsedUrl.path }, url_raw: this.request.url, url_params: this.urlParams, content: this.bodyParams, content_raw: this.request._readableState && this.request._readableState.buffer && this.request._readableState.buffer.toString(), headers: this.request.headers, user: { _id: this.user._id, name: this.user.name, username: this.user.username } }; try { const {sandbox} = buildSandbox(compiledScripts[this.integration._id].store); sandbox.script = script; sandbox.request = request; const result = vm.runInNewContext('script.process_incoming_request({ request: request })', sandbox, { timeout: 3000 }); if (result && result.error) { return RocketChat.API.v1.failure(result.error); } this.bodyParams = result && result.content; if (typeof result !== 'undefined') { this.scriptResponse = result.response; if (result.user) { this.user = result.user; } } logger.incoming.debug('[Process Incoming Request result of Trigger', this.integration.name, ':]'); logger.incoming.debug('result', this.bodyParams); } catch ({stack}) { logger.incoming.error('[Error running Script in Trigger', this.integration.name, ':]'); logger.incoming.error(this.integration.scriptCompiled.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); return RocketChat.API.v1.failure('error-running-script'); } } if (this.bodyParams == null) { return RocketChat.API.v1.failure('body-empty'); } this.bodyParams.bot = { i: this.integration._id }; try { const message = processWebhookMessage(this.bodyParams, this.user, defaultValues); if (_.isEmpty(message)) { return RocketChat.API.v1.failure('unknown-error'); } if (this.scriptResponse) { logger.incoming.debug('response', this.scriptResponse); } return RocketChat.API.v1.success(this.scriptResponse); } catch ({error}) { return RocketChat.API.v1.failure(error); } }
function(error, stdout, stderr) { helper.checkError(error, stdout, stderr); // expected values for prefs and user_prefs var expectedUserPrefs = { 'browser.manifestURL': 'app://system.gaiamobile.org/manifest.webapp', 'browser.homescreenURL': 'app://system.gaiamobile.org/index.html', 'network.http.max-connections-per-server': 15, 'dom.mozInputMethod.enabled': true, 'ril.debugging.enabled': false, 'dom.mms.version': 17, 'b2g.wifi.allow_unsafe_wpa_eap': true }; var expectedPrefs = { 'geo.gps.supl_server': 'supl.izatcloud.net', 'geo.gps.supl_port': 22024, 'dom.payment.provider.0.name': 'firefoxmarket', 'dom.payment.provider.0.description': 'marketplace.firefox.com', 'dom.payment.provider.0.uri': 'https://marketplace.firefox.com/mozpay/?req=', 'dom.payment.provider.0.type': 'mozilla/payments/pay/v1', 'dom.payment.provider.0.requestMethod': 'GET', 'dom.payment.skipHTTPSCheck': true, 'dom.payment.debug': true, 'dom.payment.provider.1.name': 'firefoxmarketdev', 'dom.payment.provider.1.description': 'marketplace-dev.allizom.org', 'dom.payment.provider.1.uri': 'https://marketplace-dev.allizom.org/mozpay/?req=', 'dom.payment.provider.1.type': 'mozilla-dev/payments/pay/v1', 'dom.payment.provider.1.requestMethod': 'GET', 'dom.payment.provider.2.name': 'firefoxmarketstage', 'dom.payment.provider.2.description': 'marketplace.allizom.org', 'dom.payment.provider.2.uri': 'https://marketplace.allizom.org/mozpay/?req=', 'dom.payment.provider.2.type': 'mozilla-stage/payments/pay/v1', 'dom.payment.provider.2.requestMethod': 'GET', 'dom.payment.provider.3.name': 'mockpayprovider', 'dom.payment.provider.3.description': 'Mock Payment Provider', 'dom.payment.provider.3.uri': 'http://ferjm.github.io/gaia-mock-payment-provider/index.html?req=', 'dom.payment.provider.3.type': 'tests/payments/pay/v1', 'dom.payment.provider.3.requestMethod': 'GET' }; // expected values for settings.json from build/config/common-settings.json var settingsPath = path.join(process.cwd(), 'profile', 'settings.json'); var commonSettingsPath = path.join(process.cwd(), 'build', 'config', 'common-settings.json'); var settings = JSON.parse(fs.readFileSync(settingsPath)); var commonSettings = JSON.parse(fs.readFileSync(commonSettingsPath)); // we change these settings values in build/settings.js if // TARGET_BUILD_VARIANT is not 'user' var ignoreSettings = [ 'apz.force-enable', 'debug.console.enabled', 'developer.menu.enabled' ]; ignoreSettings.forEach(function(key) { if (commonSettings[key] !== undefined) { delete commonSettings[key]; } }); // path in zip for unofficial branding var pathInZip = 'shared/resources/branding/initlogo.png'; // zip path for system app var zipPath = path.join(process.cwd(), 'profile', 'webapps', 'system.gaiamobile.org', 'application.zip'); // expected branding file, it should be a unofficial branding if we // execute |make| without rule and variable. var expectedBrandingPath = path.join(process.cwd(), 'shared', 'resources', 'branding', 'unofficial', 'initlogo.png'); // Read user.js and use vm module to execute javascript in user.js var userjs = fs.readFileSync( path.join('profile', 'user.js'), { encoding: 'utf8' } ); var sandbox = helper.getPrefsSandbox(); vm.runInNewContext(userjs, sandbox); var webapps = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'profile', 'webapps', 'webapps.json'))); helper.checkSettings(settings, commonSettings); helper.checkPrefs(sandbox.userPrefs, expectedUserPrefs); helper.checkPrefs(sandbox.prefs, expectedPrefs); helper.checkWebappsScheme(webapps); helper.checkFileInZip(zipPath, pathInZip, expectedBrandingPath); // Check blacklist.json of sms app var hsSmsZip = new AdmZip(path.join(process.cwd(), 'profile', 'webapps', 'sms.gaiamobile.org', 'application.zip')); var hsSmsBlacklistJSON = hsSmsZip.readAsText(hsSmsZip.getEntry('js/blacklist.json')); var expectedResult = ['4850', '7000']; assert.deepEqual(JSON.parse(hsSmsBlacklistJSON), expectedResult, 'Sms blacklist.json is not expected'); // Check config.js file of gallery var hsGalleryZip = new AdmZip(path.join(process.cwd(), 'profile', 'webapps', 'gallery.gaiamobile.org', 'application.zip')); var hsGalleryConfigJs = hsGalleryZip.readAsText(hsGalleryZip.getEntry('js/config.js')); var expectedScript = '//\n' + '// This file is automatically generated: DO NOT EDIT.\n' + '// To change these values, create a camera.json file in the\n' + '// distribution directory with content like this: \n' + '//\n' + '// {\n' + '// "maxImagePixelSize": 6000000,\n' + '// "maxSnapshotPixelSize": 4000000 }\n' + '// }\n' + '//\n' + '// Optionally, you can also define variables to specify the\n' + '// minimum EXIF preview size that will be displayed as a\n' + '// full-screen preview by adding a property like this:\n' + '//\n' + '// "requiredEXIFPreviewSize": { "width": 640, "height": 480}\n' + '//\n' + '// If you do not specify this property then EXIF previews will only' + '\n' + '// be used if they are big enough to fill the screen in either\n' + '// width or height in both landscape and portrait mode.\n' + '//\n' + 'var CONFIG_MAX_IMAGE_PIXEL_SIZE = ' + 5 * 1024 * 1024 + ';\n' + 'var CONFIG_MAX_SNAPSHOT_PIXEL_SIZE = ' + 5 * 1024 * 1024 + ';\n' + 'var CONFIG_REQUIRED_EXIF_PREVIEW_WIDTH = 0;\n' + 'var CONFIG_REQUIRED_EXIF_PREVIEW_HEIGHT = 0;\n'; assert.equal(hsGalleryConfigJs, expectedScript, 'Gallery config js is not expected'); var musicMetadataScriptPath = path.join(process.cwd(), 'build_stage', 'music', 'js', 'metadata_scripts.js'); assert.ok(fs.existsSync(musicMetadataScriptPath), 'metadata_scripts.js ' + 'should exist'); var galleryMetadataScriptPath = path.join(process.cwd(), 'build_stage', 'gallery', 'js', 'metadata_scripts.js'); assert.ok(fs.existsSync(galleryMetadataScriptPath), 'metadata_scripts.js should exist'); var galleryFrameScriptPath = path.join(process.cwd(), 'build_stage', 'gallery', 'js', 'frame_scripts.js'); assert.ok(fs.existsSync(galleryMetadataScriptPath), 'frame_scripts.js should exist'); done(); });
]).bundle(function (err, src) { if (err) throw err; vm.runInNewContext(src, { t: t }); });
function(error, stdout, stderr) { helper.checkError(error, stdout, stderr); var settingsPath = path.join(process.cwd(), 'profile-debug', 'settings.json'); var settings = JSON.parse(fs.readFileSync(settingsPath)); var expectedSettings = { 'lockscreen.enabled': false, 'lockscreen.locked': false, 'screen.timeout': 0, 'debugger.remote-mode': 'adb-devtools' }; var expectedUserPrefs = { 'browser.startup.homepage': 'app://system.gaiamobile.org/index.html', 'startup.homepage_welcome_url': '', 'browser.shell.checkDefaultBrowser': false, 'devtools.toolbox.host': 'side', 'devtools.toolbox.sidebar.width': 800, 'devtools.toolbox.selectedTool': 'firefox-os-controls', 'browser.sessionstore.max_tabs_undo': 0, 'browser.sessionstore.max_windows_undo': 0, 'browser.sessionstore.restore_on_demand': false, 'browser.sessionstore.resume_from_crash': false, 'dom.mozBrowserFramesEnabled': true, 'b2g.ignoreXFrameOptions': true, 'network.disable.ipc.security': true, 'dom.ipc.tabs.disabled': true, 'browser.ignoreNativeFrameTextSelection': true, 'ui.dragThresholdX': 25, 'dom.w3c_touch_events.enabled': 1, 'dom.sms.enabled': true, 'dom.mozTCPSocket.enabled': true, 'notification.feature.enabled': true, 'dom.sysmsg.enabled': true, 'dom.mozAlarms.enabled': true, 'device.storage.enabled': true, 'device.storage.prompt.testing': true, 'notification.feature.enabled': true, 'dom.datastore.enabled': true, 'dom.testing.datastore_enabled_for_hosted_apps': true, 'dom.mozSettings.enabled': true, 'dom.navigator-property.disable.mozSettings': false, 'dom.mozPermissionSettings.enabled': true, 'dom.mozContacts.enabled': true, 'dom.navigator-property.disable.mozContacts': false, 'dom.global-constructor.disable.mozContact': false, 'dom.experimental_forms': true, 'dom.webapps.useCurrentProfile': true, 'bluetooth.enabled': true, 'bluetooth.visible': false, 'wifi.enabled': true, 'wifi.suspended': false, 'font.default.x-western': 'sans-serif', 'font.name.serif.x-western': 'Charis SIL Compact', 'font.name.sans-serif.x-western': 'Fira Sans', 'font.name.monospace.x-western': 'Source Code Pro', 'font.name-list.sans-serif.x-western': 'Fira Sans, Roboto', 'extensions.autoDisableScopes': 0, 'devtools.debugger.enable-content-actors': true, 'devtools.debugger.prompt-connection': false, 'devtools.debugger.forbid-certified-apps': false, 'b2g.adb.timeout': 0 }; var userjs = fs.readFileSync( path.join('profile-debug', 'user.js'), { encoding: 'utf8' } ); var sandbox = helper.getPrefsSandbox(); vm.runInNewContext(userjs, sandbox); helper.checkSettings(settings, expectedSettings); helper.checkPrefs(sandbox.userPrefs, expectedUserPrefs); done(); });
t.doesNotThrow(function() { vm.runInNewContext(src, {}); });
function(error, stdout, stderr) { helper.checkError(error, stdout, stderr); var installedExtsPath = path.join('profile-debug', 'installed-extensions.json'); var expectedSettings = { 'homescreen.manifestURL': 'http://homescreen.gaiamobile.org:8080/manifest.webapp', 'rocketbar.searchAppURL': 'http://search.gaiamobile.org:8080/index.html' }; var expectedUserPrefs = { 'browser.manifestURL': 'http://system.gaiamobile.org:8080/manifest.webapp', 'browser.homescreenURL': 'http://system.gaiamobile.org:8080', 'browser.startup.homepage': 'http://system.gaiamobile.org:8080', 'startup.homepage_welcome_url': '', 'browser.shell.checkDefaultBrowser': false, 'devtools.toolbox.host': 'side', 'devtools.toolbox.sidebar.width': 800, 'devtools.toolbox.selectedTool': 'firefox-os-controls', 'browser.sessionstore.max_tabs_undo': 0, 'browser.sessionstore.max_windows_undo': 0, 'browser.sessionstore.restore_on_demand': false, 'browser.sessionstore.resume_from_crash': false, 'dom.mozBrowserFramesEnabled': true, 'b2g.ignoreXFrameOptions': true, 'network.disable.ipc.security': true, 'dom.ipc.tabs.disabled': true, 'browser.ignoreNativeFrameTextSelection': true, 'ui.dragThresholdX': 25, 'dom.w3c_touch_events.enabled': 1, 'dom.sms.enabled': true, 'dom.mozTCPSocket.enabled': true, 'notification.feature.enabled': true, 'dom.sysmsg.enabled': true, 'dom.mozAlarms.enabled': true, 'device.storage.enabled': true, 'device.storage.prompt.testing': true, 'notification.feature.enabled': true, 'dom.datastore.enabled': true, 'dom.testing.datastore_enabled_for_hosted_apps': true, 'dom.mozSettings.enabled': true, 'dom.navigator-property.disable.mozSettings': false, 'dom.mozPermissionSettings.enabled': true, 'dom.mozContacts.enabled': true, 'dom.navigator-property.disable.mozContacts': false, 'dom.global-constructor.disable.mozContact': false, 'dom.experimental_forms': true, 'dom.webapps.useCurrentProfile': true, 'bluetooth.enabled': true, 'bluetooth.visible': false, 'wifi.enabled': true, 'wifi.suspended': false, 'font.default.x-western': 'sans-serif', 'font.name.serif.x-western': 'Charis SIL Compact', 'font.name.sans-serif.x-western': 'Fira Sans', 'font.name.monospace.x-western': 'Source Code Pro', 'font.name-list.sans-serif.x-western': 'Fira Sans, Roboto', 'docshell.device_size_is_page_size': true, 'marionette.defaultPrefs.enabled': true, 'nglayout.debug.disable_xul_cache': true, 'nglayout.debug.disable_xul_fastload': true, 'javascript.options.showInConsole': true, 'browser.dom.window.dump.enabled': true, 'dom.report_all_js_exceptions': true, 'dom.w3c_touch_events.enabled': 1, 'webgl.verbose': true, 'dom.max_script_run_time': 0, 'toolkit.identity.debug': true, 'network.http.use-cache': false, 'extensions.gaia.dir': process.cwd(), 'extensions.gaia.domain': 'gaiamobile.org', 'extensions.gaia.port': 8080, 'extensions.gaia.locales_debug_path': 'locales', 'extensions.gaia.official': false, 'extensions.gaia.locales_file': 'shared/resources/languages.json', 'extensions.gaia.locale_basedir': '', 'extensions.gaia.device_pixel_suffix': '', 'extensions.autoDisableScopes': 0 }; var settingsPath = path.join(process.cwd(), 'profile-debug', 'settings.json'); var settings = JSON.parse(fs.readFileSync(settingsPath)); var userjs = fs.readFileSync( path.join('profile-debug', 'user.js'), { encoding: 'utf8' } ); var sandbox = helper.getPrefsSandbox(); vm.runInNewContext(userjs, sandbox); var zipCount = 0; dive(path.join(process.cwd(), 'profile-debug'), {recursive: true}, function action(err, file) { if (file.indexOf('application.zip') !== -1) { zipCount++; } }, function complete() { assert.ok(fs.existsSync(installedExtsPath)); helper.checkSettings(settings, expectedSettings); helper.checkPrefs(sandbox.userPrefs, expectedUserPrefs); // only expect one zip file for marketplace. assert.equal(zipCount, 1); done(); } ); });
repl.on('line', function(line) { var compiled; var output; var filename; var source; var tokens; var ast; // Check for a "metacommand" // e.g. ":q" or ":l test.roy" var metacommand = line.replace(/^\s+/, '').split(' '); try { switch(metacommand[0]) { case ":q": // Exit process.exit(); break; case ":l": // Load filename = metacommand[1]; source = getFileContents(filename); compiled = compile(source, env, aliases, {nodejs: true, filename: ".", run: true}); break; case ":t": if(metacommand[1] in env) { console.log(env[metacommand[1]].toString()); } else { colorLog(33, metacommand[1], "is not defined."); } break; case ":s": // Source if(sources[metacommand[1]]) { colorLog(33, metacommand[1], "=", prettyPrint(sources[metacommand[1]])); } else { if(metacommand[1]){ colorLog(33, metacommand[1], "is not defined."); }else{ console.log("Usage :s command "); console.log(":s [identifier] :: show original code about identifier."); } } break; case ":?": // Help colorLog(32, "Commands available from the prompt"); console.log(":l -- load and run an external file"); console.log(":q -- exit REPL"); console.log(":s -- show original code about identifier"); console.log(":t -- show the type of the identifier"); console.log(":? -- show help"); break; default: // The line isn't a metacommand // Remember the source if it's a binding tokens = lexer.tokenise(line); ast = parser.parse(tokens); ast[0].accept({ visitLet: function(n) { sources[n.name] = n.value; } }); // Just eval it compiled = compile(line, env, aliases, {nodejs: true, filename: ".", run: true}); break; } if(compiled) { output = vm.runInNewContext(compiled.output, sandbox, 'eval'); if(typeof output != 'undefined') { colorLog(32, (typeof output == 'object' ? JSON.stringify(output) : output) + " : " + compiled.type); } } } catch(e) { colorLog(31, (e.stack || e.toString())); } repl.prompt(); });
function instantiate(compiled) { return vm.runInNewContext(wrapModule(compiled.source), {_require}); }
iframe.eval = function (code) { var res = vm.runInNewContext(code, iframe); return res; };
Codesurgeon.prototype.validate = function(options, output) { var that = this; var requirements = []; var sandbox = { // // hijack the require function. // require: function(s) { // // if we find a path to a local file, try to read the file, // add its contents to the output buffer and the recurse into // addreqs again in case there are new requirements inside the // expanded buffer. // if(s[0] === '.' || ~s.indexOf('/')) { !that.options.quiet && console.log('A module was required, but not inlined to the buffer [' + s.red + ']'); // // inlining the code presents two problems, 1. the filename which i think we can deduce from // the last read file (provided as `that.lastfile`). 2. the module has several ways to export // so it may be `this`, `module.exports`, `exports`, etc. Here's one potential solution... // // var lastpath = that.lastread.substr(0, that.lastread.lastIndexOf('/')+1); // // this obviously does not work, could possibly stat for the file in the same order that // node tries to search for it. // // var fileandpath = lastpath + s + '.js'; // that.read(fileandpath); // var requirement = new RegExp('\\(?require\\)?\\s*\\([\\\'|"]' + s + '[\\\'|"]\\)'); // var wrappedcode = '(function(module) { \n\n' + that.inputs[fileandpath] + '\n\n return module; })()'; // that.output = that.output.replace(requirement, wrappedcode); } // // this is a requirement for a module not a file, we can add it // to the requirements path. // else { requirements.push(s); require(s); } } }; // // attempt to run the code in a new context, its ok // for errors to occur, we'll just report them to the // user. We hijack the require function and push the // module name to an array that we can use to build // up our unknown dependencies list. // try { vm.runInNewContext(output || this.output, sandbox, 'tmp.vm'); } catch(ex) { !that.options.quiet && console.log('An error occured while executing the code in the ouput buffer [', ex.message.red, ']'); } // // remove any known requirements and add any new // requirements that are found in the output code. // requirements.forEach(function(dep, i) { if(that.packageJSON.dependencies[dep]) { requirements.splice(i, 1); } else { that.packageJSON.dependencies[dep] = '*'; } }); // // tell the user we found some unique requirements from // out analysis of the output buffer. // !that.options.quiet && console.log('Able to add the following modules to the package.json [', requirements.join(', ').green, ']'); // // we now have an updated dependencies member in the package.json // structure, we could possibly rewrite the file depending on the // options that the user has chosen. // // console.log(this.packageJSON.dependencies) return this; };