-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvm.js
55 lines (47 loc) · 1.35 KB
/
vm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const vm = require('vm');
const RUN_OPTIONS = { timeout: 5000, displayErrors: false };
const CONTEXT_OPTIONS = { microtaskMode: 'afterEvaluate' };
const USE_STRICT = `'use strict';\n`;
const EMPTY_CONTEXT = vm.createContext(Object.freeze({}));
const COMMON_CONTEXT = vm.createContext(
Object.freeze({
Buffer,
URL,
URLSearchParams,
TextDecoder,
TextEncoder,
console,
queueMicrotask,
setTimeout,
setImmediate,
setInterval,
clearTimeout,
clearImmediate,
clearInterval,
})
);
const createContext = (context, preventEscape = false) => {
if (!context) return EMPTY_CONTEXT;
return vm.createContext(context, preventEscape ? CONTEXT_OPTIONS : {});
};
class MetaScript {
constructor(name, src, options = {}) {
const strict = src.startsWith(USE_STRICT);
const code = strict ? src : USE_STRICT + src;
const lineOffset = strict ? 0 : -1;
this.name = name;
const scriptOptions = { filename: name, ...options, lineOffset };
this.script = new vm.Script(code, scriptOptions);
this.context = options.context || createContext();
this.exports = this.script.runInContext(this.context, RUN_OPTIONS);
}
}
const createScript = (name, src, options) => new MetaScript(name, src, options);
module.exports = {
createContext,
MetaScript,
createScript,
EMPTY_CONTEXT,
COMMON_CONTEXT,
};