Run it

Node Guide

Parse a Markdown string to an AST, walk the headings, build a nested table of contents with GitHub-style ids and a heading-id map, and print it as a Markdown list. node kind.

Uses @awacloud/md (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.

When to use it

A documentation build that needs a navigation tree, a link checker that needs every anchor a page defines, or a chunker that splits a document at its headings for indexing — anything that reads Markdown as structure rather than rendering it.

Copy-paste steps

  1. npm install @awacloud/md (it depends on @awacloud/fw).
  2. Copy main.js and run bun main.js README.md (or node main.js README.md): one - [text](#id) line per heading, indented by level.
  3. Call toc(markdown) for the nested entries, headings(markdown) for the flat list or idMap(markdown) for { id: text } from your own code.

What it shows

  • Wiring: bootstrapMd({ runtime }) from @awacloud/md/bootstrap.js on a fresh ModuleRuntime; md is the façade, mdAstWalker and mdToc are resolved by name from the same runtime.
  • Parse: md.parse(text) returns the CommonMark AST (a document node whose heading nodes carry level, with text and code leaves below).
  • Walk: mdAstWalker.walk(ast) is a generator of { node, entering } events in pre-order with an explicit exit for containers — a heading's text is gathered between its entering and its exit, so emphasis and code spans flatten to plain text.
  • Ids: mdToc.slugify(text) is the package's GitHub-style anchor (lower-case, punctuation removed, spaces to hyphens); repeated slugs are suffixed -1, -2, … like the package's own table-of-contents extra; an empty heading gets section.
  • Nesting: an entry becomes a child of the nearest shallower entry before it, so a document that skips a level (an h3 under an h1) still nests; toMarkdownList prints two spaces per level.
  • Not shown: mdToc.generate and the [[toc]] placeholder, which do the same job for a rendered page; the AST manipulation module; renderMarkdown.

Code

main.js

javascriptAGPL-3.0-only80 lines

// SPDX-License-Identifier: AGPL-3.0-only
// Run: bun main.js <file.md>   (or node main.js <file.md>)
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { bootstrapMd } from '@awacloud/md/bootstrap.js';

const boot = bootstrapMd({ runtime: new ModuleRuntime() });
const { md } = boot;
const { walk } = boot.resolve('mdAstWalker');
const { slugify } = boot.resolve('mdToc'); // GitHub's anchor scheme: lower-case, punctuation out, spaces to hyphens

/** @typedef {{ level: number, text: string, id: string }} Heading */
/** @typedef {Heading & { children: Entry[] }} Entry */

/**
 * The headings of a document, in order: parse to an AST, walk it, and on each
 * heading collect the plain text of its `text` and `code` descendants (emphasis
 * and code spans flatten to their text). Ids are GitHub-style slugs, repeated
 * ones suffixed `-1`, `-2`, … like the package's own table-of-contents extra.
 * @param {string} markdown
 * @returns {Heading[]}
 */
export function headings(markdown) {
    const out = [];
    const seen = new Map();
    let current = null;
    for (const { node, entering } of walk(md.parse(markdown))) {
        if (node.type === 'heading' && entering) current = { level: node.level, text: '' };
        else if (node.type === 'heading' && current) {
            const base = slugify(current.text) || 'section';
            const n = seen.get(base) ?? 0;
            seen.set(base, n + 1);
            out.push({ ...current, id: n ? `${base}-${n}` : base });
            current = null;
        } else if (current && entering && (node.type === 'text' || node.type === 'code')) current.text += node.literal;
    }
    return out;
}

/**
 * Nest the headings: an entry becomes a child of the nearest shallower entry
 * before it (an `h3` after an `h1` nests directly under it).
 * @param {string} markdown
 * @returns {Entry[]}
 */
export function toc(markdown) {
    const root = /** @type {Entry[]} */ ([]);
    const stack = [{ level: 0, children: root }];
    for (const heading of headings(markdown)) {
        const entry = { ...heading, children: [] };
        while (stack[stack.length - 1].level >= entry.level) stack.pop();
        stack[stack.length - 1].children.push(entry);
        stack.push(entry);
    }
    return root;
}

/** `id → text` for every heading: what a link checker or a chunker keys on. @param {string} markdown */
export const idMap = (markdown) => Object.fromEntries(headings(markdown).map((h) => [h.id, h.text]));

/**
 * The table of contents as a Markdown list, one line per heading, two spaces per level.
 * @param {Entry[]} entries @param {number} [depth]
 */
export function toMarkdownList(entries, depth = 0) {
    return entries.flatMap((e) => [
        `${'  '.repeat(depth)}- [${e.text}](#${e.id})`, ...toMarkdownList(e.children, depth + 1)]);
}

/** @param {string[]} [argv] */
export function main(argv = process.argv.slice(2)) {
    const [file] = argv;
    if (!file) return ['usage: bun main.js <file.md>'];
    return toMarkdownList(toc(readFileSync(file, 'utf8')));
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    for (const line of main()) console.log(line);
}