Vega Expression Parser and Code Generator

6.1.0 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { parse, codegen } from 'vega-expression';

interface DataItem {
  value: number;
  category: string;
}

// 1. Define the expression string
const expressionString = "datum.value * 2 + 5";

// 2. Parse the expression into an AST
const ast = parse(expressionString);
console.log('Parsed AST:', JSON.stringify(ast, null, 2));

// 3. Create a code generator, specifying the field variable ('datum' in this case)
//    and any allowed globals/functions if needed.
const generator = codegen({
  fieldvar: 'datum',
  allowed: ['datum'], // 'datum' is an allowed variable in the expression scope
  // You can also provide custom functions or constants
  functions: () => ({
    pow: (args: any[]) => `Math.pow(${args[0]}, ${args[1]})`
  })
});

// 4. Generate the executable code from the AST
const { code, fields, globals } = generator(ast);
console.log('\nGenerated Code:', code);
console.log('Referenced Fields:', fields);
console.log('Referenced Globals:', globals);

// 5. Evaluate and use the generated function
//    NOTE: Using `Function` constructor is generally discouraged due to CSP issues.
//          For Vega runtime, `vega-interpreter` offers CSP-compliant evaluation.
const evaluateExpression = new Function('datum', `return ${code};`);

const sampleData: DataItem = { value: 10, category: 'A' };
const result = evaluateExpression(sampleData);
console.log(`\nResult for { value: 10 } (10 * 2 + 5):`, result); // Expected: 25

const anotherData: DataItem = { value: 7, category: 'B' };
const anotherResult = evaluateExpression(anotherData);
console.log(`Result for { value: 7 } (7 * 2 + 5):`, anotherResult); // Expected: 19

view raw JSON →