Debian Codegraph @

readme.markdown

raw
1 # static-eval
2
3 evaluate statically-analyzable expressions
4
5 [![testling badge](https://ci.testling.com/substack/static-eval.png)](https://ci.testling.com/substack/static-eval)
6
7 [![build status](https://secure.travis-ci.org/browserify/static-eval.png)](http://travis-ci.org/browserify/static-eval)
8
9 # security
10
11 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.
12
13 # example
14
15 ``` js
16 var evaluate = require('static-eval');
17 var parse = require('esprima').parse;
18
19 var src = process.argv[2];
20 var ast = parse(src).body[0].expression;
21
22 console.log(evaluate(ast));
23 ```
24
25 If you stick to simple expressions, the result is statically analyzable:
26
27 ```
28 $ node '7*8+9'
29 65
30 $ node eval.js '[1,2,3+4*5-(5*11)]'
31 [ 1, 2, -32 ]
32 ```
33
34 but if you use statements, undeclared identifiers, or syntax, the result is no
35 longer statically analyzable and `evaluate()` returns `undefined`:
36
37 ```
38 $ node eval.js '1+2+3*n'
39 undefined
40 $ node eval.js 'x=5; x*2'
41 undefined
42 $ node eval.js '5-4*3'
43 -7
44 ```
45
46 You can also declare variables and functions to use in the static evaluation:
47
48 ``` js
49 var evaluate = require('static-eval');
50 var parse = require('esprima').parse;
51
52 var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
53 var ast = parse(src).body[0].expression;
54
55 console.log(evaluate(ast, {
56 n: 6,
57 foo: function (x) { return x * 100 },
58 obj: { x: { y: 555 } }
59 }));
60 ```
61
62 # methods
63
64 ``` js
65 var evaluate = require('static-eval');
66 ```
67
68 ## evaluate(ast, vars={})
69
70 Evaluate the [esprima](https://npmjs.org/package/esprima)-parsed abstract syntax
71 tree object `ast` with an optional collection of variables `vars` to use in the
72 static expression resolution.
73
74 If the expression contained in `ast` can't be statically resolved, `evaluate()`
75 returns undefined.
76
77 # install
78
79 With [npm](https://npmjs.org) do:
80
81 ```
82 npm install static-eval
83 ```
84
85 # license
86
87 MIT