remark-mdat
v1.2.4
Published
A remark plugin implementing the Markdown Autophagic Template (MDAT) system.
Maintainers
Readme
remark-mdat
A remark plugin implementing the Markdown Autophagic Template (MDAT) system.
[!NOTE]
Please see The
mdatpackage for a higher-level CLI tool and library with a collection of built-in expansion rules.
Table of contents
- Overview
- Getting started
- Usage
- Utilities
- Implementation notes
- The future
- Maintainers
- Acknowledgments
- Contributing
- License
Overview
This is a remark plugin that automates the inline expansion of placeholder HTML comments with dynamic content in Markdown, making it easy to keep readme files and other documentation in sync with an external single source of truth.
The plugin can take placeholder comments in a Markdown file like this:
<!-- title -->And replace it with dynamic data. In this case, from package.json:
<!-- title -->
# remark-mdat
<!-- /title -->This plugin powers the higher-level mdat package, which is a better place to start if you just want to expand some comments and aren't working directly with remark processing pipelines.
Getting started
Dependencies
This library is ESM only and requires Node 20+. It's designed to work with Remark 15. remark-mdat is implemented in TypeScript and bundles a complete set of type definitions.
Installation
npm install remark-mdatUsage
API
Core plugin
This package's default export implements the unified Plugin type.
The plugin is integrated into a remark process chain via the .use() method:
import { remark } from 'remark'
import remarkMdat from 'remark-mdat'
remark().use(remarkMdat)Options
The plugin accepts an optional options object. All fields are optional:
| Option | Type | Default | Description |
| ----------------------- | ------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| rules | Rules | {} | A record mapping comment keywords to rules that determine what content is expanded at each comment site. See Rules below. |
| addMetaComment | boolean \| string | false | If true, prepends a warning comment to the document noting that content was auto-generated. If a string, uses that string as the warning message. |
| closingPrefix | string | '/' | The prefix used to identify closing comment tags, e.g. the / in <!-- /keyword -->. |
| keywordPrefix | string | '' | A prefix required on all mdat comments. Useful for namespacing, e.g. setting 'mm-' means only <!-- mm-keyword --> comments are processed. |
| metaCommentIdentifier | string | '+' | The character used to identify auto-generated meta comments, e.g. <!--+ ... +-->. |
Rules
Rules are defined as a Record<string, Rule> where each key is a keyword matching an HTML comment in the Markdown file (e.g. title matches <!-- title -->).
A Rule value can take several forms:
const rules: Rules = {
// String: direct replacement
greeting: 'Hello, world!',
// Array: compound rule combining multiple sub-rules
header: ['# My Project', () => getDescription()],
// Function with arguments: receives parsed options from the comment
// e.g. <!-- greeting({name: "Alice"}) --> or <!-- greeting {name: "Alice"} -->
personalGreeting: (options) => `Hello, ${options.name}!`,
// Function: dynamic content (sync or async)
time: () => new Date().toDateString(),
// Object: rule with validation metadata
title: {
applicationOrder: 0, // Processing priority (default: 0)
content: () => getTitle(), // String, function, or array
order: 1, // Expected position relative to other comments
required: true, // Error if comment is missing (default: false)
},
// Function with document access: receives the full mdast tree
toc: (_options, tree) => generateTocFromTree(tree),
}Examples
Basic
remark-mdat includes one test rule by default, <!-- mdat -->.
import { remark } from 'remark'
import remarkMdat from 'remark-mdat'
const markdownInput = '<!-- mdat -->'
const markdownOutput = await remark().use(remarkMdat).process(markdownInput)
console.log(markdownOutput.toString())
// Logs:
// <!-- mdat -->
//
// Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat).
//
// <!-- /mdat -->With options
If you wanted to replace <!-- time --> comments in your Markdown file with the current time, you could pass in a rule:
import type { Rules } from 'remark-mdat'
import { remark } from 'remark'
import remarkMdat from 'remark-mdat'
// Create the rule
const rules: Rules = {
time: () => new Date().toDateString(),
}
const markdownInput = '<!-- time -->'
// Pass the time rule to remarkMdat
const markdownOutput = await remark().use(remarkMdat, { rules }).process(markdownInput)
console.log(markdownOutput.toString())
// Logs:
// <!-- time -->
//
// Mon Feb 05 2024
//
// <!-- /time -->See the mdat package for a higher-level API and CLI that can operate directly on files or strings. It also provides dynamic rule loading and configuration resolution, and bundles a collection of rules convenient for use in readme files.
Utilities
The plugin bundles a number of mdast utilities designed to operate directly on syntax trees. These are exported to support customized Unified.js processors and enforce modularity and separation of concerns in mdat's internal implementation, but you do not need to use them directly — all functionality is encapsulated in the single remarkMdat plugin export.
The remark-mdat plugin chains these utilities together to accommodate the typical use case of end-to-end expansion and validation of mdat comments. For now, the individual utility transformers are not published individually to NPM, and are instead bundled with remark-mdat.
Composite transformer function performing end-to-end mdat comment expansion and validation on Markdown ASTs by chaining the other utility functions described below.
Exported as
mdat(tree: Root, file: VFile, options: MdatOptions): Promise<void>MdatOptionsincludesaddMetaComment,closingPrefix,keywordPrefix,metaCommentIdentifier, andrules(all required, unlike the plugin'sOptionswhere they are optional with defaults).Utilities wrapped by
mdast-util-mdat:Transformer function that splits multi-comment HTML nodes into individual mdast nodes, allowing inline mdat expansion comments.
Exported as
mdatSplit(tree: Root, file: VFile): voidTransformer function that "resets" all mdat comment expansions in a file, collapsing expanded comments back into single-line placeholders.
Exported as
mdatClean(tree: Root, file: VFile, options: MdatCleanOptions): voidMdatCleanOptionsincludesclosingPrefix,keywordPrefix, andmetaCommentIdentifier.Transformer function that expands mdat comments (e.g.
<!-- title -->) in a Markdown file according to the rule set passed in to the options argument.Exported as
mdatExpand(tree: Root, file: VFile, options: MdatExpandOptions): Promise<void>MdatExpandOptionsincludesaddMetaComment,closingPrefix,keywordPrefix,metaCommentIdentifier, andrules.Transformer function that validates an expanded Markdown document against the requirements defined in the rules passed in to the options argument. Does not modify the tree, it only appends messages to the VFile.
Exported as
mdatCheck(tree: Root, file: VFile, options: MdatCheckOptions): Promise<void>MdatCheckOptionsextendsMdatExpandOptionswith aparanoidboolean for extra validation checks.See
reporterMdatto extract, format, and log results from VFile messages written bymdatCheck.
Implementation notes
This project was split from a monorepo containing both mdat and remark-mdat into separate repos in July 2024.
The future
- Consider making remark a peer dependency? Though perhaps not strip-markdown/issues/24...
Maintainers
Acknowledgments
Thanks to the unified team for their superb ecosystem of AST tools.
Contributing
Issues and pull requests are welcome.
License
MIT © Eric Mika
