-
Notifications
You must be signed in to change notification settings - Fork 0
/
sandbox.js
47 lines (41 loc) · 1.01 KB
/
sandbox.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
/**
* @param {String} code - Javascript code string
* @returns {Function} - The function that can be executed after compilation
* */
function compile(code) {
const securityCode = `with (context) {
function execute() {
"use strict";
${code}
}
return execute()
}`
/** generate an executable function that has a parameter named context */
const fn = new Function('context', securityCode)
return function (context) {
/** As running context */
const contextProxy = new Proxy(context, {
has() {
return true
},
get(target, key) {
if (key === Symbol.unscopables) return undefined
return target[key]
},
})
return fn(contextProxy)
}
}
/**
* @param {String} code - Javascript code string
* @param {Object} data - Data that can be accessed during code execution。
* @returns {*}
* */
function sandbox (code, data = {}) {
try {
return compile(code)({ ...data })
} catch (e) {
console.log(e)
}
}
export default sandbox