本文整理匯總了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);
}
示例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` */
}
}
示例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,
});
}
示例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)
}
示例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);
});
示例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,
};
}
};
示例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;
}
示例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
}
};
示例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,
'數值下界',
))
//.........這裏部分代碼省略.........
示例10: getGlobal
function getGlobal(): NodeJS.Global {
return vm.runInContext('this', vm.createContext());
}
示例11: runInContext
export function runInContext(code: string, contextifiedSandbox: any, options: any) {
const vm = require('vm');
vm.runInContext(code, contextifiedSandbox, options);
}
示例12: evalIsolated
function evalIsolated(code: string) {
const es5: string = babel.transform(code).code;
const sandbox = {};
vm.createContext(sandbox);
return vm.runInContext(es5, sandbox);
}