Gathering detailed insights and metrics for eval-estree-expression
Gathering detailed insights and metrics for eval-estree-expression
Gathering detailed insights and metrics for eval-estree-expression
Gathering detailed insights and metrics for eval-estree-expression
jse-eval
JavaScript expression parsing and evaluation.
whence
Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful for evaluating expressions in config files, prompts, key bindings, completions, templates, and many other user cases.
@zvenigora/jse-eval
JavaScript expression parsing and evaluation.
@ibyar/expressions
Aurora expression, an template expression and evaluation, An 100% spec compliant ES2022 JavaScript toolchain,
Safely evaluate JavaScript (estree) expressions, sync and async.
npm install eval-estree-expression
Typescript
Module System
Node Version
NPM Version
JavaScript (100%)
Total Downloads
3,743,653
Last Day
16,588
Last Week
79,820
Last Month
329,248
Last Year
2,821,504
MIT License
56 Stars
49 Commits
5 Forks
4 Watchers
1 Branches
3 Contributors
Updated on Apr 19, 2025
Minified
Minified + Gzipped
Latest Version
3.0.0
Package Id
eval-estree-expression@3.0.0
Unpacked Size
47.92 kB
Size
10.91 kB
File Count
11
NPM Version
10.9.2
Node Version
22.13.0
Published on
Apr 19, 2025
Cumulative downloads
Total Downloads
Last Day
56.8%
16,588
Compared to previous day
Last Week
7.5%
79,820
Compared to previous week
Last Month
1%
329,248
Compared to previous month
Last Year
226.6%
2,821,504
Compared to previous year
Safely evaluate JavaScript (estree) expressions, sync and async.
Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your :heart: and support.
(TOC generated by verb using markdown-toc)
Install with npm:
1$ npm install --save eval-estree-expression
Requires Node.js version 14 or greater.
Evaluates an estree expression from [@babel/parser][], esprima, acorn, or any other library that parses and returns a valid estree
expression.
1const { evaluate } = require('eval-estree-expression'); 2// or 3import { evaluate } from 'eval-estree-expression'; 4 5evaluate.sync(expressionTree[, context]); // sync 6evaluate(expressionTree[, context]).then(console.log); // async
See the unit tests for hundreds of additional usage examples.
Params
The evaluate
function takes the following arguments:
expressionTree
{object} - a valid estree expression AST.context
{object} - a data object with values to replace variables in expressionsMost of the examples in this document assume the following setup code is used:
1const { evaluate } = require('eval-estree-expression'); 2const { parseExpression } = require('@babel/parser'); 3 4// parse your JavaScript expression 5const ast = parseExpression('1 + 2'); 6 7// evaluate synchronously 8console.log(evaluate.sync(ast)); //=> 3 9 10// or asynchronously 11console.log(await evaluate(ast)); //=> 3
[Esprima][esprimar] doesn't have a "parseExpression" method like @babel/parser, so you'll need to return the expression from the AST, like so:
1const { parse } = require('esprima'); 2const { evaluate } = require('eval-estree-expression'); 3const ast = parse('[1, 2, 3].map(n => n * x);').body[0].expression; 4 5// evaluate synchronously 6console.log(evaluate.sync(ast)); // => [2, 4, 6] 7 8// or asynchronously 9console.log(await evaluate(ast)); // => [2, 4, 6]
Evaluate expressions asynchronously.
1console.log(await evaluate(parse('1 + 2'))); //=> 3 2console.log(await evaluate(parse('5 * 2'))); //=> 10 3console.log(await evaluate(parse('1 > 2'))); //=> false 4console.log(await evaluate(parse('1 < 2'))); //=> true 5 6// with context object 7console.log(await evaluate(parse('page.title === "home"'), { page: { title: 'home' } })); //=> true
Evaluate expressions synchronously.
1console.log(evaluate.sync(parse('1 + 2'))); //=> 3 2console.log(evaluate.sync(parse('5 * 2'))); //=> 10 3console.log(evaluate.sync(parse('1 > 2'))); //=> false 4console.log(evaluate.sync(parse('1 < 2'))); //=> true 5 6// with context object 7console.log(evaluate.sync(parse('page.title === "home"'), { page: { title: 'home' } })); //=> true
Get an array of variables from an expression:
1const { parseExpression } = require('@babel/parser'); 2const { variables } = require('eval-estree-expression'); 3 4console.log(variables(parseExpression('x * (y * 3) + z.y.x'))); //=> ['x', 'y', 'z'] 5console.log(variables(parseExpression('(a || b) ? c + d : e * f'))); //=> ['a', 'b', 'c', 'd', 'e', 'f'] 6
Type: boolean
Default: undefined
Force logical operators to return a boolean result.
1console.log(await evaluate(parse('a && b'), { a: undefined, b: true })); //=> undefined 2console.log(await evaluate(parse('a && b'), { a: undefined, b: false })); //=> undefined 3console.log(await evaluate(parse('a || b'), { a: false, b: null })); //=> null 4console.log(await evaluate(parse('a || b'), { a: false, b: undefined })); //=> undefined 5 6// 7// With booleanLogicalOperators enabled 8// 9 10const options = { 11 booleanLogicalOperators: true 12}; 13 14console.log(await evaluate(parse('a || b'), { a: false, b: null }, options)); //=> false 15console.log(await evaluate(parse('a && b'), { a: undefined, b: true }, options)); //=> false 16console.log(await evaluate(parse('a && b'), { a: undefined, b: false }, options)); //=> false 17console.log(await evaluate(parse('a || b'), { a: false, b: undefined }, options)); //=> false
Type: boolean
Default: false
Allow function calls to be evaluated. This is unsafe, please enable this option at your own risk.
Example
1const { parse } = require('esprima'); 2const { generate } = require('escodegen'); 3const { evaluate } = require('eval-estree-expression'); 4 5const options = { 6 functions: true 7}; 8 9// works with native methods 10console.log(evaluate.sync(parse('/([a-z]+)/.exec(" foo ")'), { x: 2 }, options)); 11//=> [ 'foo', 'foo', index: 1, input: ' foo ', groups: undefined ] 12 13// and functions defined on the context 14console.log(evaluate.sync('a.upper("b")', { a: { upper: v => v.toUpperCase() } }, options)); 15//=> 'B'
However, this does NOT support function expressions or function statements. To enable function statements and expressions (not just function calls) to be evaluated, you must also use the generate option.
To use top-level await
with, you need to:
functions
allowAwaitOutsideFunction
. This option is passed directly to the babel parser.1const { evaluate } = require('eval-estree-expression'); 2const { parseExpression } = require('@babel/parser'); 3 4const opts = { functions: true, allowAwaitOutsideFunction: true }; 5 6const e = (input, ctx, options) => { 7 return evaluate(parseExpression(input, options), ctx, options); 8}; 9 10const run = async () => { 11 console.log(await e('await 1', {}, opts)); //=> 1 12 console.log(await e('Promise.resolve(1)', { Promise }, opts)); //=> 1 13 console.log(await e('await Promise.resolve(1)', { Promise }, opts)); //=> 1 14}; 15 16run();
Type: boolean
Default: undefined
Enable support for function statements and expressions by enabling the functions option AND by passing the .generate()
function from the escodegen library.
Example
1const escodegen = require('escodegen'); 2const { parse } = require('esprima'); 3const { evaluate } = require('eval-estree-expression'); 4 5const options = { 6 functions: true, 7 generate: escodegen.generate 8}; 9 10console.log(await evaluate(parse('[1, 2, 3].map(n => n * x);'), { x: 2 }, options)); // => [2, 4, 6]
Type: boolean
Default: true
Enable the =~
regex operator to support testing values without using functions (example name =~ /^a.*c$/
).
Why is this needed?
In expressions, if you wish to test a value using a regular expression, you have two options:
.test()
and .match()
, orIn other words, instead of having to do this:
1console.log(evaluate.sync(parse('/^ab+c$/ig.test("abbbbbc")'), {}, { functions: true }));
You can do this:
1console.log(evaluate.sync(parse('name =~ /^a.*c$/'), { name: 'abc' })); 2console.log(evaluate.sync(parse('name =~ regex'), { name: 'abc', regex: /^a.*c$/ }));
Type: boolean
Default: false
Throw an error when variables are undefined.
Type: boolean
Default: undefined
Used with the variables method to return nested variables (e.g., variables with dot notation, like foo.bar.baz
).
Supports all JavaScript operators with the exception of assignment operators (=
, +=
, etc):
1// Arithmetic operators 2evaluate('a + b'); 3evaluate('a - b'); 4evaluate('a / b'); 5evaluate('a * b'); 6evaluate('a % b'); 7evaluate('a ** b'); 8 9// Relational operators 10evaluate('a instanceof b'); 11evaluate('a < b'); 12evaluate('a > b'); 13evaluate('a <= b'); 14evaluate('a >= b'); 15 16// Equality operators 17evaluate('a !== b'); 18evaluate('a === b'); 19evaluate('a != b'); 20evaluate('a == b'); 21 22// Bitwise shift operators 23evaluate('a << b'); 24evaluate('a >> b'); 25evaluate('a >>> b'); 26 27// Binary bitwise operators 28evaluate('a & b'); 29evaluate('a | b'); 30evaluate('a ^ b'); 31 32// Binary logical operators 33evaluate('a && b'); // Logical AND. 34evaluate('a || b'); // Logical OR. 35evaluate('a ?? b'); // Nullish Coalescing Operator.
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
1$ npm install && npm test
(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)
To generate the readme, run the following command:
1$ npm install -g verbose/verb#dev verb-generate-readme && verb
You might also be interested in these projects:
whence: Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful… more | homepage
Commits | Contributor |
---|---|
45 | jonschlinkert |
1 | 6utt3rfly |
1 | freshgum-bubbles |
Jon Schlinkert
Copyright © 2025, Jon Schlinkert. Released under the MIT License.
This file was generated by verb-generate-readme, v0.8.0, on April 19, 2025.
No vulnerabilities found.
No security vulnerabilities found.