forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval.ts
More file actions
76 lines (66 loc) · 1.66 KB
/
eval.ts
File metadata and controls
76 lines (66 loc) · 1.66 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// @flow
import buildProcess from './utils/process';
const g = typeof window === 'undefined' ? self : window;
const requestFrame = (() => {
const raf =
g.requestAnimationFrame ||
// @ts-ignore
g.mozRequestAnimationFrame ||
g.webkitRequestAnimationFrame ||
function(fn) {
return g.setTimeout(fn, 20);
};
return function(fn) {
return raf(fn);
};
})();
const hasGlobalDeclaration = /^const global/m;
/* eslint-disable no-unused-vars */
export default function(
code: string,
require: Function,
module: { exports: any },
env: Object = {},
globals: Object = {},
{ asUMD = false }: { asUMD?: boolean } = {}
) {
const { exports } = module;
const global = g;
const process = buildProcess(env);
// @ts-ignore
g.global = global;
const allGlobals = {
require,
module,
exports,
process,
setImmediate: requestFrame,
global,
...globals,
};
if (asUMD) {
delete allGlobals.module;
delete allGlobals.exports;
delete allGlobals.global;
}
if (hasGlobalDeclaration.test(code)) {
delete allGlobals.global;
}
const allGlobalKeys = Object.keys(allGlobals);
const globalsCode = allGlobalKeys.length ? allGlobalKeys.join(', ') : '';
const globalsValues = allGlobalKeys.map(k => allGlobals[k]);
try {
const newCode = `(function evaluate(` + globalsCode + `) {` + code + `\n})`;
// eslint-disable-next-line no-eval
(0, eval)(newCode).apply(this, globalsValues);
return module.exports;
} catch (e) {
let error = e;
if (typeof e === 'string') {
error = new Error(e);
}
error.isEvalError = true;
throw error;
}
}
/* eslint-enable no-unused-vars */