本文整理汇总了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);
}
});
示例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);
}
示例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
}
示例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,
});
}
示例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;
}
示例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 = [{}, {}, {}];
示例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];
示例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,
'数值下界',
))
//.........这里部分代码省略.........
示例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) {