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


TypeScript vm.runInContext函數代碼示例

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


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

示例1: sourceSync

export function sourceSync (filename: string, context: Context) {
	if (!fs.existsSync(filename)) {
		return new Error('No such file: ' + filename);
	}
	const contents: string = fs.readFileSync(filename).toString();
	return vm.runInContext(contents, context);
}
開發者ID:bteixeira,項目名稱:nodeshell,代碼行數:7,代碼來源:utils.ts

示例2: visitJS

	visitJS(token: DescentParserNode, streams: Stream[], callback: executionCallback): void {
		try {
			var result = vm.runInContext(token.token.text, this.context);
			callback(result);
		} catch (e) {
			callback(new Error(e)); /* Exceptions thrown from VM must be wrapped to enable `instanceof` */
		}
	}
開發者ID:bteixeira,項目名稱:nodeshell,代碼行數:8,代碼來源:executerVisitor.ts

示例3: 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

示例4: function

 return function(this: any, content: string, filename: string): any {
   const require = makeRequireFunction.call(this)
   const dirname = path.dirname(filename)
   // remove shebang
   // eslint-disable-next-line
   const newContent = content.replace(/^\#\!.*/, '')
   const wrapper = Module.wrap(newContent)
   const compiledWrapper = vm.runInContext(wrapper, sandbox, { filename })
   const args = [this.exports, require, this, filename, dirname]
   return compiledWrapper.apply(this.exports, args)
 }
開發者ID:illarionvk,項目名稱:dotfiles,代碼行數:11,代碼來源:factory.ts

示例5: it

    it('does not mock methods from RegExp.prototype (in mock context)', () => {
      const bar = vm.runInContext(
        `
          const bar = /bar/;
          bar;
        `,
        mockContext,
      );

      const barMock = moduleMocker.generateFromMetadata(
        moduleMocker.getMetadata(bar),
      );

      expect(barMock).toBeInstanceOf(mockGlobals.RegExp);
      expect(Object.prototype.hasOwnProperty.call(barMock, 'test')).toBe(false);
      expect(barMock.test).toBe(mockGlobals.RegExp.prototype.test);
    });
開發者ID:Volune,項目名稱:jest,代碼行數:17,代碼來源:index.test.ts

示例6: getCompletions

	// TODO Current approach will not complete paths with . or .. which is very lacking
	getCompletions (input: string, cursor: number): Completions {
		const idxDot = input.lastIndexOf('.', cursor);
		const idxSpc = input.lastIndexOf(' ', cursor);// TODO CAN ACTUALLY BE ANY WHITESPACE, THIS WON'T FLY

		if (idxDot > idxSpc) { // completing property // TODO NOT NECESSARILY, DOT MAY BE PART OF FILE NAME OR DIRECTORY STRUCTURE BUT LET'S IGNORE THAT UNTIL WE HAVE THE TOKENIZER IN PLACE
			const re = /([a-zA-Z\$_]+[\.a-zA-Z0-9\$_\[\]]*)\.([a-zA-Z0-9_\$]*)$/;
			try {
				/* Extract the value we are trying to complete */
				const ex = re.exec(input.substring(0, cursor));
				try {
					var obj = vm.runInContext(ex[1], this.context);
				} catch (e) {
					/* Value to complete threw exception */
					return {completions: [e.toString() + ' completing ' + ex[1] + ' prefix ' + ex[2]], length: -1};
				}
				var prefix = ex[2];
				var comps = Autocompleter.getProperties(obj, prefix);
				if (!comps.length) {
					return {completions: ['No completions for ' + ex[1] + ' starting with ' + prefix], length: -1};
				}
				return {
					completions: comps,
					length: prefix.length,
				};
			} catch (e) {
				return {completions: [e.toString()], length: -1};
			}
		} else if (idxSpc === -1) {
			prefix = input.substring(0, cursor);
			/* If begginning of input, either var or command */
			return {
				completions: this.getCommands(prefix).concat(this.getVars(prefix)),
				length: prefix.length,
			};
		} else {
			prefix = input.substring(idxSpc + 1, cursor);
			// TODO completing file/dir or variable
			// TODO if starting with (, is variable
			// TODO else is file or dir
			return {
				// TODO THIS DOES NOT EVEN COMPLETE PATHS, WHAT A DISGRACE
				completions: this.getFiles(prefix).concat(this.getVars(prefix)),
				length: prefix.length,
			};
		}
	};
開發者ID:bteixeira,項目名稱:nodeshell,代碼行數:47,代碼來源:autocompleter.ts

示例7: 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

示例8: errorToFault

    delete details["remoteAddress"];

    logger.accessInfo(details);
  }
}

Object.defineProperty(context, "Date", { value: SandboxDate });
Object.defineProperty(context, "declare", { value: declare });
Object.defineProperty(context, "clear", { value: clear });
Object.defineProperty(context, "commit", { value: commit });
Object.defineProperty(context, "ext", { value: ext });
Object.defineProperty(context, "log", { value: log });

// Monkey-patch Math.random() to make it deterministic
context.random = random;
vm.runInContext("Math.random = random;", context);
delete context.random;

function errorToFault(err: Error): Fault {
  if (!err) return null;

  if (!err.name) return { code: "script", message: `${err}` };

  const fault: Fault = {
    code: `script.${err.name}`,
    message: err.message,
    detail: {
      name: err.name,
      message: err.message
    }
  };
開發者ID:zaidka,項目名稱:genieacs,代碼行數:31,代碼來源:sandbox.ts

示例9: 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

示例10: getGlobal

function getGlobal(): NodeJS.Global {
  return vm.runInContext('this', vm.createContext());
}
開發者ID:Volune,項目名稱:jest,代碼行數:3,代碼來源:installCommonGlobals.test.ts

示例11: runInContext

export function runInContext(code: string, contextifiedSandbox: any, options: any) {
  const vm = require('vm');
  vm.runInContext(code, contextifiedSandbox, options);
}
開發者ID:franktopel,項目名稱:stencil,代碼行數:4,代碼來源:node-context.ts

示例12: evalIsolated

function evalIsolated(code: string) {
  const es5: string = babel.transform(code).code;
  const sandbox = {};
  vm.createContext(sandbox);
  return vm.runInContext(es5, sandbox);
}
開發者ID:seanchas116,項目名稱:macaron,代碼行數:6,代碼來源:compilerTest.ts


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