Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(markdown): add native frontmatter metadata (#6381)

Cindy Zhanga540a6d8a273
diff --git a/.changeset/markdown-frontmatter.md b/.changeset/markdown-frontmatter.md
new file mode 100644
index 0000000000..85d761b8cf
--- /dev/null
+++ b/.changeset/markdown-frontmatter.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Markdown: add native typed frontmatter metadata
+
+Use `createMarkdownFrontmatter()` from `@astryxdesign/core/Markdown/plugins` to decode a document-start key/value block into typed metadata, keep unfinished streaming metadata hidden, and remove completed metadata syntax from rendered Markdown.
+
+@cixzhang
diff --git a/apps/storybook/stories/Markdown.demoPlugins.tsx b/apps/storybook/stories/Markdown.demoPlugins.tsx
index b520164d99..5b936f6254 100644
--- a/apps/storybook/stories/Markdown.demoPlugins.tsx
+++ b/apps/storybook/stories/Markdown.demoPlugins.tsx
@@ -8,6 +8,7 @@
*/
import {
+ createMarkdownFrontmatter,
createMarkdownPlugin,
createMarkdownFenceTransform,
createMarkdownSourceDecoration,
@@ -176,6 +177,14 @@ const semanticFencePlugin = createMarkdownPlugin<
export const markdownSemanticFenceDemoPlugin = semanticFencePlugin;
+export const markdownFrontmatterDemo = createMarkdownFrontmatter({
+ name: 'demo-document-metadata',
+ parse: fields => ({
+ title: fields.title ?? 'Untitled',
+ status: fields.status ?? 'unknown',
+ }),
+});
+
export const markdownDemoPlugins = [
createMarkdownPlugin<'demo-mentions', MentionNode>(mentionDefinition),
createMarkdownPlugin<'demo-callouts', CalloutNode>(calloutDefinition),
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index a844c9df22..2a63f8eef8 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -12,6 +12,7 @@ import {
createDelayedMarkdownDemoPlugin,
createSourceDecorationDemo,
markdownDemoPlugins,
+ markdownFrontmatterDemo,
markdownSemanticFenceDemoPlugin,
} from './Markdown.demoPlugins';
import {
@@ -686,6 +687,70 @@ export const NativeAndRemarkPlugins: Story = {
},
};
+const fullStackFrontmatterSource = [
+ '---',
+ 'title: Plugin rollout',
+ 'status: ready',
+ '---',
+ '# Plugin rollout',
+ '',
+ 'Hello @{Ada}. TODO tracks SPEC-4821.',
+ '',
+ '```diagram Release path',
+ 'Author --> Review --> Publish',
+ '```',
+].join('\n');
+
+export const NativeFrontmatterWithFullStack: Story = {
+ name: 'Native frontmatter with full plugin stack',
+ render: () => {
+ const metadata = markdownFrontmatterDemo.parse(fullStackFrontmatterSource);
+ const {plugins: decorationPlugins} = createSourceDecorationDemo(
+ fullStackFrontmatterSource,
+ 'Plugin rollout',
+ );
+ const plugins = [
+ markdownFrontmatterDemo.plugin,
+ ...markdownDemoPlugins,
+ markdownSemanticFenceDemoPlugin,
+ remarkSpecLinkPlugin,
+ ...decorationPlugins,
+ ];
+ const label =
+ metadata.status === 'match'
+ ? `${metadata.metadata.title} — ${metadata.metadata.status}`
+ : 'No document metadata';
+
+ return (
+ <div style={{maxWidth: 680}}>
+ <Text>Document metadata: {label}</Text>
+ <Markdown plugins={plugins}>{fullStackFrontmatterSource}</Markdown>
+ </div>
+ );
+ },
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.getByText('Document metadata: Plugin rollout — ready'),
+ ).toBeInTheDocument();
+ await expect(
+ canvas.getByRole('heading', {name: 'Plugin rollout'}),
+ ).toBeInTheDocument();
+ await expect(canvas.getByText('@Ada')).toBeInTheDocument();
+ await expect(canvas.getByText('TODO')).toBeInTheDocument();
+ await expect(canvas.getByRole('link', {name: 'SPEC-4821'})).toHaveAttribute(
+ 'href',
+ '/specs/4821',
+ );
+ await expect(
+ canvas.getByRole('figure', {name: 'Release path'}),
+ ).toBeVisible();
+ await expect(
+ canvas.queryByText('title: Plugin rollout'),
+ ).not.toBeInTheDocument();
+ },
+};
+
export const RemarkOutsideTheProfile: Story = {
name: 'Remark outside the profile',
parameters: {
diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjs
index 451cb77432..6910564295 100644
--- a/packages/core/src/Markdown/Markdown.doc.mjs
+++ b/packages/core/src/Markdown/Markdown.doc.mjs
@@ -267,6 +267,11 @@ export const docs = {
description:
'Use createMarkdownSourceDecoration to attach non-visual metadata — search hits, review annotations — to the blocks a source range touches, and getMarkdownSourceDecorations to read it back in a later plugin. Decorations appear on the settled document rather than on partial streaming chunks, and never change rendering, copyable text, accessible names, ids, focus order, or navigation.',
},
+ {
+ guidance: true,
+ description:
+ 'Use createMarkdownFrontmatter for typed document metadata. Its parse() method gives the host metadata directly; its plugin removes a complete leading block before rendering and withholds an unfinished block during streaming.',
+ },
{
guidance: true,
description:
@@ -420,6 +425,26 @@ const readDecorations = createMarkdownPlugin({
});
<Markdown plugins={[searchHits, readDecorations]}>{source}</Markdown>;
+`,
+ },
+ {
+ label: 'Native frontmatter',
+ code: `
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {createMarkdownFrontmatter} from '@astryxdesign/core/Markdown/plugins';
+
+const frontmatter = createMarkdownFrontmatter({
+ name: 'document-metadata',
+ parse: fields => ({
+ title: fields.title ?? 'Untitled',
+ draft: fields.draft === 'true',
+ }),
+});
+
+const source = '---\\ntitle: Release notes\\ndraft: true\\n---\\n# Shipped';
+const result = frontmatter.parse(source);
+
+<Markdown plugins={[frontmatter.plugin]}>{source}</Markdown>;
`,
},
{
@@ -697,6 +722,11 @@ export const docsZh = {
description:
'Use createMarkdownSourceDecoration to attach non-visual metadata — search hits, review annotations — to the blocks a source range touches, and getMarkdownSourceDecorations to read it back in a later plugin. Decorations appear on the settled document rather than on partial streaming chunks, and never change rendering, copyable text, accessible names, ids, focus order, or navigation.',
},
+ {
+ guidance: true,
+ description:
+ 'Use createMarkdownFrontmatter for typed document metadata. Its parse() method gives the host metadata directly; its plugin removes a complete leading block before rendering and withholds an unfinished block during streaming.',
+ },
{
guidance: true,
description:
@@ -769,6 +799,11 @@ export const docsDense = {
description:
'Use createMarkdownSourceDecoration to attach non-visual metadata — search hits, review annotations — to the blocks a source range touches, and getMarkdownSourceDecorations to read it back in a later plugin. Decorations appear on the settled document rather than on partial streaming chunks, and never change rendering, copyable text, accessible names, ids, focus order, or navigation.',
},
+ {
+ guidance: true,
+ description:
+ 'Use createMarkdownFrontmatter for typed document metadata. Its parse() method gives the host metadata directly; its plugin removes a complete leading block before rendering and withholds an unfinished block during streaming.',
+ },
{
guidance: true,
description:
diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.md
index 88123cfc6f..d08065276e 100644
--- a/packages/core/src/Markdown/Markdown.spec.md
+++ b/packages/core/src/Markdown/Markdown.spec.md
@@ -46,8 +46,8 @@ system_specs:
Markdown renders parsed content in a Document with stable default block parts and
constrained renderer seams. Callers may opt into the canonical plugin protocol for
-bounded source syntax, immutable document transformation, and typed extension
-rendering. They may separately opt into dollar-delimited math by supplying one typed
+bounded source syntax, immutable document transformation, typed extension
+rendering, and native typed document-start frontmatter. They may separately opt into dollar-delimited math by supplying one typed
renderer for both inline and display expressions. The parser accepts matching
explicit options. Existing parsing, rendering, styling, and streaming behavior
remain unchanged when plugins and math are absent.
@@ -84,6 +84,9 @@ Consumer migration instructions belong in consumer docs and release notes.
rendering observe them.
- Sharing plugin-enabled parse configuration, transformed heading projection, and
collision-safe heading IDs with Markdown-derived Outline utilities.
+- Decoding an optional document-start frontmatter block into caller-defined typed
+ metadata, withholding unfinished frontmatter while streaming, and excluding
+ completed frontmatter syntax from rendered content.
**Does not own / non-goals**
@@ -108,8 +111,11 @@ node-kind narrowing. Released parser functions preserve their existing result sh
through a compatibility projection. Transforms return validated replacement roots
without entering parse identity. Every extension node introduced
by syntax or transformation has complete renderer ownership and a deterministic
-text projection. Text matching, semantic fences, and source decoration are helpers
-that compile to transforms rather than separate protocol phases. `spec:AST-036`
+text projection. Text matching, semantic fences, source decoration, and native
+frontmatter are helpers that compile to transforms rather than separate protocol
+phases. Frontmatter is document metadata: it has no renderer, uses a bounded
+first-party key/value grammar rather than Remark compatibility, and exposes typed
+metadata through the helper that created it. `spec:AST-036`
owns the shared protocol and limited Remark compatibility profile,
`module:Markdown/remark` owns that profile's adapter, and this component owns
aggregate application and fallback.
@@ -161,6 +167,7 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and
| FR21 | A transform runs again for every streamed update and must be idempotent and convergent; transforms whose effect requires complete input use the final-input signal. Semantically equal plugin lists reuse prepared work whether or not the array reference is stable, and development reports one diagnostic when a recreated list prevents reuse. |
| FR22 | An extension renderer may opt into the Markdown-owned extension theme target so themes reach plugin output. Opting out leaves output untargeted. The target adds no default styling or anatomy beyond the block spacing and content width Core already applies. |
| FR23 | Markdown owns an explicit supported dialect rather than claiming full CommonMark or GFM conformance. Adjacent compatible ordered or unordered items remain one list regardless of task-marker presence; each item independently preserves its checked state or ordinary list-item semantics, including at nested levels. The default grammar keeps its released task-list and table support, while `autolink: 'gfm'` adds only the documented autolink behavior and does not toggle any other syntax. |
+| FR24 | `createMarkdownFrontmatter()` recognizes only a leading `---` block of unique `key: value` lines, decodes it through the caller's typed parser, stores finite JSON-like metadata on the canonical document, and removes the syntax from rendered content. An unfinished leading block yields no visible Markdown while streaming; malformed or unfinished final input remains ordinary Markdown. Frontmatter has no renderer and requires no Remark compatibility. |
### Allowed variation
@@ -197,6 +204,7 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and
| Streaming math | Incomplete math is withheld; once complete, the streamed nodes equal the full-parse nodes at top level and inside list/blockquote containers. | Delimiters and expression text may arrive in separate chunks; source ranges remain optional. |
| Plugins omitted | Released parser unions, AST, DOM, targets, heading IDs, and performance remain unchanged. | Omitted or empty list; both are one empty transform pipeline. |
| Plugins enabled | Fixed syntax → immutable transform → render order, validated roots, readable fallback, and matching Markdown/Outline heading identity remain invariant. | Syntax, transforms, renderers, helper execution plans, plugin order, and live post-parse state. |
+| Native frontmatter | A complete leading block is absent from rendered content and yields typed metadata; unfinished streaming input is withheld. | Metadata schema and values are caller-defined finite data. |
### Transformation and precedence order
@@ -211,6 +219,10 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and
- Built-in syntax and protected contexts claim first; extension syntax claims only
eligible source; ordered transforms then receive deeply readonly document roots;
Core validates each returned root before rendering.
+- A configured native frontmatter helper claims only the document-start delimiter.
+ It withholds an unfinished block during streaming, removes a completed block
+ before later transforms render the document, and makes typed metadata available
+ to those later transforms and to callers of that helper.
- Text matching, semantic fences, and source decorations use transform helpers. Core
may compile those helpers into indexed internal plans without exposing additional
public phases.
@@ -324,6 +336,7 @@ and this change preserves the existing spelling exactly.
| FR19 | diagnostic-channel tests in development and production | every phase, advisory reports, rate suppression, no handler, malformed list, duplicate Core, version skew | A silent production failure, document content in a diagnostic, or one entrypoint throwing where another recovers. |
| FR20–FR22 | canonical/server imports, inference, streaming, preparation, theming tests | server imports, no explicit type args, chunk boundaries, recreated lists, themed/unthemed extensions | Client references, explicit-type workarounds, oscillation, per-render re-preparation, or unreachable opted-in output. |
| FR23 | parser, renderer, nesting, and public option tests | task-only, plain-only, and mixed ordered/unordered lists at top level and nested; autolink omitted/enabled | A mixed list splits or loses order/state, a plain item becomes a checkbox, or `autolink: 'gfm'` changes non-autolink syntax. |
+| FR24 | `plugins/frontmatter.test.tsx`, Storybook, and server rendering | complete, malformed, non-leading, LF/CRLF, unfinished streaming, full plugin stack | Metadata syntax renders after completion, unfinished syntax leaks while streaming, typing is lost, or later plugins stop composing. |
| Public syntax/types | `Markdown.public.test.ts`, core typecheck, and `Markdown.doc.mjs` | Legacy exhaustive switches, math opt-ins, inferred extension-node unions | A released union widens, an enabled union loses nodes, or docs drift from declarations. |
| Security/accessibility | `parser.test.ts`, `Markdown.test.tsx`, and renderer guidance | Inert expression strings and renderer-owned semantics | Astryx executes math as HTML or silently claims renderer-owned accessibility. |
@@ -394,6 +407,19 @@ Markdown's released grammar is an explicit Astryx-owned subset. Task-list marker
This keeps documents stable as Astryx adds or declines individual ecosystem features. It rejects a blanket CommonMark or GFM conformance claim, aggregate all-task/all-plain classification, an implicit whole-grammar mode switch, and silently enabling future GFM features under the existing autolink option.
+### DEC-5 — Frontmatter is typed document metadata
+
+**Reference:** `component:Markdown/DEC-5`
+**Decider:** `cixzhang`, `2026-09-19`
+
+Native frontmatter is a first-party helper in the ordered plugin pipeline. It
+recognizes only a leading delimited block, parses a deliberately small key/value
+grammar through a caller-provided typed decoder, and removes the syntax from the
+rendered document. It does not create a visual extension node or require Remark's
+frontmatter format. During streaming, incomplete frontmatter is withheld so raw
+metadata never flashes as content; once closed, later plugins can consume the
+metadata and the remaining document normally.
+
## Open questions
- **OQ1 — Which focused tests should pin target absence for the five remaining
diff --git a/packages/core/src/Markdown/plugins/frontmatter.test.tsx b/packages/core/src/Markdown/plugins/frontmatter.test.tsx
new file mode 100644
index 0000000000..2cbcd4f6d0
--- /dev/null
+++ b/packages/core/src/Markdown/plugins/frontmatter.test.tsx
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file frontmatter.test.tsx
+ * @input Native document-start frontmatter in complete and streaming documents
+ * @output Typed metadata, non-rendering, ordering, and failure coverage
+ * @position Acceptance tests for first-party Markdown frontmatter
+ */
+
+import {renderToString} from 'react-dom/server';
+import {describe, expect, expectTypeOf, it} from 'vitest';
+import {Markdown} from '../Markdown';
+import {parseMarkdownAst} from '../parser';
+import {createMarkdownPlugin, type MarkdownTransform} from './protocol';
+import {createMarkdownFrontmatter} from './frontmatter';
+
+const documentMetadata = createMarkdownFrontmatter({
+ name: 'document-metadata',
+ parse(fields) {
+ return {title: fields.title ?? '', draft: fields.draft === 'true'};
+ },
+});
+
+const SOURCE = '---\ntitle: Release notes\ndraft: true\n---\n# Shipped\n\nBody';
+
+describe('createMarkdownFrontmatter', () => {
+ it('removes document-start syntax and exposes typed metadata to later plugins', () => {
+ let seen: ReturnType<typeof documentMetadata.getMetadata>;
+ const observer = createMarkdownPlugin({
+ name: 'frontmatter-observer',
+ apiVersion: 1,
+ transform(root) {
+ seen = documentMetadata.getMetadata(root);
+ return root;
+ },
+ });
+ const root = parseMarkdownAst(SOURCE, {
+ plugins: [documentMetadata.plugin, observer],
+ });
+
+ expect(seen).toEqual({title: 'Release notes', draft: true});
+ expect(documentMetadata.parse(SOURCE)).toEqual({
+ status: 'match',
+ contentStart: SOURCE.indexOf('# Shipped'),
+ metadata: {title: 'Release notes', draft: true},
+ });
+ expect(documentMetadata.getMetadata(root)).toEqual(seen);
+ expect(root.children).toHaveLength(2);
+ expect(JSON.stringify(root)).not.toContain('title: Release notes');
+ expectTypeOf(documentMetadata.plugin).toMatchTypeOf<{
+ readonly name: string;
+ }>();
+ });
+
+ it('hides unfinished streaming frontmatter and exposes it once closed', () => {
+ const partial = parseMarkdownAst(
+ '---\ntitle: Pending',
+ {plugins: [documentMetadata.plugin]},
+ false,
+ );
+ expect(documentMetadata.getMetadata(partial)).toBeUndefined();
+ expect(partial.children).toEqual([]);
+
+ const settled = parseMarkdownAst(
+ SOURCE,
+ {plugins: [documentMetadata.plugin]},
+ false,
+ );
+ expect(documentMetadata.getMetadata(settled)).toEqual({
+ title: 'Release notes',
+ draft: true,
+ });
+ expect(settled.children[0]).toMatchObject({type: 'heading'});
+ expect(
+ documentMetadata.parse(
+ '---\r\ntitle: Windows\r\ndraft: false\r\n---\r\nBody',
+ ),
+ ).toMatchObject({
+ status: 'match',
+ metadata: {title: 'Windows', draft: false},
+ });
+ });
+
+ it('does not treat non-leading frontmatter syntax as metadata', () => {
+ expect(
+ documentMetadata.getMetadata(
+ parseMarkdownAst(`# Intro\n\n${SOURCE}`, {
+ plugins: [documentMetadata.plugin],
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('keeps renderer and server output free of metadata syntax', () => {
+ const html = renderToString(
+ <Markdown plugins={[documentMetadata.plugin]}>{SOURCE}</Markdown>,
+ );
+ expect(html).toContain('Shipped');
+ expect(html).toContain('Body');
+ expect(html).not.toContain('Release notes');
+ expect(html).not.toContain('draft');
+ });
+
+ it('rejects duplicate fields and unrepresentable decoded metadata', () => {
+ const duplicate = parseMarkdownAst(
+ '---\ntitle: One\ntitle: Two\n---\nBody',
+ {plugins: [documentMetadata.plugin]},
+ );
+ expect(documentMetadata.getMetadata(duplicate)).toBeUndefined();
+
+ const invalid = createMarkdownFrontmatter({
+ name: 'invalid',
+ parse: () => new Date() as never,
+ });
+ expect(() =>
+ parseMarkdownAst(SOURCE, {plugins: [invalid.plugin]}),
+ ).not.toThrow();
+ });
+
+ it('returns a transform plugin that composes in the ordered pipeline', () => {
+ expectTypeOf<MarkdownTransform>().toBeFunction();
+ const root = parseMarkdownAst(SOURCE, {plugins: [documentMetadata.plugin]});
+ expect(root.children[0]).toMatchObject({type: 'heading', depth: 1});
+ });
+});
diff --git a/packages/core/src/Markdown/plugins/frontmatter.ts b/packages/core/src/Markdown/plugins/frontmatter.ts
new file mode 100644
index 0000000000..1228a0d1a0
--- /dev/null
+++ b/packages/core/src/Markdown/plugins/frontmatter.ts
@@ -0,0 +1,198 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file frontmatter.ts
+ * @input Document-start frontmatter delimiters and a typed metadata decoder
+ * @output A Markdown plugin plus a typed metadata reader for later transforms
+ * @position Optional first-party document metadata helper
+ */
+
+import type {MarkdownAstRoot} from '../ast';
+import {
+ createMarkdownPlugin,
+ freezeMarkdownPluginData,
+ isMarkdownPluginData,
+ markMarkdownTransformTrusted,
+ type MarkdownExtensionNode,
+ type MarkdownPluginData,
+ type MarkdownPluginEntry,
+ type MarkdownTransform,
+} from './protocol';
+
+const ENVELOPE_KEY = 'astryx:frontmatter';
+const ENVELOPE_BRAND = 'astryx.markdown.frontmatter';
+const ENVELOPE_VERSION = 1;
+
+type FrontmatterRecord = Readonly<Record<string, string>>;
+type Envelope = {
+ readonly brand: typeof ENVELOPE_BRAND;
+ readonly version: typeof ENVELOPE_VERSION;
+ readonly values: Readonly<Record<string, MarkdownPluginData>>;
+};
+
+export interface MarkdownFrontmatterOptions<
+ Metadata extends MarkdownPluginData,
+> {
+ /** Stable plugin and metadata namespace. */
+ readonly name: string;
+ /** Converts validated key/value fields into typed document metadata. */
+ readonly parse: (fields: FrontmatterRecord) => Metadata;
+}
+
+export type MarkdownFrontmatterParseResult<
+ Metadata extends MarkdownPluginData,
+> =
+ | {readonly status: 'none'}
+ | {readonly status: 'defer'}
+ | {
+ readonly status: 'match';
+ readonly contentStart: number;
+ readonly metadata: Metadata;
+ };
+
+export interface MarkdownFrontmatter<Metadata extends MarkdownPluginData> {
+ readonly plugin: MarkdownPluginEntry<never>;
+ parse(
+ source: string,
+ isFinal?: boolean,
+ ): MarkdownFrontmatterParseResult<Metadata>;
+ getMetadata(
+ document: MarkdownAstRoot<MarkdownExtensionNode>,
+ ): Metadata | undefined;
+}
+
+type DataRecord = Readonly<Record<string, MarkdownPluginData>>;
+
+function asDataRecord(value: MarkdownPluginData | undefined): DataRecord {
+ return value != null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as DataRecord)
+ : {};
+}
+
+function parseEnvelope(value: unknown): Envelope | undefined {
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
+ return;
+ }
+ const candidate = value as Partial<Envelope>;
+ return candidate.brand === ENVELOPE_BRAND &&
+ candidate.version === ENVELOPE_VERSION &&
+ candidate.values != null &&
+ typeof candidate.values === 'object' &&
+ !Array.isArray(candidate.values)
+ ? (candidate as Envelope)
+ : undefined;
+}
+
+function readFrontmatter(source: string):
+ | {readonly status: 'none'}
+ | {readonly status: 'defer'}
+ | {
+ readonly status: 'match';
+ readonly end: number;
+ readonly fields: FrontmatterRecord;
+ } {
+ const openingLength = source.startsWith('---\r\n')
+ ? 5
+ : source.startsWith('---\n')
+ ? 4
+ : 0;
+ if (openingLength === 0) {
+ return {status: 'none'};
+ }
+ const body = source.slice(openingLength);
+ const close = /(?:^|\r?\n)---(?=\r?\n|$)/.exec(body);
+ if (close == null) {
+ return {status: 'defer'};
+ }
+ const fields: Record<string, string> = Object.create(null);
+ for (const line of body.slice(0, close.index).split(/\r?\n/)) {
+ if (line.trim() === '') {
+ continue;
+ }
+ const separator = line.indexOf(':');
+ const key = line.slice(0, separator).trim();
+ if (separator <= 0 || key === '' || Object.hasOwn(fields, key)) {
+ return {status: 'none'};
+ }
+ fields[key] = line.slice(separator + 1).trim();
+ }
+ let end = openingLength + close.index + close[0].length;
+ if (source.startsWith('\r\n', end)) {
+ end += 2;
+ } else if (source[end] === '\n') {
+ end += 1;
+ }
+ return {status: 'match', end, fields: Object.freeze(fields)};
+}
+
+export function createMarkdownFrontmatter<Metadata extends MarkdownPluginData>(
+ options: MarkdownFrontmatterOptions<Metadata>,
+): MarkdownFrontmatter<Metadata> {
+ if (options.name.trim() === '') {
+ throw new TypeError('Markdown frontmatter name must be non-empty');
+ }
+ const name = options.name;
+ const parse = (
+ source: string,
+ isFinal = true,
+ ): MarkdownFrontmatterParseResult<Metadata> => {
+ const parsed = readFrontmatter(source);
+ if (parsed.status === 'defer') {
+ return isFinal ? {status: 'none'} : parsed;
+ }
+ if (parsed.status === 'none') {
+ return parsed;
+ }
+ const metadata = options.parse(parsed.fields);
+ if (!isMarkdownPluginData(metadata)) {
+ throw new TypeError(
+ 'Markdown frontmatter metadata must be finite JSON-like data',
+ );
+ }
+ return {
+ status: 'match',
+ contentStart: parsed.end,
+ metadata: freezeMarkdownPluginData(metadata),
+ };
+ };
+ const transform: MarkdownTransform<never> = (document, context) => {
+ const parsed = parse(context.source, context.isFinal);
+ if (parsed.status === 'none') {
+ return document;
+ }
+ if (parsed.status === 'defer') {
+ return {...document, children: []};
+ }
+ const documentData = asDataRecord(document.data);
+ const prior = parseEnvelope(documentData[ENVELOPE_KEY]);
+ const envelope: Envelope = Object.freeze({
+ brand: ENVELOPE_BRAND,
+ version: ENVELOPE_VERSION,
+ values: Object.freeze({
+ ...prior?.values,
+ [name]: parsed.metadata,
+ }),
+ });
+ return {
+ ...document,
+ data: Object.freeze({...documentData, [ENVELOPE_KEY]: envelope}),
+ children: document.children.filter(
+ node => (node.position?.end.offset ?? Infinity) > parsed.contentStart,
+ ),
+ };
+ };
+ const plugin = createMarkdownPlugin({
+ name,
+ apiVersion: 1,
+ transform: markMarkdownTransformTrusted(transform),
+ });
+ return Object.freeze({
+ plugin,
+ parse,
+ getMetadata(document: MarkdownAstRoot<MarkdownExtensionNode>) {
+ const data = asDataRecord(document.data);
+ return parseEnvelope(data[ENVELOPE_KEY])?.values[name] as
+ Metadata | undefined;
+ },
+ });
+}
diff --git a/packages/core/src/Markdown/plugins/index.ts b/packages/core/src/Markdown/plugins/index.ts
index 3e3209ea6a..44e9c91351 100644
--- a/packages/core/src/Markdown/plugins/index.ts
+++ b/packages/core/src/Markdown/plugins/index.ts
@@ -27,6 +27,12 @@ export type {
MarkdownSourceDecorationOptions,
MarkdownSourceDecorationRange,
} from './sourceDecoration';
+export {createMarkdownFrontmatter} from './frontmatter';
+export type {
+ MarkdownFrontmatter,
+ MarkdownFrontmatterOptions,
+ MarkdownFrontmatterParseResult,
+} from './frontmatter';
export type {
MarkdownPluginData,
MarkdownExtensionNode,