micromark events to Acorn parser utility

2.0.3 · active · verified Sun Apr 19

micromark-util-events-to-acorn is a core utility within the micromark ecosystem, specifically designed to bridge micromark's low-level parsing events with acorn's robust JavaScript parsing capabilities. It takes an array of micromark events and attempts to construct an Abstract Syntax Tree (AST) using an acorn parser instance. This package is crucial for handling MDX expressions and similar constructs where embedded JavaScript needs to be parsed and validated. The current stable version is 2.0.3. While it doesn't have an independent, fixed release cadence, its updates are typically coordinated with major and minor releases of related micromark extensions, such as micromark-extension-mdx-expression. A key differentiator is its specialized role in the micromark architecture, providing a performant and integrated way to parse JavaScript directly from event streams, requiring the acorn parser and its options to be passed explicitly rather than being a direct dependency. It is ESM-only, requiring Node.js 16 or later.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `eventsToAcorn` to parse a mock stream of `micromark` events into an `ESTree` using `acorn`.

import { eventsToAcorn } from 'micromark-util-events-to-acorn';
import * as acorn from 'acorn'; // acorn must be installed and provided

// Mock micromark events representing a simple MDX expression `{1 + 1}`.
// In a real micromark application, these events would be generated by a tokenizer
// parsing Markdown/MDX content.
const sampleEvents = [
  { type: 'mdxExpressionText', start: { line: 1, column: 2, offset: 1 }, end: { line: 1, column: 7, offset: 6 } }
];

const mockAcornOptions = { ecmaVersion: 2024, sourceType: 'module' };

// Attempt to parse the micromark events into an ESTree AST using acorn.
const result = eventsToAcorn(sampleEvents, {
  acorn: {
    parse: acorn.parse,
    parseExpressionAt: acorn.parseExpressionAt,
  },
  tokenTypes: ['mdxExpressionText'], // Essential since v2.0.0: list micromark token types that represent code data
  acornOptions: mockAcornOptions,
  start: { line: 1, column: 1, offset: 0 }, // Start position for source mapping
  expression: true, // Indicate that we are parsing an expression
  allowEmpty: false, // Do not allow empty expressions
  prefix: '',
  suffix: ''
});

if (result.error) {
  console.error('Failed to parse expression:', result.error.message);
} else if (result.estree) {
  console.log('Successfully parsed ESTree expression:');
  console.log(JSON.stringify(result.estree.body[0], null, 2));
  // Expected output will be an ESTree node for '1 + 1'.
} else {
  console.log('Parsing completed, but no ESTree generated (e.g., empty expression allowed).');
}

view raw JSON →