Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

static-eval

browserify17mMIT2.1.1TypeScript support: definitely-typed

evaluate statically-analyzable expressions

abstract, analysis, ast, esprima, eval, expression, static, syntax, tree

readme

static-eval

evaluate statically-analyzable expressions

testling badge

build status

security

static-eval is like eval. It is intended for use in build scripts and code transformations, doing some evaluation at build time—it is NOT suitable for handling arbitrary untrusted user input. Malicious user input can execute arbitrary code.

example

var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = process.argv[2];
var ast = parse(src).body[0].expression;

console.log(evaluate(ast));

If you stick to simple expressions, the result is statically analyzable:

$ node '7*8+9'
65
$ node eval.js '[1,2,3+4*5-(5*11)]'
[ 1, 2, -32 ]

but if you use statements, undeclared identifiers, or syntax, the result is no longer statically analyzable and evaluate() returns undefined:

$ node eval.js '1+2+3*n'
undefined
$ node eval.js 'x=5; x*2'
undefined
$ node eval.js '5-4*3'
-7

You can also declare variables and functions to use in the static evaluation:

var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;

console.log(evaluate(ast, {
    n: 6,
    foo: function (x) { return x * 100 },
    obj: { x: { y: 555 } }
}));

methods

var evaluate = require('static-eval');

evaluate(ast, vars={})

Evaluate the esprima-parsed abstract syntax tree object ast with an optional collection of variables vars to use in the static expression resolution.

If the expression contained in ast can't be statically resolved, evaluate() returns undefined.

install

With npm do:

npm install static-eval

license

MIT

changelog

static-eval Change Log

All notable changes to this project will be documented in this file. This project adheres to Semantic Versioning.

2.1.1

  • Update escodegen. @FabianWarnecke in #43

    escodegen doesn't officially support all the Node.js versions that static-eval supports, but so far it still works on them. This has been the case for both v1.x and v2.1.0 of escodegen, so the upgrade doesn't change that situation.

2.1.0

  • Add allowAccessToMethodsOnFunctions option to restore 1.x behaviour so that cwise can upgrade. (@archmoj in #31)

    Do not use this option if you are not sure that you need it, as it had previously been removed for security reasons. There is a known exploit to execute arbitrary code. Only use it on trusted inputs, like the developer's JS files in a build system.

2.0.5

  • Fix function bodies being invoked during declaration. (@RoboPhred in #30)

2.0.4

  • Short-circuit evaluation in && and || expressions. (@RoboPhred in #28)
  • Start tracking changes.