vega-expression is a JavaScript/TypeScript library that provides a secure and configurable expression parser and code generator, forming a core component of the broader Vega visualization toolkit. It processes a limited subset of JavaScript expressions into an Abstract Syntax Tree (AST) and then generates `eval`'able JavaScript code. The library intentionally restricts language features like assignment operators, `new` expressions, and control flow to prioritize security and prevent unwanted side effects, making it suitable for user-provided expressions in visualization contexts. It is currently in active development, with version 6.2.0 as the latest stable release at the time of this entry, following a fairly active release cadence that often aligns with the larger Vega monorepo. Its key differentiators include its security-first approach, a stripped-down Esprima-based parser, and highly configurable code generation options for managing constants, functions, and variable scopes, including tracking data field dependencies.
npm install vega-expressionVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates parsing a basic mathematical expression, generating executable JavaScript code, and evaluating it within a defined data context. It highlights the use of `parse` and `codegen` with `fieldvar` and `allowed` options.
Migrate all `require()` calls to `import` statements. Ensure your project is configured for ESM, typically by setting `"type": "module"` in `package.json` or using `.mjs` file extensions.
Upgrade to `vega-expression@5.33.1` or higher (including all `v6.x` versions) to mitigate the prototype pollution vulnerability. Always validate user-provided expressions carefully.
Ensure expressions adhere to the allowed syntax. Refer to the Vega expression language documentation for a full list of supported features, constants, and functions. Use the `codegen` options (`forbidden`, `allowed`, `functions`) to explicitly control what can be referenced.
If CSP is a concern, integrate `vega-interpreter` into your runtime. Invoke the Vega parser with the `{ast: true}` option and pass the interpreter as an option to the Vega View constructor to enable AST-based evaluation.Replace `const { parse } = require('vega-expression');` with `import { parse } from 'vega-expression';`. Ensure your `package.json` has `"type": "module"` or use `.mjs` file extensions for ESM files.Rewrite the expression to use only the allowed subset of JavaScript. Avoid assignment operators, `new` expressions, `for`/`while` loops, and direct method calls on nested properties.
When creating the code generator, use the `allowed` array for variables within the expression scope, or the `globalvar` option to specify the object through which global variables should be looked up.