• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript vm.runInNewContext函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中vm.runInNewContext函数的典型用法代码示例。如果您正苦于以下问题:TypeScript runInNewContext函数的具体用法?TypeScript runInNewContext怎么用?TypeScript runInNewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了runInNewContext函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1:

(function () {
    var sandbox = { expTypeScript: null };

    var typescriptmodulefile = require.resolve("typescript");
    var location = path.dirname(typescriptmodulefile);
	var tmp = module.exports._libdPath = require.resolve(location + '/lib.d.ts');
	
    var contents = [
        "(function() {",
        fs.readFileSync(typescriptmodulefile, "utf8"),
        "expTypeScript = TypeScript;",
        "}).call({});"
    ].join("");

    vm.runInNewContext(contents, sandbox, 'ts.vm');

    var TypeScript = module.exports.TypeScript = sandbox.expTypeScript;
    TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous;
})();
开发者ID:KostyaSumf,项目名称:jFarm,代码行数:19,代码来源:wrapper.ts


示例2: Error

		b.bundle((err, src) => {
			if (err) {
				throw new Error("failed to bundle!");
			}
			vm.runInNewContext(src.toString(), {
				test: t.test.bind(t),
				Buffer,
				Int8Array,
				Int16Array,
				Int32Array,
				Float32Array,
				Float64Array,
				Uint8Array,
				Uint16Array,
				Uint32Array,
				Uint8ClampedArray,
				console: { log: console.log.bind(console) }
			});
			t.end();
		});
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:20,代码来源:cwise-tests.ts


示例3: test

test('bundleNextModule should bundle a virtual empty module per external falsy configuration', t => {
  const modules: any[] = [];
  const plugins = {};
  const globals = {
    global: false,
    process: false,
    buffer: false
  };
  const host = new HostMock({});

  enqueueModule('fs');
  bundleNextModule(modules, { config: { externals: { fs: false } } as any, host }, globals, plugins);

  const sandbox = {
    module: {
      exports: {
      }
    }
  };
  runInNewContext(generate(modules[0]) + '_0(module, module.exports);', sandbox);
  t.deepEqual(sandbox.module.exports, {});
});
开发者ID:ZauberNerd,项目名称:paeckchen,代码行数:22,代码来源:modules-test.ts


示例4:

        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 = [{}, {}, {}];

        const script = new vm.Script('globalVar = "set"');

        sandboxes.forEach((sandbox) => {
            script.runInNewContext(sandbox);
            script.runInThisContext();
        });

        console.log(util.inspect(sandboxes));
开发者ID:Crevil,项目名称:DefinitelyTyped,代码行数:30,代码来源:node-tests.ts


示例5: beforeEach

 beforeEach(() => {
   mockContext = vm.createContext();
   mockGlobals = vm.runInNewContext('this', mockContext);
   moduleMocker = new ModuleMocker(mockGlobals);
 });
开发者ID:Volune,项目名称:jest,代码行数:5,代码来源:index.test.ts


示例6: visitDQSTRING

	visitDQSTRING(dqstring: DescentParserNode, streams: Stream[], callback: executionCallback): void {
		const value = vm.runInNewContext(dqstring.token.text);
		callback(value);
	}
开发者ID:bteixeira,项目名称:nodeshell,代码行数:4,代码来源:executerVisitor.ts


示例7: it

 it('should be able to encode Arrays across stack frames', function() {
   assert.equal(
     vm.runInNewContext("RLP.encode(['dog', 'god', 'cat']).toString('hex')", { RLP }),
     'cc83646f6783676f6483636174',
   )
 })
开发者ID:ethereumjs,项目名称:rlp,代码行数:6,代码来源:integration.spec.ts


示例8: field

export const evaluate = (connection: SendableConnection, message: NewEvalMessage, onDispose: () => void, fork?: ForkProvider): ActiveEvaluation | void => {
	/**
	 * Send the response and call onDispose.
	 */
	// tslint:disable-next-line no-any
	const sendResp = (resp: any): void => {
		logger.trace(() => [
			"resolve",
			field("id", message.getId()),
			field("response", stringify(resp)),
		]);

		const evalDone = new EvalDoneMessage();
		evalDone.setId(message.getId());
		evalDone.setResponse(stringify(resp));

		const serverMsg = new ServerMessage();
		serverMsg.setEvalDone(evalDone);
		connection.send(serverMsg.serializeBinary());

		onDispose();
	};

	/**
	 * Send an exception and call onDispose.
	 */
	const sendException = (error: Error): void => {
		logger.trace(() => [
			"reject",
			field("id", message.getId()),
			field("response", stringify(error, true)),
		]);

		const evalFailed = new EvalFailedMessage();
		evalFailed.setId(message.getId());
		evalFailed.setResponse(stringify(error, true));

		const serverMsg = new ServerMessage();
		serverMsg.setEvalFailed(evalFailed);
		connection.send(serverMsg.serializeBinary());

		onDispose();
	};

	let eventEmitter = message.getActive() ? new EventEmitter(): undefined;
	const sandbox = {
		helper: eventEmitter ? new ServerActiveEvalHelper({
			removeAllListeners: (event?: string): void => {
				eventEmitter!.removeAllListeners(event);
			},
			// tslint:disable no-any
			on: (event: string, cb: (...args: any[]) => void): void => {
				eventEmitter!.on(event, (...args: any[]) => {
					logger.trace(() => [
						`${event}`,
						field("id", message.getId()),
						field("args", args.map((a) => stringify(a))),
					]);
					cb(...args);
				});
			},
			emit: (event: string, ...args: any[]): void => {
				logger.trace(() => [
					`emit ${event}`,
					field("id", message.getId()),
					field("args", args.map((a) => stringify(a))),
				]);
				const eventMsg = new EvalEventMessage();
				eventMsg.setEvent(event);
				eventMsg.setArgsList(args.map((a) => stringify(a)));
				eventMsg.setId(message.getId());
				const serverMsg = new ServerMessage();
				serverMsg.setEvalEvent(eventMsg);
				connection.send(serverMsg.serializeBinary());
			},
			// tslint:enable no-any
		}, fork || cpFork) : new EvalHelper(),
		_Buffer: Buffer,
		// When the client is ran from Webpack, it will replace
		// __non_webpack_require__ with require, which we then need to provide to
		// the sandbox. Since the server might also be using Webpack, we need to set
		// it to the non-Webpack version when that's the case. Then we need to also
		// provide __non_webpack_require__ for when the client doesn't run through
		// Webpack meaning it doesn't get replaced with require (Jest for example).
		require: typeof __non_webpack_require__ !== "undefined" ? __non_webpack_require__ : require,
		__non_webpack_require__: typeof __non_webpack_require__ !== "undefined" ? __non_webpack_require__ : require,
		setTimeout,
		setInterval,
		clearTimeout,
		process: {
			env: process.env,
		},
		args: message.getArgsList().map(parse),
	};

	let value: any; // tslint:disable-line no-any
	try {
		const code = `(${message.getFunction()})(helper, ...args);`;
		value = vm.runInNewContext(code, sandbox, {
			// If the code takes longer than this to return, it is killed and throws.
//.........这里部分代码省略.........
开发者ID:AhmadAlyTanany,项目名称:code-server,代码行数:101,代码来源:evaluate.ts


示例9: initializeTests

    public initializeTests() {
        switch (this.testType) {
            case UnittestTestType.Compiler:
                this.tests = this.enumerateFiles('tests/cases/unittests/compiler');
                break;
            case UnittestTestType.LanguageService:
                this.tests = this.enumerateFiles('tests/cases/unittests/ls');
                break;
            case UnittestTestType.Services:
                this.tests = this.enumerateFiles('tests/cases/unittests/services');
                break;
            case UnittestTestType.Harness:
                this.tests = this.enumerateFiles('tests/cases/unittests/harness');
                break;
            case UnittestTestType.Samples:
                this.tests = this.enumerateFiles('tests/cases/unittests/samples');
                break;
            default:
                if (this.tests.length === 0) {
                    throw new Error('Unsupported test cases: ' + this.testType);
                }
                break;
        }

        var outfile = new Harness.Compiler.WriterAggregator()
        var outerr = new Harness.Compiler.WriterAggregator();
        var harnessCompiler = Harness.Compiler.getCompiler(Harness.Compiler.CompilerInstance.DesignTime);

        var toBeAdded = this.tests.map(test => {
            return { unitName: test, content: TypeScript.IO.readFile(test, /*codepage:*/ null).contents }
        });
        harnessCompiler.addInputFiles(toBeAdded);
        harnessCompiler.compile({ noResolve: true });
        
        var stdout = new Harness.Compiler.EmitterIOHost();
        var emitDiagnostics = harnessCompiler.emitAll(stdout);
        var results = stdout.toArray();
        var lines: string[] = [];
        results.forEach(v => lines = lines.concat(v.file.lines));
        var code = lines.join("\n")

        describe("Setup compiler for compiler unittests", () => {
            Harness.Compiler.recreate(Harness.Compiler.CompilerInstance.RunTime, { useMinimalDefaultLib: this.testType !== UnittestTestType.Samples, noImplicitAny: false });
        });
        
        if (typeof require !== "undefined") {
            var vm = require('vm');
            vm.runInNewContext(code,
                {
                    require: require,
                    TypeScript: TypeScript,
                    process: process,
                    describe: describe,
                    it: it,
                    assert: Harness.Assert,
                    Harness: Harness,
                    IO: TypeScript.IO,
                    Exec: Exec,
                    Services: TypeScript.Services,
                    // Formatting: Formatting,
                    Diff: Diff,
                    FourSlash: FourSlash
                },
                "generated_test_code.js"
            );
        } else {
            eval(code);
        }

        // make sure the next unittestrunner doesn't include the previous one's stuff
        Harness.Compiler.recreate(Harness.Compiler.CompilerInstance.DesignTime);
    }
开发者ID:Anupinky,项目名称:typescript,代码行数:72,代码来源:unittestrunner.ts


示例10: executeFixComments

function executeFixComments(input: string, files: any = {}, settings: any = {}): any {
  const processed = fixComments(input, files);
  const result = {};
  runInNewContext(processed, result);
  return result;
}
开发者ID:ZauberNerd,项目名称:paeckchen,代码行数:6,代码来源:ast-fixes-test.ts



注:本文中的vm.runInNewContext函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript vm.runInThisContext函数代码示例发布时间:2022-05-25
下一篇:
TypeScript vm.runInContext函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap