Created
May 17, 2017 22:42
-
-
Save amasad/613396f7ae640832685ec9a783f37984 to your computer and use it in GitHub Desktop.
a project repl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const babel = require('babel-core'); | |
const vm = require('vm'); | |
const repl = require('repl'); | |
let context = repl.start({ eval: evaluate }).context; | |
// Autorequire all models so that they're available by name in the repl. | |
const models = require('../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 => { | |
context[RESULT_SYMBOL] = r; | |
if (assign) { | |
simpleEval(assign + ' = ' + RESULT_SYMBOL, context, filename, callback); | |
} else { | |
callback(null, 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment