Compact mdast Trees

5.0.0 · active · verified Sun Apr 19

mdast-util-compact is a specialized utility within the unified (syntax-tree) ecosystem designed to normalize mdast (Markdown Abstract Syntax Tree) trees by merging adjacent text nodes and collapsing blockquotes. Its primary use case is to clean up an mdast tree after programmatically modifying it, making the tree structure more consistent with how it would be generated by a parser. The current stable version is 5.0.0. The package follows semantic versioning with major releases introducing breaking changes, often related to Node.js version support or ESM migration, as well as updates to underlying `mdast` type definitions. A key differentiator is its explicit recommendation against frequent use, suggesting developers should ideally maintain clean trees themselves rather than relying on this utility post-hoc. It is an ESM-only package and fully typed with TypeScript.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `compact` to merge adjacent text nodes within a paragraph and combine consecutive blockquote nodes in an mdast tree, modifying the tree in-place.

import { u } from 'unist-builder';
import { compact } from 'mdast-util-compact';

// Create a sample mdast tree with adjacent text nodes and blockquotes
const tree = u('root', [
  u('paragraph', [
    u('text', 'Hello'),
    u('text', ' '),
    u('text', 'world!')
  ]),
  u('blockquote', [u('paragraph', [u('text', 'First quote line')])]),
  u('text', '\n'), // Newline between blocks might prevent merging without additional parsers
  u('blockquote', [u('paragraph', [u('text', 'Second quote line')])])
]);

console.log('Original tree:\n', JSON.stringify(tree, null, 2));

// Compact the tree in-place
compact(tree);

console.log('\nCompacted tree:\n', JSON.stringify(tree, null, 2));

/*
Expected compacted output (exact structure may vary based on unist-builder and mdast versions, 
but text nodes and blockquotes will be merged):
Compacted tree:
 {
  "type": "root",
  "children": [
    {
      "type": "paragraph",
      "children": [
        {
          "type": "text",
          "value": "Hello world!"
        }
      ]
    },
    {
      "type": "blockquote",
      "children": [
        {
          "type": "paragraph",
          "children": [
            {
              "type": "text",
              "value": "First quote line\nSecond quote line"
            }
          ]
        }
      ]
    }
  ]
}
*/

view raw JSON →