Registry / serialization / eval-estree-expression

eval-estree-expression

JSON →
library3.0.1jsnpmunverified

eval-estree-expression is a JavaScript library designed for the safe, synchronous, and asynchronous evaluation of ESTree-compliant Abstract Syntax Trees (ASTs). It is currently at version 3.0.1, with development active and a 4.0.0-beta release available, indicating a steady release cadence. This package differentiates itself by focusing specifically on expressions, avoiding the inherent dangers of direct `eval()` usage by operating on ASTs from parsers like `@babel/parser`, `esprima`, or `acorn`. It provides a controlled environment, requiring explicit context for variables and offering options to enable potentially unsafe features like arbitrary function calls with caution. The library strictly operates on Node.js version 14 or greater and does not support JavaScript statements or assignment operators by default, ensuring a higher degree of security when evaluating untrusted expressions compared to general-purpose JavaScript evaluators. Its design choice to work with ASTs makes it a robust alternative to libraries like `expr-eval` which have faced critical remote code execution vulnerabilities due to insufficient validation of evaluation contexts.

npm install eval-estree-expression
INSTALL
IMPORT
SIG · EVAL-ESTREE-EXPRES
E
eval-estree-expression
serializationjavascriptv3.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

evaluate
import { evaluate } from 'eval-estree-expression';
const { evaluate } = require('eval-estree-expression');
While CommonJS `require` is still supported, ESM `import` is the preferred and more modern approach for Node.js 14+ environments. The `evaluate` function itself returns a Promise for asynchronous evaluation.
evaluate.sync
import { evaluate } from 'eval-estree-expression'; const result = evaluate.sync(ast, context);
The synchronous evaluation method is a property of the main `evaluate` export. No separate named export exists for `evaluate.sync`.
parseExpression (from @babel/parser)
import { parseExpression } from '@babel/parser';
import { parse } from '@babel/parser'; // parseExpression is typically more suitable for expressions than general `parse`
`eval-estree-expression` consumes ASTs, it does not parse strings itself. You need an external parser like `@babel/parser` to convert expression strings into an AST first.

Demonstrates parsing a JavaScript expression string using `@babel/parser` and then evaluating it both synchronously and asynchronously with `eval-estree-expression`, providing a custom context object. It also highlights the flexibility of changing context for different evaluations.

import { evaluate } from 'eval-estree-expression'; import { parseExpression } from '@babel/parser'; async function runEvaluation() { const expressionString = 'user.age > 18 && user.status === "active" ? "Eligible" : "Not Eligible"'; const context = { user: { name: 'Alice', age: 25, status: 'active' } }; try { // Parse the expression string into an ESTree AST const ast = parseExpression(expressionString, { sourceType: 'script', // or 'module' plugins: ['estree'] // Ensure Babel outputs ESTree-compatible AST }); // Synchronous evaluation const syncResult = evaluate.sync(ast, context); console.log('Synchronous result:', syncResult); // Expected: Eligible // Asynchronous evaluation (returns a Promise) const asyncResult = await evaluate(ast, { ...context, functions: true }); // functions option enabled for example console.log('Asynchronous result:', asyncResult); // Expected: Eligible // Example with a different context const anotherContext = { user: { name: 'Bob', age: 16, status: 'inactive' } }; const syncResult2 = evaluate.sync(ast, anotherContext); console.log('Synchronous result (Bob):', syncResult2); // Expected: Not Eligible } catch (error) { console.error('Evaluation error:', error.message); } } runEvaluation();
Debug
Known issues
breakingVersion 3.x and later of `eval-estree-expression` requires Node.js version 14 or greater. This may break existing applications running on older Node.js runtimes.
fix
Upgrade your Node.js environment to version 14 or higher. If you must support older Node.js, consider using an earlier major version of the library (e.g., v2.x).
affects: >=3.0.0
gotchaEnabling the `functions: true` or `generate: true` options can introduce security vulnerabilities by allowing arbitrary function calls or function expressions/statements to be evaluated. This can lead to remote code execution if expressions or contexts originate from untrusted user input.
fix
Avoid enabling `functions: true` or `generate: true` when evaluating untrusted user-supplied expressions or when context objects can contain malicious functions. Carefully sanitize or whitelist any user input before parsing or evaluating.
affects: >=1.0.0
gotchaThe library is designed for expressions and does not support JavaScript assignment operators (e.g., `=`, `+=`, `--`) or general statements by default. Attempting to evaluate code with these constructs will result in an error.
fix
Ensure that the input AST represents only pure expressions. If you need to allow specific assignments or statements, consider alternative, more powerful (and potentially less safe) evaluation mechanisms or pre-process the AST to remove/transform unsupported nodes.
affects: >=1.0.0
gotchaWhile `eval-estree-expression` avoids direct `eval()`, it does not inherently provide a secure sandbox against all forms of malicious code execution. If user-controlled data is passed in the `context` object, especially if it contains objects with malicious getters or methods, it could potentially be exploited.
fix
Always validate and sanitize the `context` object when it's populated by untrusted sources. Ensure that context values are primitive types or objects whose properties are strictly controlled and do not expose system-level APIs or sensitive operations.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: 'myVariable' is not defined
An expression attempts to access a variable or property ('myVariable') that is not present in the provided `context` object.
fix
Ensure all variables referenced in the expression are explicitly provided as properties in the `context` object passed to `evaluate` or `evaluate.sync`.
SyntaxError: Assign expression is not supported
The input AST (from the parsed expression) contains an assignment operation (e.g., `x = 10`) or a statement not supported by the evaluator.
fix
The library is designed for pure expressions. Do not attempt to evaluate JavaScript statements or expressions that modify state. Remove assignment operators or convert them to pure expressions where possible.
TypeError: 'myFunction' is not a function
An expression attempts to call a function (`myFunction`) when the `functions` option is not explicitly enabled, or a function expression/statement is present without the `generate` option.
fix
If you intend to allow function calls, enable the `functions: true` option in the `evaluate` options. If you need to evaluate full function expressions or statements, use `generate: true` (with extreme caution due to security implications).
Upgrade
Version history
3.0.1latest on npm
Audit
Dependencies
@babel/parseroptionalCommonly used to parse JavaScript code into an ESTree-compatible AST, which is then consumed by `eval-estree-expression`.
Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources