Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

74 Commits

Repository files navigation

es-eval

Evaluate JavaScript expressions safely. No more being afraid of what the users enter!

🎲 Playground (pre-release version)

Installation

npm i es-eval

Usage

// Simple expressionconstesEval=require('es-eval');constresult=esEval('1 + 2');console.log(result);// Output: 3
// User valuesconstesEval=require('es-eval');constresult=esEval('1 + x',{x: 4});console.log(result);// Output: 5

Or more complex examples:

// IIFE exampleconstesEval=require('es-eval');constexp=`(() => { const out = []; const callback = () => { out.push('callback() called'); }; const main = function (param, cb) { out.push('main() started with param = "' + param + '"'); cb(); out.push('main() finished'); }; main('My value', callback); return out;})()`;console.log(esEval(exp));// Output: [// 'main() called with My value',// 'Callback called!',// 'main() finished'// ]
// Hangup protection in infinite loopconstesEval=require('es-eval');try{esEval(`(() => { while (true) {} })()`);}catch(err){console.log(err.message);// Output: 'Evaluation timeout'}

Features

FeatureNotes
Hangup protectionThe execution of any user inputs is protected against intentional or unintentional hangups. Since it is mathematically proven that the halting problem is undecidable, hence it cannot be automatically computed, this protection is based on a configurable timeout.
Primitive valuesnumber, string, boolean and undefined values.
Objects{ key: 'value' }, null, built-in static methods: Object.entries(), Object.keys(), Object.values()
Arrays[1, 2, 3], built-in properties and methods: length, push, pop, shift, ushift, slice, splice, forEach, map, filter, reduce, includes
Arrow function expressions(x, y) => x + y
Standard function expressionsfunction () { return 'value'; }
Closures
Nested expressions(a < (b + 1) && a - (a < ([1, 2].map(x => 1 + x)).length))
Callbackscb => { cb(); return 1; }
Mathematical operations+, -, /, *, %, **
Comparators===, !==, ==, !=, <, >, <=, >=
Logical operations&&, ||, !
Bitwise operations&, |, ^
Ternary operator... ? ... : ...
Nullish operator??
Variablesconst and let declarations. Assignments.
Conditionalif...else statement.
Loopswhile and for...of statements.
JSONJSON.parse() and JSON.stringify().
MathMath.random(), Math.min(), Math.max(), Math.floor(), Math.ceil() and Math.round().
Spread operator (...)Spread syntax for arrays, objects, and parameters.
Global functionsparseFloat, parseInt, isNaN and isFinite.

Coming soon...

StatusFeatureNotes
😓 In Progressglobal thisReference to the global object.
😓 In ProgressArray.isArray()Determines whether the passed value is an Array.
😓 In Progress+= operatorAddition assignment.
⏳ To-DoArray.from()Creates a copy of an iterable or array-like object.
⏳ To-DoArray.of()Creates an array from the arguments.
⏳ To-DoBlock evaluationRun a block code and return the block context variables with the values at the end of the execution.

Future features

📨 Vote what's coming on! 💡 or Suggest your ideas.

FeatureNotes
Browser support
for in loop
for (;;) loop
do ... while loop
Destructuring
And a lot more!...

How it works?

  • It never executes user code passing it to JS engine (no eval(), no new Function(...), no vm, no other third party engines), making sure the evaluation is safe.
  • No access to require/import modules.
  • No access to OS features like file system, network, etc.
  • No access to global objects.
  • All user code is parsed to an AST and analyzed step by step, representing the code statements and functions in own components. No native functions are created with the user input.
  • All access to global objects is emulated and there's no real access to natives.
  • Standard ECMAScript features are implemented and not delegated to the underlying engine.

What is this for

✅ Evaluate user input expressions safely

✅ Easily provide a way to enter and evaluate custom conditions

✅ Embed JS expressions in template engines

✅ Parse custom JS functions once and evaluate them many times

✅ Create expressions with context values, including objects and arrays

What is this NOT for

⛔ Create entire applications

⛔ Replace V8, or other JS engines

About

Run JavaScript safely

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages