Markdown AST
These runtime helpers provide a friendly wrapper around the remark, mdast, unified ecosystem to parse and manipulate Markdown documents.
Installation
Section titled “Installation”npm i -D @genaiscript/plugin-mdast
pnpm add -D @genaiscript/plugin-mdast
yarn add -D @genaiscript/plugin-mdast
If you are using the plugin in a Node.JS environment, without a .genai...
entry file, you will need
to initialize the runtime before using the plugin:
import { initialize } from "@genaiscript/runtime";
await initialize();
Markdown manipulation
Section titled “Markdown manipulation”- load the parsers
import { mdast } from "@genaiscript/plugin-mdast";
const { parse, visit, stringify } = await mdast();
- parsing to mdast tree
const root = parse("# Hello World");
- visiting the tree (see documentation)
const updated = visit(root, `code`, (node) => { ...node});
- serializing the tree back to Markdown
const markdown = await stringify(updated);
- chunk the tree into sections
const { parse, chunk } = await mdast();const root = parse( "# Section 1\n\nContent 1\n\n## Subsection 1.1\n\nContent 1.1\n\n# Section 2\n\nContent 2",);const sections = chunk(root);console.log(sections);
In order to get type completion, you will need to install the @types/mdast
package as a development dependency.
Debugging trees
Section titled “Debugging trees”You can use inspect
to pretty print a MDAST tree.
const { parse, inspect } = await mdast();const root = parse("# Hello World");console.log(inspect(root));
If you plan to process MDX documents, you should configure the plugin to use the mdx
parser:
const { parse } = await mdast({ mdx: true });