-
Notifications
You must be signed in to change notification settings - Fork 1
/
repl.js
76 lines (60 loc) · 1.38 KB
/
repl.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*jshint esversion: 6 */
const babel = require('babel-core'),
vm = require('vm'),
repl = require('repl');
let context = repl.start({ eval: evaluate}).context;
const models = require('src/server/models');
for (let name in models) {
context[name] = models[name];
}
const RESULT_SYMBOL = '__eval_res';
function evaluate (cmd, context, filename, callback) {
context = vm.createContext(context);
if (cmd.match(/await/)) {
let assign = null;
if (cmd.match(/\=/)) {
let parts = cmd.split('=');
assign = parts[0];
cmd = parts.slice(1).join('=');
}
cmd = '(async function() { return ' + cmd + '})()';
try {
cmd = compile(cmd);
} catch (e) {
callback(new repl.Recoverable());
return;
}
let res;
try {
res = vm.runInContext(cmd, context);
} catch (e) {
callback(e);
return;
}
res.then(r => {
},
(e) => callback(e));
return;
}
simpleEval(cmd, context, filename, callback);
}
function simpleEval (cmd, context, filename, callback) {
try {
cmd = compile(cmd);
} catch (e) {
callback(new repl.Recoverable());
return;
}
try {
callback(null, vm.runInContext(cmd, context));
} catch (e) {
callback(e);
return;
}
}
function compile (cmd) {
return babel.transform(cmd, {
sourceType: 'script',
blacklist: ['strict'],
}).code;
}