all files / src/modules/ sandbox.js

89.47% Statements 17/19
100% Branches 0/0
66.67% Functions 2/3
93.75% Lines 15/16
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                      13×            
// A safe alternative to JS's eval
import vm from 'vm';
import _ from 'underscore';
import * as colors from './colors';
 
// Objects exposed here should be treated like a public API
// if `underscore` had backwards incompatible changes in a future release, we'd
// have to be careful about bumping the library as those changes could break user charts
const GLOBAL_CONTEXT = {
  console,
  _,
  colors,
};
 
// Copied/modified from https://github.com/hacksparrow/safe-eval/blob/master/index.js
export default function sandboxedEval(code, context, opts) {
  const sandbox = {};
  const resultKey = 'SAFE_EVAL_' + Math.floor(Math.random() * 1000000);
  sandbox[resultKey] = {};
  const codeToEval = resultKey + '=' + code;
  const sandboxContext = { ...GLOBAL_CONTEXT, ...context };
  Object.keys(sandboxContext).forEach(function (key) {
    sandbox[key] = sandboxContext[key];
  });
  try {
    vm.runInNewContext(codeToEval, sandbox, opts);
    return sandbox[resultKey];
  } catch (error) {
    return () => error;
  }
}