Convert JavaScript values to ESTree expressions
estree-util-value-to-estree is a utility library for converting diverse JavaScript values into their corresponding ESTree Abstract Syntax Tree (AST) expressions. This package is particularly useful for tools that manipulate or generate JavaScript code, enabling programmatic construction of AST nodes from native JavaScript types. The current stable version is 3.5.0, with a release cadence that includes regular minor and patch updates to support new JavaScript features and fix bugs. Key differentiators include its broad support for various primitive types (e.g., bigint, symbol, undefined, null, boolean, number, string) and object types (e.g., Array, Object, Map, Set, Date, RegExp, Buffer, various TypedArrays, and Temporal types). It also provides a `serialize` option for handling custom or unsupported values, allowing users to define how complex or application-specific data structures should be represented in the AST. It is designed for values that can be constructed without needing a runtime context.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require()` to import `estree-util-value-to-estree` in a pure ESM context (e.g., in a Node.js module with `"type": "module"` in `package.json` or a `.mjs` file).fixChange your import statement to use ES module syntax: `import { valueToEstree } from 'estree-util-value-to-estree';` -
Error: Unknown value type for serialization.
cause You are attempting to serialize a value type that is not natively supported by `estree-util-value-to-estree`, and no custom `serialize` option has been provided to handle it.fixImplement a `serialize` function in the options object passed to `valueToEstree` to explicitly define how to convert the unsupported value into an ESTree node. For example, `valueToEstree(myCustomValue, { serialize: (value) => value instanceof MyClass ? { type: 'NewExpression', callee: { type: 'Identifier', name: 'MyClass' }, arguments: [] } : undefined })`.
Warnings
- breaking A critical vulnerability (CVE-2025-32014) was identified where converting an object with a `__proto__` property could lead to prototype pollution in the generated ESTree. This allows an attacker to inject arbitrary properties into `Object.prototype`, affecting all objects in the application.
- gotcha When working with `Temporal` types (e.g., `Temporal.Instant`, `Temporal.PlainDate`), ensure that the `Temporal` global object is available or polyfilled in the environment where the generated code will run. While the library itself was updated in v3.3.1 to not crash if `Temporal` is undefined, the resulting AST for `Temporal` objects will rely on the `Temporal` global being present.
- gotcha For unsupported JavaScript values or custom class instances, the default behavior of `valueToEstree` might not produce the desired AST representation. For example, a custom class instance might be serialized as a plain object or might lead to an error if not handled.
Install
-
npm install estree-util-value-to-estree -
yarn add estree-util-value-to-estree -
pnpm add estree-util-value-to-estree
Imports
- valueToEstree
const valueToEstree = require('estree-util-value-to-estree')import { valueToEstree } from 'estree-util-value-to-estree' - Options
import type { Options } from 'estree-util-value-to-estree'
Quickstart
import { valueToEstree } from 'estree-util-value-to-estree';
import { generate } from 'astring'; // Commonly used to convert ESTree to code
const exampleValue = {
id: 123,
name: 'Example Item',
enabled: true,
price: 99.95,
details: ['alpha', 'beta', null],
config: new Map([['key1', 'value1'], ['key2', 42n]]),
created: new Date('2024-01-01T10:00:00Z'),
pattern: /test/g,
complex: {
nested: Symbol.for('unique-id'),
buffer: Buffer.from('hello'),
// Unsupported types will require a custom serializer
customClass: new class MyCustom { constructor() { this.prop = 'value'; } }()
}
};
// Convert a standard JavaScript value to an ESTree expression
const estreeExpression = valueToEstree(exampleValue);
console.log('Generated ESTree (partial):', estreeExpression.type);
console.log('Generated Code for standard value:\n', generate(estreeExpression));
// Example with a custom serializer for the custom class
const estreeWithCustom = valueToEstree(exampleValue, {
serialize(value) {
if (value instanceof Buffer) {
// Convert Buffer to a Buffer.from() call
return {
type: 'CallExpression',
callee: { type: 'MemberExpression', object: { type: 'Identifier', name: 'Buffer' }, property: { type: 'Identifier', name: 'from' }, computed: false, optional: false },
arguments: [{ type: 'Literal', value: value.toString('hex') }, { type: 'Literal', value: 'hex' }]
};
}
if (value && typeof value === 'object' && value.constructor.name === 'MyCustom') {
// Convert MyCustom instance to a new MyCustom() expression
return {
type: 'NewExpression',
callee: { type: 'Identifier', name: 'MyCustom' },
arguments: []
};
}
// Let the default logic handle other types
return undefined;
}
});
console.log('\nGenerated Code with custom serializer:\n', generate(estreeWithCustom));