當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript vm.createContext函數代碼示例

本文整理匯總了TypeScript中vm.createContext函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript createContext函數的具體用法?TypeScript createContext怎麽用?TypeScript createContext使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了createContext函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: DynamicRequire

                fs.readFile(scriptFile, (err: NodeJS.ErrnoException, data: Buffer) => {
                    let required: { [id: number]: any } = {};
                    let requiredIndex: number = 0;
                    try {

                        let code = '(function (request, response, next){\ntry{\n'
                            + data.toString().replace(/require\s*\(\s*[\'"]\s*\[\s*(\w+)\s*\]\s*[\'"]\s*\)/ig, (capture: string, ...args: any[]) => {
                                return args[0];
                            }).replace(/require\s*\(\s*[\'"](\.+[\/a-z_\-\s0-9\.]+)[\'"]\s*\)/ig, (capture: string, ...args: any[]) => {
                                //console.log('Replacing: ', capture);
                                let $file = pathreducer.reduce($directory + '//' + args[0] + '.js');
                                required[requiredIndex] = DynamicRequire(pathreducer.filename($file), pathreducer.pathname($file));
                                let replacement = '$__required[' + requiredIndex + ']';
                                requiredIndex += 1;
                                return replacement;
                            }) +
                            '\n}\ncatch(ex){\n\tconsole.log("Error:", ex);\n\tresponse.statusCode = 500;\n\tresponse.end(ex.toString()); \n}\n})';
                        //console.log(code);
                        let context = vm.createContext({
                            console: console,
                            require: require,
                            __dirname: $directory,
                            __filename: scriptFile,
                            process: process,
                            $__required: required
                        });
                        let _script = vm.createScript(code);
                        let fn: MiddlewareHandler = _script.runInContext(context);
                        fn(req, res, next);
                    }
                    catch (ex) {
                        console.log(ex);
                    }
                });
開發者ID:errisy,項目名稱:ng2ts,代碼行數:34,代碼來源:cgi.ts

示例2: createContext

export function createContext(compilerCtx: d.CompilerCtx, outputTarget: d.OutputTargetWww, sandbox: any) {
  const vm = require('vm');
  // https://github.com/tmpvar/jsdom/issues/1724
  // manually adding a fetch polyfill until jsdom adds it
  patchFetch(compilerCtx, outputTarget, sandbox);

  patchRaf(sandbox);

  return vm.createContext(sandbox);
}
開發者ID:franktopel,項目名稱:stencil,代碼行數:10,代碼來源:node-context.ts

示例3: createSandbox

function createSandbox(filename: string, logger: Logger): ISandbox {
  const module = new Module(filename)
  module.paths = Module._nodeModulePaths(filename)

  const sandbox = vm.createContext({
    module,
    Buffer,
    console: {
      log: (...args: any[]) => {
        logger.debug.apply(logger, args)
      },
      error: (...args: any[]) => {
        logger.error.apply(logger, args)
      },
      info: (...args: any[]) => {
        logger.info.apply(logger, args)
      },
      warn: (...args: any[]) => {
        logger.warn.apply(logger, args)
      }
    }
  }) as ISandbox

  defaults(sandbox, global)
  sandbox.Reflect = Reflect

  sandbox.require = function sandboxRequire(p): any {
    const oldCompile = Module.prototype._compile
    Module.prototype._compile = compileInSandbox(sandbox)
    const moduleExports = sandbox.module.require(p)
    Module.prototype._compile = oldCompile
    return moduleExports
  }

  // patch `require` in sandbox to run loaded module in sandbox context
  // if you need any of these, it might be worth discussing spawning separate processes
  sandbox.process = new (process as any).constructor()
  for (let key of Object.keys(process)) {
    sandbox.process[key] = process[key]
  }

  REMOVED_GLOBALS.forEach(name => {
    sandbox.process[name] = removedGlobalStub(name)
  })

  // read-only umask
  sandbox.process.umask = (mask: number) => {
    if (typeof mask !== 'undefined') {
      throw new Error('Cannot use process.umask() to change mask (read-only)')
    }
    return process.umask()
  }

  return sandbox
}
開發者ID:illarionvk,項目名稱:dotfiles,代碼行數:55,代碼來源:factory.ts

示例4: constructor

  constructor(config: Config.ProjectConfig) {
    this.context = vm.createContext();
    const global = (this.global = vm.runInContext(
      'this',
      Object.assign(this.context, config.testEnvironmentOptions),
    ));
    global.global = global;
    global.clearInterval = clearInterval;
    global.clearTimeout = clearTimeout;
    global.setInterval = setInterval;
    global.setTimeout = setTimeout;
    global.ArrayBuffer = ArrayBuffer;
    // URL and URLSearchParams are global in Node >= 10
    if (typeof URL !== 'undefined' && typeof URLSearchParams !== 'undefined') {
      /* global URL, URLSearchParams */
      global.URL = URL;
      global.URLSearchParams = URLSearchParams;
    }
    // TextDecoder and TextDecoder are global in Node >= 11
    if (
      typeof TextEncoder !== 'undefined' &&
      typeof TextDecoder !== 'undefined'
    ) {
      /* global TextEncoder, TextDecoder */
      global.TextEncoder = TextEncoder;
      global.TextDecoder = TextDecoder;
    }
    installCommonGlobals(global, config.globals);
    this.moduleMocker = new ModuleMocker(global);

    const timerIdToRef = (id: number) => ({
      id,
      ref() {
        return this;
      },
      unref() {
        return this;
      },
    });

    const timerRefToId = (timer: Timer): number | undefined =>
      (timer && timer.id) || undefined;

    const timerConfig = {
      idToRef: timerIdToRef,
      refToId: timerRefToId,
    };

    this.fakeTimers = new FakeTimers({
      config,
      global,
      moduleMocker: this.moduleMocker,
      timerConfig,
    });
  }
開發者ID:Volune,項目名稱:jest,代碼行數:55,代碼來源:index.ts

示例5: runCodeAndExtract

// tslint:disable-next-line:no-any
function runCodeAndExtract(source: string): any {
  let result = null;
  let numCalls = 0;
  let sandbox = {
    // tslint:disable-next-line:no-any
    setResult(r: any): void {
      result = r;
      numCalls++;
    }
  };
  vm.createContext(sandbox);
  vm.runInContext(source, sandbox);
  if (numCalls !== 1) {
    throw new Error(`expected setResult to be called exactly once`);
  }
  return result;
}
開發者ID:alangpierce,項目名稱:decaffeinate,代碼行數:18,代碼來源:validate.ts

示例6: Buffer

    const part2: string = decoder2.write(new Buffer('test'));
    const end2: string = decoder1.end(new Buffer('test'));
}

////////////////////////////////////////////////////
/// vm tests : https://nodejs.org/api/vm.html
////////////////////////////////////////////////////

{
    {
        const sandbox = {
            animal: 'cat',
            count: 2
        };

        const context = vm.createContext(sandbox);
        console.log(vm.isContext(context));
        const script = new vm.Script('count += 1; name = "kitty"');

        for (let i = 0; i < 10; ++i) {
            script.runInContext(context);
        }

        console.log(util.inspect(sandbox));

        vm.runInNewContext('count += 1; name = "kitty"', sandbox);
        console.log(util.inspect(sandbox));
    }

    {
        const sandboxes = [{}, {}, {}];
開發者ID:Lavoaster,項目名稱:DefinitelyTyped,代碼行數:31,代碼來源:node-tests.ts

示例7: Symbol

import * as device from "./device";
import * as extensions from "./extensions";
import * as logger from "./logger";
import * as scheduling from "./scheduling";
import Path from "./common/path";
import { Fault, SessionContext } from "./types";

// Used for throwing to exit user script and commit
const COMMIT = Symbol();

// Used to execute extensions and restart
const EXT = Symbol();

const UNDEFINED = undefined;

const context = vm.createContext();

let state;

const runningExtensions = new WeakMap();
function runExtension(sessionContext, key, extCall, callback): void {
  let re = runningExtensions.get(sessionContext);
  if (!re) {
    re = {};
    runningExtensions.set(sessionContext, re);
  }

  if (re[key]) {
    re[key].push(callback);
  } else {
    re[key] = [callback];
開發者ID:zaidka,項目名稱:genieacs,代碼行數:31,代碼來源:sandbox.ts

示例8: generateRules

  static generateRules ({ name, type, rule, value }: any): any {
    // see https://github.com/nuysoft/Mock/wiki/Syntax-Specification
    let rules = []
    switch (type) {
      // 被暫時忽略的小分組
      case 'RegExp':
      case 'Function':
      case 'Object':
        return

      case 'Array':
        if (rule !== '+1') {
          return
        }

        let arr
        try {
          let ctx = vm.createContext()
          arr = vm.runInContext(value, ctx, {
            timeout: 1000,
          })
        } catch (err) {
          break
        }

        let set = new Set()
        for (let item in arr) {
          if (!_.isBoolean(item) && typeof item !== 'string' && typeof item !== 'number') {
            continue
          }
          set.add(item.toString().charAt(0))
        }
        for (let i = 'A'.charCodeAt(0), j = 'z'.charCodeAt(0); i < j; i++) {
          if (!set.has(String.fromCharCode(i))) {
            rules.push(encapsulate(String.fromCharCode(i), '數組枚舉邊界'))
            break
          }
        }

        break

      // 先實現的小分組
      case 'String': {
        if (!RULE_NUM_INT.test(rule)) {
          break
        }
        // 構建長度邊界
        RULE_NUM_INT.lastIndex = -1
        let [, intMin, intMax]: any = RULE_NUM_INT.exec(rule)
        intMin = +intMin
        intMax = +intMax
        if (intMin > 0) {
          rules.push(encapsulate(
            'x'.repeat((value.length || 1) * (intMin - 1)),
            '字符串長度下界',
          ))
        }
        if (intMax < Number.MAX_SAFE_INTEGER) {
          rules.push(encapsulate(
            'x'.repeat((value.length || 1) * (intMax + 1)),
            '字符串長度上界',
          ))
        }
        break
      }
      case 'Number': {
        // 構建類型邊界
        rules.push(encapsulate('NaN', '數字類型邊界'))

        if (!RULE_NUM_INT.test(rule)) {
          break
        }
        RULE_NUM_INT.lastIndex = -1
        let [, intMin, intMax]: any = RULE_NUM_INT.exec(rule)
        intMin = +intMin
        intMax = +intMax

        if (RULE_NUM_DEC.test(rule)) {
          RULE_NUM_DEC.lastIndex = -1
          let [, decMin, decMax]: any = RULE_NUM_INT.exec(rule)
          decMin = +decMin
          decMax = +decMax
          // let int = intMin + Math.round(Math.random() * (intMax - intMin))
          let dec: any = (decMin + Math.round(Math.random() * (decMax - decMin))) * 0.01

          // 構建精度邊界 -- 暫緩
          // rules.push(encapsulate(
          //   int + Math.pow(0.1, (decMin - 1)),
          //   '精度下界'
          // ))
          // rules.push(encapsulate(
          //   int + Math.pow(0.1, (decMax + 1)),
          //   '精度上界'
          // ))

          // 構建整數邊界
          rules.push(encapsulate(
            dec + intMin - 1,
            '數值下界',
          ))
//.........這裏部分代碼省略.........
開發者ID:tonyjt,項目名稱:rap2-delos,代碼行數:101,代碼來源:roomHelper.ts

示例9: runCommand

				function runCommand () {
					commands.runCmd(rootNode.cmd, argValues.concat(args), streams, callback);
				}
			}, '[alias]');
		},
		home: __dirname,
		setLayout: setLayout,
		on: function (event: string, cb: () => any) {
			// TODO
		},
		layout: null,
	},
};
const extend = utils.extend;
const ctx = vm.createContext(permanent);
const commands = new CommandSet(defaultCommands());
const executerVisitor = new ExecuterVisitor(commands, ctx);
const history = new History(lineReader);



process.on('SIGINT', () => {
	console.log('\nSIGINT'.blue.bold);
	if (!paused) {
		console.log();
		lineReader.refreshLine();
	}
});
process.on('SIGCHLD', function () {
	if (paused) {
開發者ID:bteixeira,項目名稱:nodeshell,代碼行數:30,代碼來源:shell.ts


注:本文中的vm.createContext函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。