本文整理汇总了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;未经允许,请勿转载。 |
请发表评论