--- title: Plugin API description: Type-safe API for creating Comark plugins with pre and post lifecycle hooks. links: - label: Parse API icon: i-lucide-file-code to: /reference/parse color: neutral variant: soft - label: Document model icon: i-lucide-braces to: /getting-started/document-model color: neutral variant: soft --- The `comark` package exports `defineComarkPlugin`, a typed factory wrapper for building plugins that extend the parser. ## `defineComarkPlugin(factory)`{lang="ts"} Wraps a plugin factory function to provide type safety for both options and the returned plugin. **Parameters:** - `factory`: A function `(options?: O) => ComarkPlugin` where `O` is an optional options type. When the plugin is instantiated, `options` receives the values passed by the caller. See [`ComarkPlugin`](#comarkplugintmeta-tfrontmatter) for the full shape of the returned object. **Type parameters:** | Parameter | Default | Description | |---|---|---| | `Options` | `unknown` | Shape of the options the factory accepts. | | `TMeta` | `{}` | Keys this plugin contributes to `tree.meta`. Surfaces on the `parse` result and constrains writes inside `post`. | | `TFrontmatter` | `{}` | Keys this plugin contributes to `tree.frontmatter`. This is experimental and may change in future versions. | **Returns:** A typed plugin factory `(options?: O) => ComarkPlugin` **Example:** ```typescript import { defineComarkPlugin } from 'comark' export default defineComarkPlugin(() => ({ name: 'my-plugin', pre(state) {}, post(state) {}, })) ``` With typed options: ```typescript import { defineComarkPlugin } from 'comark' interface MyOptions { prefix?: string } export default defineComarkPlugin((options: MyOptions = {}) => ({ name: 'my-plugin', post(state) { // options.prefix is typed }, })) ``` --- ## Typed contributions Plugins that write to `tree.meta` can declare what they contribute via the second and third type parameters of `defineComarkPlugin`. Two things follow from that declaration: 1. **Inside `post(state)`**, `state.tree.meta` and `state.tree.frontmatter` are typed as the declared shape, so writes are checked against it. 2. **At the `parseMarkdown` call site**, Comark intersects the contribution into `tree.meta` and `tree.frontmatter`, so `result.meta.toc` reads back as the declared type instead of `any`. ### Declaring a contribution ```typescript import { defineComarkPlugin } from 'comark' interface TocTree { title: string depth: number links: { id: string; text: string }[] } export default defineComarkPlugin<{}, { toc: TocTree }>(() => ({ name: 'toc', post(state) { state.tree.meta.toc = { title: 'Contents', depth: 2, links: [] } // @ts-expect-error wrong value type for the declared key state.tree.meta.toc = 123 // @ts-expect-error `summary` was not declared in the contribution state.tree.meta.summary = [] }, })) ``` A plugin that contributes more than one key lists them all in the same object literal: ```typescript defineComarkPlugin(() => ({ name: 'title-description', post(state) { state.tree.meta.title = 'Hello' state.tree.meta.description = undefined }, })) ``` ### Inference at the `parseMarkdown` call site `parseMarkdown` and `createMarkdownParser` infer the plugins tuple and intersect each plugin's contribution into the result type without an explicit generic argument: ```typescript import { parseMarkdown } from 'comark' import toc from 'comark/plugins/toc' import summary from 'comark/plugins/summary' const tree = await parseMarkdown(content, { plugins: [toc(), summary()] }) tree.meta.toc // Toc tree.meta.summary // Node[] tree.meta.something // unknown: undeclared keys are typed as unknown ``` ### Backward compatibility for untyped plugins Plugins that omit the meta and frontmatter type parameters keep untyped `Record` maps, allowing writes to any key. At the `parseMarkdown` call site, `meta` also stays `Record` when no plugin declares a contribution (or when `plugins` is typed as a widened `ComarkPlugin[]` variable rather than an inline array). ```typescript // Untyped plugin: meta stays Record defineComarkPlugin(() => ({ name: 'wordcount', post(state) { state.tree.meta.wordCount = 42 // allowed when no contribution is declared }, })) ``` --- ## Lifecycle Plugins hook into two phases of the parsing pipeline: ``` Markdown string │ ▼ ┌──────────┐ │ pre() │ ← Modify raw Markdown before parsing └──────────┘ │ ▼ Parse & Build MarkdownDocument │ ▼ ┌──────────┐ │ post() │ ← Transform the AST after parsing └──────────┘ │ ▼ MarkdownDocument ``` ### `pre(state)`{lang="ts"} Called before Markdown is tokenized. Use it to transform the raw Markdown string. ```typescript import { defineComarkPlugin } from 'comark' export default defineComarkPlugin(() => ({ name: 'strip-comments', pre(state) { state.markdown = state.markdown.replace(//g, '') }, })) ``` **`ComarkParsePreState`:** | Field | Type | Description | |---|---|---| | `markdown` | `string` | The raw Markdown; modify it to change parser input | | `options` | [`ParserOptions`](/reference/parse#options) | The parser configuration | ### `post(state)`{lang="ts"} Called after the AST is built. Use it to traverse nodes or populate `meta` with extracted data. ```typescript import { defineComarkPlugin } from 'comark' import { visit } from 'comark/utils' export default defineComarkPlugin(() => ({ name: 'word-count', post(state) { let count = 0 visit(state.tree, (node) => typeof node === 'string', (node) => { count += (node as string).split(/\s+/).filter(Boolean).length } ) state.tree.meta.wordCount = count }, })) ``` **`ComarkParsePostState`:** | Field | Type | Description | |---|---|---| | `markdown` | `string` | The original Markdown input | | `tree` | [`MarkdownDocument`](/getting-started/document-model#document-structure) | The parsed document; modify it to transform output. `tree.meta` and `tree.frontmatter` are typed against the plugin's declared contribution. | | `options` | [`ParserOptions`](/reference/parse#options) | The parser configuration | | `tokens` | `unknown[]` | The raw markdown-it tokens | ::tip{to="/plugins/custom/ast-api"} To traverse and transform `tree` nodes, see the AST API page for the `visit()` utility. :: --- ## `ComarkPlugin` | Property | Type | Description | |---|---|---| | `name` | `string` | A unique identifier for the plugin | | `markdownItPlugins` | [`MarkdownItPlugin[]`](https://markdown-it.github.io/markdown-it/#MarkdownIt) | markdown-it plugins to register on the parser. See [Markdown-it plugins](/plugins/custom/markdown-it) | | `pre` | `(state: ComarkParsePreState) => Promise \| void` | Hook called before parsing | | `post` | `(state: ComarkParsePostState) => Promise \| void` | Hook called after the AST is built. `state.tree.meta` and `state.tree.frontmatter` are typed as the declared contribution. See [Typed contributions](#typed-contributions) | | `autoClose` | `{ bracketMath?: boolean }` | Auto-close flags for syntax this plugin adds. Flags from all plugins are merged and applied when the parser's `autoClose` is `true`; a custom `autoClose` function ignores them | --- ## Usage Pass plugins to `parseMarkdown()` or the `` component: ::code-group ```typescript [Parse API] import { parseMarkdown } from 'comark' import myPlugin from './my-plugin' const tree = await parseMarkdown(content, { plugins: [myPlugin()] }) ``` ```vue [Vue] ``` ```tsx [React] import { Markdown } from '@comark/react' import myPlugin from './my-plugin' {content} ``` ```svelte [Svelte] ``` ::