-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathindex.js
More file actions
26 lines (25 loc) · 772 Bytes
/
index.js
File metadata and controls
26 lines (25 loc) · 772 Bytes
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
var vm = require('vm')
module.exports = function safeEval (code, context, opts) {
var sandbox = {}
var resultKey = 'SAFE_EVAL_' + Math.floor(Math.random() * 1000000)
sandbox[resultKey] = {}
var clearContext = `
(function() {
Function = undefined;
const keys = Object.getOwnPropertyNames(this).concat(['constructor']);
keys.forEach((key) => {
const item = this[key];
if (!item || typeof item.constructor !== 'function') return;
this[key].constructor = undefined;
});
})();
`
code = clearContext + resultKey + '=' + code
if (context) {
Object.keys(context).forEach(function (key) {
sandbox[key] = context[key]
})
}
vm.runInNewContext(code, sandbox, opts)
return sandbox[resultKey]
}