Skip to content

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

TypeScript

feat(markdown): add limited Remark adapter (#6345)

Cindy Zhang2acc24feb5a8
diff --git a/.changeset/markdown-remark-adapter.md b/.changeset/markdown-remark-adapter.md
new file mode 100644
index 0000000000..ea08c06f70
--- /dev/null
+++ b/.changeset/markdown-remark-adapter.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Markdown: add a limited Remark compatibility adapter
+
+Import `createMarkdownRemarkTransform()` from `@astryxdesign/core/Markdown/remark` to run one synchronous transform-only Remark plugin over the documented MDAST subset. Every invocation gets a fresh mutable tree and an isolated file, and each plugin's compatibility is proven by fixtures rather than assumed: async work, parser or compiler plugins, processor state, raw HTML, unsupported nodes, forged positions, and metadata Astryx cannot represent keep the last valid readable document and report one diagnostic. The adapter is a separate entry point, so it stays out of every bundle that does not import it.
+
+@cixzhang
diff --git a/apps/storybook/stories/Markdown.demoPlugins.tsx b/apps/storybook/stories/Markdown.demoPlugins.tsx
index 5048f31d47..b520164d99 100644
--- a/apps/storybook/stories/Markdown.demoPlugins.tsx
+++ b/apps/storybook/stories/Markdown.demoPlugins.tsx
@@ -106,7 +106,11 @@ const calloutDefinition = {
},
renderers: {
callout: {
- render: ({node}) => <aside aria-label="Note">{node.data.body}</aside>,
+ render: ({node}) => (
+ <aside role="note" aria-label="Note">
+ {node.data.body}
+ </aside>
+ ),
toText: node => node.data.body,
},
},
diff --git a/apps/storybook/stories/Markdown.remarkPlugins.tsx b/apps/storybook/stories/Markdown.remarkPlugins.tsx
new file mode 100644
index 0000000000..df327e1f2d
--- /dev/null
+++ b/apps/storybook/stories/Markdown.remarkPlugins.tsx
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Markdown.remarkPlugins.tsx
+ * @input Synchronous transform-only Remark plugins in Unified's attacher shape
+ * @output Storybook-only adapted plugins: one compatible, two outside the profile
+ * @position Documentation fixtures for the limited Remark compatibility profile
+ */
+
+import {
+ createMarkdownPlugin,
+ createMarkdownTextTransform,
+ type MarkdownExtensionNode,
+} from '@astryxdesign/core/Markdown/plugins';
+import {createMarkdownRemarkTransform} from '@astryxdesign/core/Markdown/remark';
+import type {MarkdownRemarkPlugin} from '@astryxdesign/core/Markdown/remark';
+
+type DemoNode = {
+ type: string;
+ children?: DemoNode[];
+ [key: string]: unknown;
+};
+
+function walk(node: DemoNode, visitor: (node: DemoNode) => void): void {
+ visitor(node);
+ for (const entry of [...(node.children ?? [])]) {
+ walk(entry, visitor);
+ }
+}
+
+const SPEC_PATTERN = /\bSPEC-\d+\b/;
+
+/**
+ * Compatible: turns `SPEC-1234` prose into a link. Astryx still owns the
+ * destination, so the rendered link goes through the same navigation policy as
+ * an authored one. Prose already claimed by another plugin never reaches it.
+ */
+const remarkSpecLinks: MarkdownRemarkPlugin<[{basePath: string}]> =
+ ({basePath}) =>
+ tree => {
+ walk(tree as unknown as DemoNode, node => {
+ if (node.children == null || node.type === 'link') {
+ return;
+ }
+ node.children = node.children.flatMap(entry => {
+ if (entry.type !== 'text' || typeof entry.value !== 'string') {
+ return [entry];
+ }
+ const parts = entry.value.split(
+ new RegExp(`(${SPEC_PATTERN.source})`, 'g'),
+ );
+ if (parts.length === 1) {
+ return [entry];
+ }
+ return parts
+ .filter(part => part !== '')
+ .map(part =>
+ new RegExp(`^${SPEC_PATTERN.source}$`).test(part)
+ ? {
+ type: 'link',
+ url: `${basePath}/${part.slice('SPEC-'.length)}`,
+ title: null,
+ children: [{type: 'text', value: part}],
+ }
+ : {type: 'text', value: part},
+ );
+ });
+ });
+ };
+
+/** Outside the profile: raw HTML has no Astryx representation. */
+const remarkRawHtml: MarkdownRemarkPlugin = () => tree => {
+ (tree as unknown as DemoNode).children?.push({
+ type: 'html',
+ value: '<button onclick="alert(1)">Injected</button>',
+ });
+};
+
+/** Outside the profile: the navigation owner rejects the destination. */
+const remarkUnsafeLinks: MarkdownRemarkPlugin = () => tree => {
+ walk(tree as unknown as DemoNode, node => {
+ if (node.type === 'link') {
+ node.url = 'javascript:alert(1)';
+ }
+ });
+};
+
+type SpecBadgeNode = MarkdownExtensionNode<
+ 'demo-spec-badges',
+ 'badge',
+ {readonly label: string},
+ 'inline'
+>;
+
+/**
+ * Native counterpart claiming the same prose as `remarkSpecLinks`, so the two
+ * compete for one input and the ordered list decides which one gets it.
+ */
+export const specBadgePlugin = createMarkdownPlugin<
+ 'demo-spec-badges',
+ SpecBadgeNode
+>({
+ name: 'demo-spec-badges',
+ apiVersion: 1,
+ transform: createMarkdownTextTransform<SpecBadgeNode>({
+ pattern: new RegExp(SPEC_PATTERN.source, 'g'),
+ requiredSubstrings: ['SPEC-'],
+ replace: match => ({
+ type: 'extension',
+ plugin: 'demo-spec-badges',
+ name: 'badge',
+ display: 'inline',
+ data: {label: match[0]},
+ }),
+ }),
+ renderers: {
+ badge: {
+ render: ({node}) => <mark data-spec-badge>{node.data.label}</mark>,
+ toText: node => node.data.label,
+ },
+ },
+});
+
+export const remarkSpecLinkPlugin = createMarkdownPlugin({
+ name: 'demo-remark-spec-links',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkSpecLinks, {
+ basePath: '/specs',
+ }),
+});
+
+export const remarkRawHtmlPlugin = createMarkdownPlugin({
+ name: 'demo-remark-raw-html',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkRawHtml),
+});
+
+export const remarkUnsafeLinkPlugin = createMarkdownPlugin({
+ name: 'demo-remark-unsafe-links',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkUnsafeLinks),
+});
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index 13a64aa11d..a844c9df22 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -7,12 +7,19 @@ import type {MarkdownComponents} from '@astryxdesign/core/Markdown';
import {Button} from '@astryxdesign/core/Button';
import {Link} from '@astryxdesign/core/Link';
import {Text} from '@astryxdesign/core/Text';
+import {expect, userEvent, within} from 'storybook/test';
import {
createDelayedMarkdownDemoPlugin,
createSourceDecorationDemo,
markdownDemoPlugins,
markdownSemanticFenceDemoPlugin,
} from './Markdown.demoPlugins';
+import {
+ remarkRawHtmlPlugin,
+ remarkSpecLinkPlugin,
+ remarkUnsafeLinkPlugin,
+ specBadgePlugin,
+} from './Markdown.remarkPlugins';
const meta: Meta<typeof Markdown> = {
title: 'Core/Markdown',
@@ -567,3 +574,175 @@ export const SourceDecoration: Story = {
);
},
};
+
+const nativeAndRemarkSource = [
+ '# Plugin composition',
+ '',
+ 'Hello @{Ada}. TODO becomes a transform-owned node, and SPEC-4821 is claimed',
+ 'by whichever plugin runs first, next to an [Authored link](/people).',
+ '',
+ ':::note',
+ 'Native syntax and an adapted Remark transform share one ordered list.',
+ ':::',
+ '',
+ 'Protected contexts stay literal: `TODO @{Linus} SPEC-9999`.',
+ '',
+ '```txt',
+ 'SPEC-9999 stays copyable',
+ '```',
+].join('\n');
+
+/**
+ * Both plugins claim `SPEC-4821`, so whichever runs first consumes it and the
+ * second sees output it must leave alone: a badge is an owned extension node,
+ * and link children are a protected context.
+ */
+const nativeFirst = [
+ ...markdownDemoPlugins,
+ specBadgePlugin,
+ remarkSpecLinkPlugin,
+];
+const remarkFirst = [
+ ...markdownDemoPlugins,
+ remarkSpecLinkPlugin,
+ specBadgePlugin,
+];
+
+export const NativeAndRemarkPlugins: Story = {
+ name: 'Native and Remark plugins',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Native syntax plugins and one adapted synchronous Remark transform run in the same ordered list, and the order decides the outcome. Both claim SPEC-4821: running the native badge first leaves the Remark transform nothing to link, and running the Remark transform first puts the text inside a link, which the native helper treats as a protected context. Astryx keeps ownership of the transformed destination, and code stays copyable either way.',
+ },
+ },
+ },
+ render: () => (
+ <div style={{display: 'grid', gap: 24, maxWidth: 680}}>
+ <section data-order="native-first">
+ <Text>Native badge plugin first</Text>
+ <Markdown plugins={nativeFirst}>{nativeAndRemarkSource}</Markdown>
+ </section>
+ <section data-order="remark-first">
+ <Text>Adapted Remark plugin first</Text>
+ <Markdown plugins={remarkFirst}>{nativeAndRemarkSource}</Markdown>
+ </section>
+ </div>
+ ),
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const pane = (order: string): HTMLElement => {
+ const element = canvasElement.querySelector<HTMLElement>(
+ `[data-order="${order}"]`,
+ );
+ if (element == null) {
+ throw new Error(`missing pane: ${order}`);
+ }
+ return element;
+ };
+ const nativeFirstPane = within(pane('native-first'));
+ const remarkFirstPane = within(pane('remark-first'));
+
+ // Native syntax and transform plugins still own their own nodes.
+ await expect(nativeFirstPane.getByText('@Ada')).toBeInTheDocument();
+ await expect(nativeFirstPane.getByLabelText('Note')).toBeInTheDocument();
+ await expect(nativeFirstPane.getByText('TODO')).toBeInTheDocument();
+
+ // Native first: the badge consumed the prose, so no link was produced.
+ const badge = nativeFirstPane.getByText('SPEC-4821');
+ await expect(badge).toHaveAttribute('data-spec-badge');
+ await expect(
+ nativeFirstPane.queryByRole('link', {name: 'SPEC-4821'}),
+ ).not.toBeInTheDocument();
+
+ // Reversed: the Remark transform consumed it, and the native helper left
+ // the link's children alone — so the same source renders differently.
+ const specLink = remarkFirstPane.getByRole('link', {name: 'SPEC-4821'});
+ await expect(specLink).toHaveAttribute('href', '/specs/4821');
+ await expect(remarkFirstPane.getByText('SPEC-4821')).not.toHaveAttribute(
+ 'data-spec-badge',
+ );
+
+ // Protected contexts and copyable code are untouched in both orders.
+ await expect(canvas.getAllByText('TODO @{Linus} SPEC-9999')).toHaveLength(
+ 2,
+ );
+ await expect(canvas.getAllByText('SPEC-9999 stays copyable')).toHaveLength(
+ 2,
+ );
+
+ // Keyboard order follows document order: the transformed link is an
+ // ordinary tab stop that hands focus on to the authored link.
+ await expect(
+ remarkFirstPane.getAllByRole('link').map(link => link.textContent),
+ ).toEqual(['SPEC-4821', 'Authored link']);
+ specLink.focus();
+ await expect(specLink).toHaveFocus();
+ await userEvent.tab();
+ await expect(
+ remarkFirstPane.getByRole('link', {name: 'Authored link'}),
+ ).toHaveFocus();
+ },
+};
+
+export const RemarkOutsideTheProfile: Story = {
+ name: 'Remark outside the profile',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A plugin that emits raw HTML or a rejected destination falls closed: the last valid document stays readable, no markup is injected, and the authored destination survives.',
+ },
+ },
+ },
+ render: () => (
+ <div style={{maxWidth: 680}}>
+ <Markdown plugins={[remarkRawHtmlPlugin, remarkUnsafeLinkPlugin]}>
+ {
+ '# Still readable\n\nProse survives with its [authored link](/people).'
+ }
+ </Markdown>
+ </div>
+ ),
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByRole('heading', {name: 'Still readable'}),
+ ).toBeInTheDocument();
+ await expect(
+ canvas.getByRole('link', {name: 'authored link'}),
+ ).toHaveAttribute('href', '/people');
+ await expect(canvas.queryByText('Injected')).not.toBeInTheDocument();
+ },
+};
+
+export const PluginsOmittedBaseline: Story = {
+ name: 'Plugins omitted baseline',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'The same source without plugins. Extension syntax stays literal, no badge or transformed link exists, so opting in is the only thing that changes behavior.',
+ },
+ },
+ },
+ render: () => (
+ <div style={{maxWidth: 680}}>
+ <Markdown>{nativeAndRemarkSource}</Markdown>
+ </div>
+ ),
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.queryByRole('link', {name: 'SPEC-4821'}),
+ ).not.toBeInTheDocument();
+ await expect(canvas.queryByLabelText('Note')).not.toBeInTheDocument();
+ await expect(canvas.getByText(/Hello @\{Ada\}/)).toBeInTheDocument();
+ await expect(
+ canvas.getByRole('link', {name: 'Authored link'}),
+ ).toBeInTheDocument();
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index 973508e27d..e5c4031067 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -658,6 +658,11 @@
"source": "./src/Typeahead/utils.ts",
"types": "./dist/Typeahead/utils.d.ts",
"default": "./dist/Typeahead/utils.js"
+ },
+ "./Markdown/remark": {
+ "source": "./src/Markdown/remark.ts",
+ "types": "./dist/Markdown/remark.d.ts",
+ "default": "./dist/Markdown/remark.js"
}
},
"files": [
diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjs
index 62966517be..451cb77432 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:
+ "Import createMarkdownRemarkTransform from '@astryxdesign/core/Markdown/remark' only to reuse an existing synchronous transform-only Remark plugin; it stays out of every other bundle. Prove each plugin with fixtures: anything outside the supported MDAST subset — async work, parser or compiler plugins, processor state, raw HTML, unsupported nodes, forged positions, or metadata Astryx cannot represent — keeps the last valid document and reports one diagnostic.",
+ },
{
guidance: true,
description:
@@ -415,6 +420,38 @@ const readDecorations = createMarkdownPlugin({
});
<Markdown plugins={[searchHits, readDecorations]}>{source}</Markdown>;
+`,
+ },
+ {
+ label: 'Compatible Remark plugin',
+ code: `
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {createMarkdownPlugin} from '@astryxdesign/core/Markdown/plugins';
+import {createMarkdownRemarkTransform} from '@astryxdesign/core/Markdown/remark';
+
+// A synchronous transform-only Remark plugin in the usual attacher shape.
+const remarkRename =
+ ({from, to}) =>
+ tree => {
+ const rename = node => {
+ if (node.type === 'text') {
+ node.value = node.value.split(from).join(to);
+ }
+ node.children?.forEach(rename);
+ };
+ rename(tree);
+ };
+
+const productName = createMarkdownPlugin({
+ name: 'product-name',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkRename, {
+ from: 'Astryx',
+ to: 'Astryx Design',
+ }),
+});
+
+<Markdown plugins={[productName]}># Astryx release notes</Markdown>;
`,
},
{
@@ -660,6 +697,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:
+ "Import createMarkdownRemarkTransform from '@astryxdesign/core/Markdown/remark' only to reuse an existing synchronous transform-only Remark plugin; it stays out of every other bundle. Prove each plugin with fixtures: anything outside the supported MDAST subset — async work, parser or compiler plugins, processor state, raw HTML, unsupported nodes, forged positions, or metadata Astryx cannot represent — keeps the last valid document and reports one diagnostic.",
+ },
{
guidance: true,
description:
@@ -727,6 +769,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:
+ "Import createMarkdownRemarkTransform from '@astryxdesign/core/Markdown/remark' only to reuse a synchronous transform-only Remark plugin; it stays out of every other bundle and unsupported behavior keeps the last valid document with one diagnostic.",
+ },
{
guidance: true,
description:
diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.md
index 18bc018611..88123cfc6f 100644
--- a/packages/core/src/Markdown/Markdown.spec.md
+++ b/packages/core/src/Markdown/Markdown.spec.md
@@ -16,11 +16,12 @@ verified_by:
packages/core/src/Markdown/Markdown.public.test.ts,
packages/core/src/Markdown/parser.test.ts,
packages/core/src/Markdown/incremental.test.ts,
+ packages/core/src/Markdown/remark.test.tsx,
packages/core/src/Outline/parseOutlineFromMarkdown.test.ts,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
]
-modules: []
+modules: [module:Markdown/remark]
families: [family:navigation-destinations]
design_specs: []
architecture:
@@ -109,8 +110,9 @@ 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`
-owns the shared protocol and limited Remark compatibility profile; this component
-owns aggregate application and fallback.
+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.
### Acceptance and implementation state
@@ -303,6 +305,8 @@ and this change preserves the existing spelling exactly.
- `spec:AST-036` owns the opaque syntax/transform/renderer protocol, immutable AST
validation, limited Remark compatibility, performance, and resource boundaries.
This record owns aggregate Markdown behavior in FR12–FR22;
+ `module:Markdown/remark` owns the separately imported Remark adapter's
+ supported subset, rejections, and diagnostics; and
`module:Outline/parseOutlineFromMarkdown` owns the corresponding Outline
projection.
- Nested Astryx primitives retain ownership of their own anatomy and targets;
diff --git a/packages/core/src/Markdown/modules/remark.spec.md b/packages/core/src/Markdown/modules/remark.spec.md
new file mode 100644
index 0000000000..3d6b3ed562
--- /dev/null
+++ b/packages/core/src/Markdown/modules/remark.spec.md
@@ -0,0 +1,269 @@
+---
+schema_version: 3
+template_version: 2
+kind: module
+id: module:Markdown/remark
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: cixzhang
+approved_at: 2026-09-15
+owners: [cixzhang]
+review_triggers: [public-api, behavior]
+verified_by: [packages/core/src/Markdown/remark.test.tsx]
+parent_component: component:Markdown
+references: [architecture:public-component-api, spec:AST-036/DEC-3]
+---
+
+# remark module contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `createMarkdownRemarkTransform(plugin, ...settings)` in the separate `@astryxdesign/core/Markdown/remark` entry point returns one Markdown transform for `createMarkdownPlugin()`. It accepts a conventional Unified/Remark plugin type as well as an Astryx-authored one. |
+| Behavior | Each invocation runs one synchronous transform-only Remark plugin over a fresh mutable copy of the canonical tree with an isolated constrained file, then accepts a lossless round trip or rejects it. |
+| End-user impact | Readers see either the plugin's supported transformation or the last valid readable document; unsupported behavior can never silently drop, approximate, or forge document content. |
+| Builder impact | Builders who import nothing are unaffected. An opt-in builder imports the adapter, proves one plugin compatible with fixtures, and reads one diagnostic when a plugin leaves the profile. |
+| Compatibility/readiness | Additive and opt-in; absent from Markdown's entry point and from parser-only or server bundles unless imported. Compatibility is per plugin evidence, never package identity. |
+| Review checks | Reject silent approximation, dropped fields, restored or rebuilt provenance, authored or shifted positions, edited Astryx owned nodes, raw-markup channels, async or processor-state plugins, plugin-authored diagnostic text, a refusal a plugin can catch and continue past, an unhandled rejection, or adapter imports inside Markdown or the parser. |
+| Governing rules | [`spec:AST-036` FR18–FR20, FR24](../../../../../docs/specs/AST-036/spec.md); [`component:Markdown` FR12–FR16](../Markdown.spec.md); [`architecture:public-component-api`](../../../../../docs/architecture/public-component-api.md). |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+Teams with existing Remark transforms should be able to reuse a compatible one
+inside Astryx Markdown without adopting Unified as a Core runtime, mutating the
+canonical tree, or weakening Core-owned semantics. This module owns that narrow
+compatibility boundary: what the profile accepts, what it refuses, and how a
+refusal stays readable.
+
+Everything outside the profile fails closed. "Remark-compatible" is a claim a
+plugin earns from fixtures in this module's tests, never from a package name.
+
+## Compatibility and migration
+
+- Released default preserved: `yes`
+- Compatibility class: additive, opt-in, separately imported; no released
+ Markdown, parser, Outline, or bundle behavior changes when the adapter is not
+ imported
+- Migration decision: `spec:AST-036/DEC-3`
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The adapter's public factory, its mutable Remark tree types, and its
+ constrained file type.
+- The supported-subset round trip and the exact rejection conditions below.
+- The isolated per-invocation copy, file data, and diagnostics.
+- Its own evidence that one real plugin is compatible.
+
+**Does not own / non-goals**
+
+- Plugin admission, transform ordering, validation, and failure recovery —
+ owned by `component:Markdown` and `spec:AST-036`.
+- Unified processors, parser or compiler registration, micromark extensions,
+ async pipelines, and `VFile` behavior beyond the constrained file.
+- Heading identity, navigation, resource policy, list, table, and document
+ semantics — owned by Core.
+
+## Public API and concepts
+
+| Concept | Closed values or states | Meaning | Default | Owner | Stability |
+| ------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ------------------------ | --------- |
+| `createMarkdownRemarkTransform` | `(plugin, ...settings) => MarkdownTransform` | Adapts one attacher-shaped Remark plugin; the attacher runs once, its transformer per run. | none | `module:Markdown/remark` | stable |
+| Adapted tree | supported MDAST subset plus Astryx flow image, citation, extension | A fresh mutable copy the plugin may mutate or replace. | fresh per run | `module:Markdown/remark` | stable |
+| Constrained file | `value`, `data`, `messages`, `message()`, `fail()`, `toString()` | Readonly source, per-run JSON-like data, and diagnostics. | empty `data` | `module:Markdown/remark` | stable |
+| Accepted plugin type | `MarkdownRemarkPlugin` or `MarkdownRemarkCompatiblePlugin` | A new plugin may be authored against typed Astryx trees; a conventional Unified/Remark plugin type is accepted structurally, including a declared async or callback-style transformer that the run time then rejects. | structural | `module:Markdown/remark` | stable |
+| Rejection | one diagnostic plus the last valid document | The fail-closed result for anything outside the profile. | not applicable | `module:Markdown/remark` | stable |
+
+## Behavioral contract
+
+| ID | Invariant | Basis |
+| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
+| FR1 | The adapter accepts only a plugin whose attacher synchronously returns one transformer of at most two parameters. A parser, compiler, async, callback-style, or registration-only plugin is rejected. | `spec:AST-036` FR18 |
+| FR2 | Every invocation receives a fresh mutable copy of the canonical tree and a new constrained file. No canonical node, array, data value, or position is mutable, and no state survives between runs. | `spec:AST-036` FR10, FR18 |
+| FR3 | The constrained file exposes exactly `value`, `data`, `messages`, `message()`, `fail()`, and `toString()`. Every other key — `path`, `cwd`, `history`, or any other — fails closed on read, write, define, and delete, rather than answering `undefined`; `in` and key enumeration answer truthfully so a plugin can feature-detect. Processor access fails closed the same way. | `spec:AST-036` FR18 |
+| FR4 | A returned or mutated tree is accepted only when every node and metadata field round-trips losslessly through the supported subset, fenced-code `meta` included; otherwise the last valid document is preserved. | `spec:AST-036` FR19 |
+| FR5 | A surviving source-backed node keeps Core's provenance exactly: every line, column, and offset on both points must come back unchanged. A rebuilt, retyped, duplicated, or shifted surviving node is rejected, never silently restored. Source-backed nodes, including headings, may be removed or reordered; a surviving source heading keeps its depth. | `spec:AST-036` FR11, FR19, FR26 |
+| FR6 | Astryx-owned citation and plugin extension nodes pass through only when every owned field — including `data` and authored `source` — is exactly equal. Authoring or editing one through the adapter is rejected. | `spec:AST-036` FR11, FR15 |
+| FR7 | A failed run reports exactly one diagnostic, assembled only from the adapter's own vocabulary and read from adapter-owned state, never from the thrown value or any object the plugin can rewrite. Text a plugin authored — a thrown error, a `fail()` reason, a `message()` diagnostic — never becomes a diagnostic, because the plugin read the document and may quote it. Any refusal the plugin catches and continues past still fails the run, and the first recorded reason is the one reported. Later plugins and rendering continue on the last valid document. | `spec:AST-036` FR12 |
+| FR8 | An unchanged document returns the identical canonical root, so an adapted no-op costs no tree allocation and no downstream invalidation. | `spec:AST-036` FR13, FR21 |
+| FR9 | The adapter is a separate entry point that Markdown, the parser, and the plugin protocol never import, so parser-only and server bundles exclude it unless a caller imports it. It is registered in the exports generator, so the published subpath cannot drift from the source. | `spec:AST-036` FR24 |
+| FR10 | A conventional Unified/Remark plugin type-checks at the callsite without being rewritten, including a transformer that declares Unified's callback parameter or an asynchronous return union. The run time still rejects an actual promise and a callback-style transformer. | `spec:AST-036` FR18 |
+| FR11 | A promise the adapter refuses — from the attacher or the transformer — gets a rejection handler attached before any other verdict is applied, so a result that is both refused for another reason and rejected cannot surface as an unhandled rejection. That matters most on the server, where an unhandled rejection ends the process by default and would print a plugin-authored reason drawn from the document. `then` is read exactly once, because reading it can itself throw or trip a guard. | `spec:AST-036` FR12, FR18 |
+| FR12 | Sticky refusal is re-checked immediately before validated output becomes observable, so a guard that fires late — inside a hostile `then` accessor, or a getter read while the result is validated — still rejects rather than letting the plugin's output through. | `spec:AST-036` FR12 |
+
+### Supported round trip
+
+| Input | Round trip |
+| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `root`, `paragraph`, `heading`, `blockquote`, `thematicBreak` | Structure and children; heading depth stays Core-owned. |
+| `text`, `strong`, `emphasis`, `delete`, `inlineCode`, `break` | Values and ordered phrasing children. |
+| `link`, `image` | `url` revalidated by the navigation and resource owners; `alt` required; `title` null. |
+| `list`, `listItem` | `ordered`, `start`, `spread`, Astryx `delimiter`, and `checked`. |
+| `code` | `lang` and `meta`, each `null` when absent, plus `value`. The authored info string survives both conversions and the released language projection is preserved. |
+| `math`, `inlineMath` | Present only when the caller enabled math. |
+| `table`, `tableRow`, `tableCell` | Normalized `align` and cell children. |
+| Astryx flow image, `citation`, `extension` | Preserved as owned nodes; readable by the plugin, not writable. |
+| `position`, `data` | Core-authored positions and finite JSON-like data. |
+
+### Rejection matrix
+
+| Rejected input | Result |
+| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
+| Async, callback-style, registration-only, or processor-state plugin | Last valid document plus one diagnostic; FR1, FR3 |
+| `html` or any node outside the supported subset (definitions, references, footnotes, frontmatter, directives, MDX) | Last valid document plus one diagnostic; FR4 |
+| An unsupported field, `hName`, `hProperties`, `hChildren`, or non-JSON node or file data | Last valid document plus one diagnostic; FR3, FR4 |
+| Non-string fence `meta`, a link or image `title`, a loose list item, or a ragged transformed table | Last valid document plus one diagnostic; FR4 |
+| Reading, writing, defining, or deleting an unsupported file key — `path`, `cwd`, `history`, or any other | Last valid document plus one diagnostic; FR3 |
+| An authored, shifted, or removed position on a surviving source-backed node; a rebuilt, retyped, or duplicated source node; or a re-levelled source heading | Last valid document plus one diagnostic; FR5 |
+| A shifted line or column on an otherwise unchanged offset | Last valid document plus one diagnostic; FR5 |
+| Provenance rebuilt from a copied position, or smuggled in from another document | Last valid document plus one diagnostic; FR5 |
+| An authored or edited Astryx citation or extension node, `data` and `source` included | Last valid document plus one diagnostic; FR6 |
+| A rejected link or image URL, invalid built-in structure, a nested link, or block output from an inline entry point | Last valid document plus one diagnostic; FR4 |
+| A transformer that throws, or any refusal the plugin caught and continued past, `fail()` included | Last valid document plus one diagnostic; FR7 |
+| A rejected promise from the attacher or transformer, alone or on top of a caught refusal | Last valid document, one diagnostic, no unhandled rejection; FR11 |
+| A guard that fires late, inside a `then` accessor or a getter read during validation | Last valid document plus one diagnostic; FR12 |
+
+### Transformation and precedence order
+
+- **ORD1 — one run.** Canonical tree → fresh mutable copy → the plugin's single
+ synchronous transformer → validated round trip → the document later plugins
+ and rendering observe. Core validates the result again; the adapter never
+ substitutes for Core's own validation.
+- **ORD2 — one diagnostic, adapter-authored.** A successful run is silent;
+ Core's only diagnostic channel reports plugin failure, so there is nothing
+ truthful to say. A failed run reports exactly one line, built from this
+ module's own vocabulary. Messages a plugin recorded stay on its file, which
+ only the plugin sees.
+- **ORD3 — defuse, then judge, then accept.** A returned value is inspected
+ and defused before any verdict is applied, so the reason a run is refused
+ never decides whether a promise is left dangling. Sticky refusal is checked
+ again immediately before output is accepted, because a guard can fire at any
+ point the adapter touches plugin-controlled values.
+
+### Performance and resources
+
+- **PR1 — one copy per invocation.** Work is proportional to document size once
+ per run; an unchanged document returns the canonical root itself.
+- **PR2 — no runtime dependency.** The adapter adds no Unified, Remark, mdast,
+ or `VFile` dependency and no parse work; it runs inside the existing transform
+ phase and cannot trigger reparsing.
+
+## Accessibility contract
+
+- **AR1 — required meaning survives.** An image must keep its text alternative
+ and a source heading its level, so a rejection is preferred over an
+ accessible-name or document-outline regression.
+- **AR2 — no markup channel.** Raw HTML and hast property channels are rejected,
+ so an adapted plugin cannot inject unlabeled or non-semantic output.
+
+## Design relationships
+
+No visual representation is owned by this compatibility adapter; adapted output
+renders through Markdown's existing parts.
+
+## Parent and system relationships
+
+- `component:Markdown` owns aggregate plugin application, validation, fallback,
+ and heading identity.
+- `spec:AST-036` owns the protocol, the canonical MDAST compatibility matrix,
+ and the limited Remark profile this record implements.
+- `family:navigation-destinations` keeps ownership of every adapted link
+ destination and image resource.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| -------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
+| FR1–FR3 | `remark.test.tsx` attachment, isolation, and constrained-file fixtures | async, callback-style, processor-state, registration-only plugins; repeated invocations; every unsupported file key, read and written; caught guard refusals | Accepting one of them, leaking file data between runs, or letting a caught refusal clear the verdict fails the fixtures. |
+| FR4–FR6 | `remark.test.tsx` round-trip and rejection matrix, including a parsed-fence identity fixture | every supported node kind; fences with and without an info string; each rejected input above; owned citation and extension nodes | A silently dropped field — `meta` included — an accepted unsupported node, or an edited owned node fails closed fixtures. |
+| FR7 | `remark.test.tsx` diagnostics plus Markdown rendering after a rejection | thrown transformer, swallowed `fail()`, forged rejection built from the adapter's own class, rewritten `message`, hand-marked fatal message, later plugin in the same list | A missing, duplicated, or plugin-authored diagnostic, a swallowed failure that succeeds, or a lost sibling plugin, fails. |
+| FR8 | `remark.test.tsx` identity fixture over the full supported document | untouched document with positions, math, citations, and extension nodes | Returning a copy instead of the canonical root fails identity. |
+| FR9 | `remark.test.tsx` import and manifest fixtures; `sync:exports:check` | Markdown, parser, and plugin modules; the published entry point | An adapter import inside Core's Markdown path, or an unregistered subpath, fails. |
+| FR10 | `remark.test.tsx` compile fixture over Unified-shaped declarations | attacher bound to a processor; callback-parameter and async-union transformer; inline Astryx plugin | Narrowing the accepted type so a conventional plugin stops compiling fails the fixture. |
+| FR11 | `remark.test.tsx` rejection fixtures observing `process` unhandled rejections, including server rendering | rejected attacher result; rejected transformer result; a rejected result on top of a caught guard or a caught `fail()`; a thenable whose `then` throws | Applying a verdict before defusing, or refusing without attaching a handler, fails the fixtures. |
+| FR12 | `remark.test.tsx` late-guard fixtures | a hostile `then` accessor; a getter that trips a guard while the result is validated | Dropping the final sticky re-check lets caught-guard output through and fails the fixtures. |
+
+## Decision log
+
+### DEC-1 — Lossless round trip or a readable rejection
+
+**Reference:** `module:Markdown/remark/DEC-1`
+**Decider:** `cixzhang`, `2026-09-15`
+
+The adapter never approximates. Link titles, loose list items, raw markup,
+unsupported nodes, and metadata Astryx cannot represent — including a
+non-string fence `meta` — have no Astryx meaning, so accepting them would
+silently change or drop what a reader sees. An authored fence info string does
+have a meaning here and round-trips intact; it is rejected only when it is not
+a string. Refusing the rest keeps the last valid document readable and makes
+the gap visible to the builder in one diagnostic instead of to the reader as
+missing content.
+
+### DEC-2 — Provenance is carried, never inferred
+
+**Reference:** `module:Markdown/remark/DEC-2`
+**Decider:** `cixzhang`, `2026-09-15`
+
+A transformed node belongs to a source node only when it carries the marker the
+adapter put on the copy; matching on a position that merely looks right would
+let a rebuilt node inherit provenance it never had. Equality is exact across
+every line, column, and offset, because restoring Core's position over a
+changed one is the silent approximation this profile exists to refuse.
+
+### DEC-3 — Only the adapter speaks in diagnostics
+
+**Reference:** `module:Markdown/remark/DEC-3`
+**Decider:** `cixzhang`, `2026-09-15`
+
+A plugin's own text reached it from the document and may quote any of it, so
+forwarding it would turn a developer warning into a place private content
+leaks. The single reported line is assembled from this module's vocabulary
+instead; a plugin's messages remain on the file it was given.
+
+Everything the plugin can reach, it can also rewrite: `message` is writable on
+any Error, and catching one rejection hands it the rejection class itself. So
+the reported reason is read from adapter-owned state keyed by the thrown
+object, and every refusal — a prohibited file key, a processor access, the
+plugin's own `fail()` — is recorded in adapter-owned run state rather than on
+anything the plugin holds. A refusal the plugin catches and continues past
+still fails the run, and the first reason recorded is the one reported.
+
+### DEC-4 — Owned nodes stay Core's
+
+**Reference:** `module:Markdown/remark/DEC-4`
+**Decider:** `cixzhang`, `2026-09-15`
+
+An adapted plugin may read an Astryx citation or extension node but cannot mint
+or edit one, and cannot change a source heading. Owned nodes are how Markdown,
+Outline, and fallback agree on one document; a compatibility shim is the wrong
+place to let them drift.
+
+### DEC-5 — Accept the plugin types Remark already has
+
+**Reference:** `module:Markdown/remark/DEC-5`
+**Decider:** `cixzhang`, `2026-09-15`
+
+The whole point of the profile is reusing an existing plugin, so a plugin typed
+against Unified must compile here unchanged — Unified declares one transformer
+type carrying both the callback parameter and an async return, and refusing it
+at the type level would refuse every real plugin. The adapter accepts that
+shape structurally and rejects the unsupported behavior at run time, where it
+can fail closed with a readable document. Authors writing a new plugin against
+Astryx annotate it with `MarkdownRemarkPlugin` and keep a fully typed tree.
+
+## Open questions
+
+None.
+
+## Content boundary
+
+This record does not duplicate consumer signatures or examples, the canonical
+plugin protocol, Markdown's aggregate application and fallback rules, the AST
+compatibility matrix, or Remark's own documentation. It links to their owners.
diff --git a/packages/core/src/Markdown/plugins/protocol.test.tsx b/packages/core/src/Markdown/plugins/protocol.test.tsx
index fac16def6e..0b5ed9b4d3 100644
--- a/packages/core/src/Markdown/plugins/protocol.test.tsx
+++ b/packages/core/src/Markdown/plugins/protocol.test.tsx
@@ -533,31 +533,7 @@ describe('Markdown plugin protocol', () => {
},
});
- const headingRebuild = createMarkdownPlugin({
- name: 'heading-rebuild',
- apiVersion: 1,
- transform(root) {
- return {
- ...root,
- children: root.children.map(block =>
- block.type === 'heading'
- ? {
- type: 'heading' as const,
- depth: 5 as const,
- children: block.children,
- }
- : block,
- ),
- };
- },
- });
-
- for (const plugin of [
- mutating,
- asyncPlugin,
- headingChange,
- headingRebuild,
- ]) {
+ for (const plugin of [mutating, asyncPlugin, headingChange]) {
expect(parseMarkdown('# Safe', {plugins: [plugin]})).toEqual([
{
type: 'heading',
@@ -569,7 +545,7 @@ describe('Markdown plugin protocol', () => {
warning.mockRestore();
});
- it('allows synthetic headings without changing source-backed depth', () => {
+ it('allows source heading removal and synthetic headings without changing surviving depth', () => {
const addHeading = createMarkdownPlugin({
name: 'add-heading',
apiVersion: 1,
@@ -588,10 +564,31 @@ describe('Markdown plugin protocol', () => {
},
});
+ const removeHeading = createMarkdownPlugin({
+ name: 'remove-heading',
+ apiVersion: 1,
+ transform(root) {
+ return {
+ ...root,
+ children: root.children.filter(block => block.type !== 'heading'),
+ };
+ },
+ });
+
expect(parseMarkdown('# Source', {plugins: [addHeading]})).toMatchObject([
{type: 'heading', level: 1},
{type: 'heading', level: 2, children: [{content: 'Generated'}]},
]);
+ expect(
+ parseMarkdown('# Removed\n\nSurviving body.', {
+ plugins: [removeHeading],
+ }),
+ ).toMatchObject([
+ {
+ type: 'paragraph',
+ children: [{type: 'text', content: 'Surviving body.'}],
+ },
+ ]);
});
it('rejects unsafe destinations, forged provenance, and foreign deletion', () => {
diff --git a/packages/core/src/Markdown/plugins/protocol.ts b/packages/core/src/Markdown/plugins/protocol.ts
index faa5f5cb19..e94a7106b7 100644
--- a/packages/core/src/Markdown/plugins/protocol.ts
+++ b/packages/core/src/Markdown/plugins/protocol.ts
@@ -1157,7 +1157,6 @@ function validateAst(
return (
visit(candidate, null, false) &&
candidate.type === 'root' &&
- seenHeadingMarkers.size === sourceHeadingMarkers.size &&
Array.from(existingExtensions.values()).every(
extension =>
extension.plugin === activePluginName || extension.count === 0,
diff --git a/packages/core/src/Markdown/remark.test.tsx b/packages/core/src/Markdown/remark.test.tsx
new file mode 100644
index 0000000000..cf1951eed2
--- /dev/null
+++ b/packages/core/src/Markdown/remark.test.tsx
@@ -0,0 +1,1877 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file remark.test.tsx
+ * @input Synchronous transform-only Remark plugins over the canonical Markdown tree
+ * @output Round-trip, rejection, diagnostic, rendering, and bundle-isolation coverage
+ * @position Compatibility evidence for the limited Remark profile in spec:AST-036
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {renderToString} from 'react-dom/server';
+import {render, screen} from '@testing-library/react';
+import {describe, expect, expectTypeOf, it, vi} from 'vitest';
+import {Markdown} from './Markdown';
+import {parseInlineAst, parseMarkdown, parseMarkdownAst} from './parser';
+import {createMarkdownPlugin} from './plugins';
+import type {
+ MarkdownExtensionNode,
+ MarkdownPluginEntry,
+ MarkdownSyntaxPluginDefinition,
+ MarkdownTransformContext,
+} from './plugins';
+import type {MarkdownAstRoot} from './ast';
+import type {MarkdownTransform} from './plugins';
+import {createMarkdownRemarkTransform} from './remark';
+import type {
+ MarkdownRemarkFile,
+ MarkdownRemarkPlugin,
+ MarkdownRemarkRoot,
+} from './remark';
+import {parseOutlineFromMarkdown} from '../Outline/parseOutlineFromMarkdown';
+
+type MutableNode = {
+ type: string;
+ children?: MutableNode[];
+ [key: string]: unknown;
+};
+
+/** Minimal unist-style walk, matching how real Remark plugins traverse. */
+function visit(node: MutableNode, visitor: (node: MutableNode) => void): void {
+ visitor(node);
+ if (Array.isArray(node.children)) {
+ for (const entry of [...node.children]) {
+ visit(entry, visitor);
+ }
+ }
+}
+
+function asTree(tree: MarkdownRemarkRoot): MutableNode {
+ return tree as unknown as MutableNode;
+}
+
+/** Reads a file key through the guard; the value itself is never used. */
+function probe(file: MarkdownRemarkFile, key: string): void {
+ const record = file as unknown as Record<string, unknown>;
+ // A plain member access, so the Proxy sees an ordinary read.
+ void record[key];
+}
+
+/**
+ * A realistic transform-only plugin in Unified's attacher shape: it wraps a
+ * prose term in `strong` without touching code, link destinations, or any
+ * other protected value.
+ */
+const remarkStrongTerm: MarkdownRemarkPlugin<[{term: string}]> =
+ ({term}) =>
+ (tree, file) => {
+ let matches = 0;
+ visit(asTree(tree), node => {
+ if (!Array.isArray(node.children) || node.type === 'strong') {
+ return;
+ }
+ node.children = node.children.flatMap(candidate => {
+ if (candidate.type !== 'text' || typeof candidate.value !== 'string') {
+ return [candidate];
+ }
+ const parts = candidate.value.split(term);
+ if (parts.length === 1) {
+ return [candidate];
+ }
+ matches += parts.length - 1;
+ return parts.flatMap((part, index) =>
+ index === 0
+ ? part === ''
+ ? []
+ : [{type: 'text', value: part}]
+ : [
+ {type: 'strong', children: [{type: 'text', value: term}]},
+ ...(part === '' ? [] : [{type: 'text', value: part}]),
+ ],
+ );
+ });
+ });
+ if (matches > 0) {
+ file.message(`wrapped ${matches} term(s)`);
+ }
+ };
+
+/** A text-only rename, used to prove transformed heading identity. */
+const remarkRenameTerm: MarkdownRemarkPlugin<[{from: string; to: string}]> =
+ ({from, to}) =>
+ tree => {
+ visit(asTree(tree), node => {
+ if (node.type === 'text' && typeof node.value === 'string') {
+ node.value = node.value.split(from).join(to);
+ }
+ });
+ };
+
+const renameTermPlugin = createMarkdownPlugin({
+ name: 'remark-rename-term',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkRenameTerm, {
+ from: 'Astryx',
+ to: 'Astryx Design',
+ }),
+});
+
+const removeFirstHeadingPlugin = createMarkdownPlugin({
+ name: 'remark-remove-first-heading',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(() => tree => {
+ const root = asTree(tree);
+ const headingIndex = root.children?.findIndex(
+ node => node.type === 'heading',
+ );
+ if (headingIndex != null && headingIndex >= 0) {
+ root.children?.splice(headingIndex, 1);
+ }
+ }),
+});
+
+const strongTermPlugin = createMarkdownPlugin({
+ name: 'remark-strong-term',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(remarkStrongTerm, {term: 'Astryx'}),
+});
+
+type NoteNode = MarkdownExtensionNode<
+ 'notes',
+ 'note',
+ {readonly body: string},
+ 'block'
+>;
+
+const notePlugin = createMarkdownPlugin<'notes', NoteNode>({
+ name: 'notes',
+ apiVersion: 1,
+ parseKey: 'v1',
+ syntax: {
+ block: [
+ {
+ startsWith: [':::note'],
+ maxSpan: 200,
+ tokenize({source, offset, end, isFinal}) {
+ const close = source.indexOf('\n:::', offset + 7);
+ if (close < 0 || close + 4 > end) {
+ return isFinal ? {status: 'no-match'} : {status: 'defer'};
+ }
+ return {
+ status: 'match',
+ end: close + 4,
+ node: {
+ type: 'extension',
+ plugin: 'notes',
+ name: 'note',
+ display: 'block',
+ data: {body: source.slice(offset + 7, close).trim()},
+ },
+ };
+ },
+ },
+ ],
+ },
+ renderers: {
+ note: {
+ render: ({node}) => <aside data-testid="note">{node.data.body}</aside>,
+ toText: node => node.data.body,
+ },
+ },
+} satisfies MarkdownSyntaxPluginDefinition<'notes', NoteNode>);
+
+function deepFreeze<T>(value: T, seen = new Set<object>()): T {
+ if (value != null && typeof value === 'object' && !seen.has(value)) {
+ seen.add(value);
+ for (const nested of Object.values(value)) {
+ deepFreeze(nested, seen);
+ }
+ Object.freeze(value);
+ }
+ return value;
+}
+
+interface RunResult {
+ readonly root: MarkdownAstRoot<MarkdownExtensionNode>;
+ readonly result: MarkdownAstRoot<MarkdownExtensionNode>;
+ readonly reports: string[];
+}
+
+function runAdapter(
+ source: string,
+ plugin: MarkdownRemarkPlugin<[]>,
+ options: {
+ display?: 'inline' | 'block';
+ sourceIds?: ReadonlySet<string>;
+ plugins?: ReadonlyArray<MarkdownPluginEntry>;
+ } = {},
+): RunResult {
+ const display = options.display ?? 'block';
+ const parsed =
+ display === 'inline'
+ ? ({
+ type: 'root',
+ children: [
+ {
+ type: 'paragraph',
+ children: parseInlineAst(source, options.sourceIds),
+ },
+ ],
+ } as MarkdownAstRoot<MarkdownExtensionNode>)
+ : (parseMarkdownAst(source, {
+ sourceRanges: true,
+ sourceIds: options.sourceIds,
+ plugins: options.plugins ?? [],
+ }) as MarkdownAstRoot<MarkdownExtensionNode>);
+ const root = deepFreeze(parsed);
+ const reports: string[] = [];
+ const context: MarkdownTransformContext = {
+ source,
+ isFinal: true,
+ display,
+ report: message => reports.push(message),
+ };
+ const result = createMarkdownRemarkTransform(plugin)(root, context);
+ return {root, result, reports};
+}
+
+const everyNodeSource = [
+ '# Heading with `code` and *emphasis*',
+ '',
+ 'Prose with **strong**, ~~struck~~, [a link](/docs), ![alt](/logo.png), a',
+ 'citation [ref], $x + y$ inline math, and a hard break. ',
+ 'Second line.',
+ '',
+ '![standalone](/hero.png)',
+ '',
+ '> Quoted prose',
+ '>',
+ '> - nested item',
+ '',
+ '1) First',
+ '2) Second',
+ '',
+ '- [ ] open task',
+ '- [x] done task',
+ '',
+ '| Left | Right |',
+ '| :--- | ----: |',
+ '| a | b |',
+ '',
+ '```ts title="example.ts" {1,3}',
+ 'const value = 1;',
+ '```',
+ '',
+ '```',
+ 'no language, no meta',
+ '```',
+ '',
+ '$$',
+ 'a^2 + b^2',
+ '$$',
+ '',
+ '---',
+ '',
+ ':::note',
+ 'An owned extension node.',
+ ':::',
+].join('\n');
+
+describe('Remark adapter — supported round trip', () => {
+ it('returns the identical document when every supported node is untouched', () => {
+ const root = deepFreeze(
+ parseMarkdownAst(everyNodeSource, {
+ math: true,
+ sourceRanges: true,
+ sourceIds: new Set(['ref']),
+ plugins: [notePlugin],
+ }) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const reports: string[] = [];
+ const transform = createMarkdownRemarkTransform(() => () => undefined);
+ const result = transform(root, {
+ source: everyNodeSource,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ });
+
+ // Identity, not just equality: every node round-tripped without loss, so
+ // the adapter reuses the canonical tree instead of allocating a copy.
+ expect(result).toBe(root);
+ expect(reports).toEqual([]);
+ });
+
+ it('exposes the supported subset as a mutable mdast tree', () => {
+ const seen: string[] = [];
+ const codeNodes: MutableNode[] = [];
+ runAdapter(everyNodeSource, () => tree => {
+ visit(asTree(tree), node => {
+ seen.push(node.type);
+ if (node.type === 'code') {
+ codeNodes.push(node);
+ }
+ });
+ });
+
+ expect(new Set(seen)).toEqual(
+ new Set([
+ 'root',
+ 'heading',
+ 'paragraph',
+ 'text',
+ 'inlineCode',
+ 'emphasis',
+ 'strong',
+ 'delete',
+ 'link',
+ 'image',
+ 'break',
+ 'blockquote',
+ 'list',
+ 'listItem',
+ 'table',
+ 'tableRow',
+ 'tableCell',
+ 'code',
+ 'thematicBreak',
+ ]),
+ );
+ // MDAST spelling on the way in: `meta` is the authored info string, or
+ // `null` when the fence had none.
+ expect(codeNodes[0]).toMatchObject({
+ type: 'code',
+ lang: 'ts',
+ meta: 'title="example.ts" {1,3}',
+ value: 'const value = 1;',
+ });
+ expect(codeNodes[1]).toMatchObject({
+ type: 'code',
+ lang: null,
+ meta: null,
+ value: 'no language, no meta',
+ });
+ });
+
+ it('applies a compatible transform and keeps protected contexts literal', () => {
+ const blocks = parseMarkdown(
+ 'Astryx ships `Astryx` and [Astryx](/astryx).',
+ {plugins: [strongTermPlugin]},
+ );
+
+ expect(blocks).toMatchObject([
+ {
+ type: 'paragraph',
+ children: [
+ {type: 'bold', children: [{type: 'text', content: 'Astryx'}]},
+ {type: 'text', content: ' ships '},
+ {type: 'code', content: 'Astryx'},
+ {type: 'text', content: ' and '},
+ {
+ type: 'link',
+ href: '/astryx',
+ children: [
+ {type: 'bold', children: [{type: 'text', content: 'Astryx'}]},
+ ],
+ },
+ {type: 'text', content: '.'},
+ ],
+ },
+ ]);
+ });
+
+ it('leaves fenced code copyable and renders adapted output in the browser and on the server', () => {
+ const source = 'Astryx docs\n\n```txt\nAstryx stays literal\n```';
+ render(<Markdown plugins={[strongTermPlugin]}>{source}</Markdown>);
+
+ expect(screen.getByText('Astryx')).toHaveRole('strong');
+ expect(screen.getByText('Astryx stays literal')).toBeInTheDocument();
+
+ const html = renderToString(
+ <Markdown plugins={[strongTermPlugin]}>{source}</Markdown>,
+ );
+ expect(html).toContain('<strong');
+ expect(html).toContain('Astryx stays literal');
+ });
+
+ it('shares transformed heading identity with Outline', () => {
+ const source = '# Astryx release\n\nBody.';
+ render(<Markdown plugins={[renameTermPlugin]}>{source}</Markdown>);
+ const [item] = parseOutlineFromMarkdown(source, {
+ plugins: [renameTermPlugin],
+ });
+
+ expect(item).toMatchObject({label: 'Astryx Design release', level: 1});
+ expect(screen.getByRole('heading', {level: 1})).toHaveTextContent(
+ 'Astryx Design release',
+ );
+ expect(screen.getByRole('heading', {level: 1})).toHaveAttribute(
+ 'id',
+ item.id,
+ );
+ });
+
+ it('lets a transform remove a heading while Markdown and Outline keep surviving identity', () => {
+ const source = '# Removed\n\n## Kept\n\nBody.';
+ render(<Markdown plugins={[removeFirstHeadingPlugin]}>{source}</Markdown>);
+ const outline = parseOutlineFromMarkdown(source, {
+ plugins: [removeFirstHeadingPlugin],
+ });
+
+ expect(
+ screen.queryByRole('heading', {name: 'Removed'}),
+ ).not.toBeInTheDocument();
+ expect(outline).toHaveLength(1);
+ expect(outline[0]).toMatchObject({label: 'Kept', level: 2});
+ expect(
+ screen.getByRole('heading', {name: 'Kept', level: 2}),
+ ).toHaveAttribute('id', outline[0].id);
+ });
+
+ it('reports exactly one fixed diagnostic that cannot carry plugin text', () => {
+ // Every channel a plugin could speak through quotes the document.
+ const {reports} = runAdapter(
+ 'Astryx confidential-token',
+ () => (tree, file) => {
+ file.message('saw confidential-token at line 1');
+ file.message('saw confidential-token again');
+ asTree(tree).children?.push({type: 'html', value: '<b>x</b>'});
+ },
+ );
+
+ expect(reports).toEqual([
+ 'Remark adapter: raw HTML has no Astryx representation',
+ ]);
+ expect(reports.join(' ')).not.toContain('confidential-token');
+ });
+
+ it('keeps a plugin-authored failure reason off the diagnostic', () => {
+ const {reports} = runAdapter(
+ 'Astryx confidential-token',
+ () => (_t, file) => file.fail('cannot handle "confidential-token"'),
+ );
+
+ expect(reports).toEqual([
+ 'Remark adapter: the plugin reported the document as unsupported',
+ ]);
+ expect(reports.join(' ')).not.toContain('confidential-token');
+ });
+
+ it('keeps a thrown error message off the diagnostic', () => {
+ const {reports} = runAdapter('Astryx confidential-token', () => () => {
+ throw new Error('failed parsing "confidential-token"');
+ });
+
+ expect(reports).toEqual(['Remark adapter: the plugin threw an error']);
+ expect(reports.join(' ')).not.toContain('confidential-token');
+ });
+
+ it('keeps a successful run quiet even when the plugin records messages', () => {
+ const {reports} = runAdapter(
+ 'Astryx prose',
+ () => (_tree, file) => void file.message('informational'),
+ );
+
+ expect(reports).toEqual([]);
+ });
+
+ it('makes provenance tamper-proof rather than trusting the plugin', () => {
+ let markers: symbol[] = [];
+ runAdapter('Prose.', () => tree => {
+ const paragraph = asTree(tree).children?.[0] ?? {};
+ markers = Object.getOwnPropertySymbols(paragraph);
+ for (const marker of markers) {
+ const descriptor = Object.getOwnPropertyDescriptor(paragraph, marker);
+ expect(descriptor).toMatchObject({
+ configurable: false,
+ writable: false,
+ });
+ }
+ });
+
+ expect(markers).toHaveLength(1);
+ });
+
+ it('gives every invocation a fresh tree and isolated file data', () => {
+ const observed: unknown[] = [];
+ const transform = createMarkdownRemarkTransform(
+ () => (tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ observed.push(file.data.runs);
+ file.data.runs = 'first';
+ asTree(tree).children?.push({type: 'thematicBreak'});
+ },
+ );
+ const source = 'Body text';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const context: MarkdownTransformContext = {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: () => {},
+ };
+
+ const first = transform(root, context);
+ const second = transform(root, context);
+
+ expect(observed).toEqual([undefined, undefined]);
+ expect(root.children).toHaveLength(1);
+ expect(first.children).toHaveLength(2);
+ expect(second).toEqual(first);
+ });
+});
+
+describe('Remark adapter — fenced code metadata', () => {
+ const fenceSource = [
+ '```ts title="example.ts" {1,3}',
+ 'const value = 1;',
+ '```',
+ '',
+ '```',
+ 'bare fence',
+ '```',
+ ].join('\n');
+
+ it('round-trips a parsed fence untouched, metadata included', () => {
+ const root = deepFreeze(
+ parseMarkdownAst(fenceSource, {
+ sourceRanges: true,
+ }) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const reports: string[] = [];
+ const result = createMarkdownRemarkTransform(() => () => undefined)(root, {
+ source: fenceSource,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ });
+
+ // Identity: a dropped or re-added `meta` would rebuild the node.
+ expect(result).toBe(root);
+ expect(reports).toEqual([]);
+ });
+
+ it('keeps the released code projection for a fence it rewrites', () => {
+ const blocks = parseMarkdown(fenceSource, {
+ plugins: [
+ createMarkdownPlugin({
+ name: 'uppercase-code',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(() => tree => {
+ mutateFirst(tree, 'code', node => {
+ node.value = String(node.value).toUpperCase();
+ });
+ }),
+ }),
+ ],
+ });
+
+ // The rewritten node keeps lang, meta, and the released language
+ // projection the renderer reads.
+ expect(blocks[0]).toMatchObject({
+ type: 'codeblock',
+ language: 'ts',
+ content: 'CONST VALUE = 1;',
+ });
+ expect(blocks[1]).toMatchObject({
+ type: 'codeblock',
+ content: 'bare fence',
+ });
+ });
+
+ it('carries metadata into and back out of a transform', () => {
+ const seen: unknown[] = [];
+ const {result} = runAdapter(fenceSource, () => tree => {
+ visit(asTree(tree), node => {
+ if (node.type === 'code') {
+ seen.push(node.meta);
+ }
+ });
+ mutateFirst(tree, 'code', node => {
+ node.meta = 'title="renamed.ts"';
+ });
+ });
+
+ expect(seen).toEqual(['title="example.ts" {1,3}', null]);
+ expect(result.children[0]).toMatchObject({
+ type: 'code',
+ lang: 'ts',
+ meta: 'title="renamed.ts"',
+ });
+ });
+
+ it('rejects metadata Astryx cannot represent', () => {
+ const {root, result, reports} = runAdapter(
+ fenceSource,
+ () => tree =>
+ mutateFirst(tree, 'code', node => {
+ node.meta = {title: 'example.ts'};
+ }),
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: a code node requires a string or null "meta"',
+ ]);
+ });
+});
+
+describe('Remark adapter — the constrained file fails closed', () => {
+ const unsupportedKeys = [
+ 'path',
+ 'cwd',
+ 'history',
+ 'basename',
+ 'dirname',
+ 'extname',
+ 'stem',
+ 'stored',
+ 'result',
+ 'map',
+ 'contents',
+ ];
+
+ it.each(unsupportedKeys)('rejects reading file.%s', key => {
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ probe(file, key);
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ `Remark adapter: the file has no "${key}" in this profile`,
+ ]);
+ });
+
+ it('rejects reading an arbitrary key without echoing its name', () => {
+ const {reports} = runAdapter('Prose.', () => (_tree, file) => {
+ probe(file, 'secretProjectCodename');
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "unknown" in this profile',
+ ]);
+ expect(reports[0]).not.toContain('secretProjectCodename');
+ });
+
+ it.each(['path', 'cwd', 'value'])('rejects writing file.%s', key => {
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ (file as unknown as Record<string, unknown>)[key] = 'anything';
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ `Remark adapter: the file's "${key}" cannot be assigned in this profile`,
+ ]);
+ });
+
+ it('rejects defining or deleting a file property', () => {
+ for (const mutate of [
+ (file: MarkdownRemarkFile) =>
+ Object.defineProperty(file, 'cwd', {value: '/'}),
+ (file: MarkdownRemarkFile) =>
+ delete (file as unknown as Record<string, unknown>).value,
+ ]) {
+ const {reports} = runAdapter('Prose.', () => (_tree, file) => {
+ mutate(file);
+ });
+ expect(reports).toEqual([
+ expect.stringMatching(/cannot be assigned in this profile$/),
+ ]);
+ }
+ });
+
+ it('lets a plugin feature-detect instead of failing', () => {
+ const detected: Record<string, boolean> = {};
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ for (const key of ['cwd', 'path', 'data', 'message']) {
+ detected[key] = key in file;
+ }
+ expect(Object.keys(file).sort()).toEqual([
+ 'data',
+ 'fail',
+ 'message',
+ 'messages',
+ 'toString',
+ 'value',
+ ]);
+ },
+ );
+
+ expect(detected).toEqual({
+ cwd: false,
+ path: false,
+ data: true,
+ message: true,
+ });
+ expect(result).toBe(root);
+ expect(reports).toEqual([]);
+ });
+
+ it('serves the whole documented surface', () => {
+ const observed: Record<string, unknown> = {};
+ const {reports} = runAdapter('Document source.', () => (_tree, file) => {
+ observed.value = file.value;
+ observed.text = file.toString();
+ observed.data = file.data;
+ observed.messages = file.messages.length;
+ file.data.note = 'kept';
+ file.message('advisory');
+ observed.afterMessage = file.messages.length;
+ });
+
+ expect(observed).toEqual({
+ value: 'Document source.',
+ text: 'Document source.',
+ data: {note: 'kept'},
+ messages: 0,
+ afterMessage: 1,
+ });
+ expect(reports).toEqual([]);
+ });
+});
+
+describe('Remark adapter — a plugin cannot talk its way out of a failure', () => {
+ it('fails the run when the plugin swallows its own fail()', () => {
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ try {
+ file.fail('cannot handle this document');
+ } catch {
+ // A plugin that carries on regardless has still declared the
+ // document unsupported.
+ }
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the plugin reported the document as unsupported',
+ ]);
+ });
+
+ it('keeps the verdict when the plugin swallows fail() and returns a tree', () => {
+ const {root, result, reports} = runAdapter('Prose.', () => (tree, file) => {
+ try {
+ file.fail('cannot handle this document');
+ } catch {
+ // ignored
+ }
+ return tree;
+ });
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the plugin reported the document as unsupported',
+ ]);
+ });
+
+ it('keeps the verdict when the plugin swallows fail() then throws its own error', () => {
+ const {result, root, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ try {
+ file.fail('cannot handle this document');
+ } catch {
+ throw new Error('a different, friendlier-sounding message');
+ }
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the plugin reported the document as unsupported',
+ ]);
+ });
+
+ it('lets the original verdict stand when a plugin steals the rejection class', () => {
+ let stolen: (new (message: string) => Error) | undefined;
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ try {
+ probe(file, 'cwd');
+ } catch (error) {
+ stolen = (error as Error).constructor as new (
+ message: string,
+ ) => Error;
+ }
+ // Carrying on after a guard fires does not clear the verdict.
+ },
+ );
+
+ expect(stolen).toBeTypeOf('function');
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "cwd" in this profile',
+ ]);
+ });
+
+ it('never echoes a rejection forged from the stolen class in a later run', () => {
+ let stolen: (new (message: string) => Error) | undefined;
+ const transform = createMarkdownRemarkTransform(
+ () => (_tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ if (stolen == null) {
+ try {
+ probe(file, 'cwd');
+ } catch (error) {
+ stolen = (error as Error).constructor as new (
+ message: string,
+ ) => Error;
+ }
+ return;
+ }
+ throw new stolen('the document is perfectly fine, carry on');
+ },
+ );
+ const reports: string[] = [];
+ const run = (): MarkdownAstRoot<MarkdownExtensionNode> => {
+ const source = 'Prose.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const result = transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ });
+ expect(result).toBe(root);
+ return result;
+ };
+
+ run();
+ run();
+
+ // The forged throw is an untracked instance, so only the generic reason
+ // is reported — its own wording never reaches the diagnostic.
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "cwd" in this profile',
+ 'Remark adapter: the plugin threw an error',
+ ]);
+ expect(reports.join(' ')).not.toContain('perfectly fine');
+ });
+
+ it('never echoes a rewritten message on a real rejection', () => {
+ const {reports} = runAdapter('Prose.', () => (_tree, file) => {
+ try {
+ probe(file, 'cwd');
+ } catch (error) {
+ (error as Error).message = 'everything is fine';
+ throw error;
+ }
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "cwd" in this profile',
+ ]);
+ });
+
+ it.each([
+ [
+ 'reading a prohibited key',
+ (file: MarkdownRemarkFile) => probe(file, 'cwd'),
+ ],
+ [
+ 'writing a prohibited key',
+ (file: MarkdownRemarkFile) => {
+ (file as unknown as Record<string, unknown>).cwd = '/tmp';
+ },
+ ],
+ [
+ 'defining a property',
+ (file: MarkdownRemarkFile) =>
+ Object.defineProperty(file, 'path', {value: '/tmp/doc.md'}),
+ ],
+ [
+ 'deleting a property',
+ (file: MarkdownRemarkFile) => {
+ delete (file as unknown as Record<string, unknown>).value;
+ },
+ ],
+ ])('fails the run when the plugin catches %s', (_name, trip) => {
+ const {root, result, reports} = runAdapter('Prose.', () => (tree, file) => {
+ try {
+ trip(file);
+ } catch {
+ // Swallowed, then the plugin carries on as if nothing happened.
+ }
+ return tree;
+ });
+
+ expect(result).toBe(root);
+ expect(reports).toHaveLength(1);
+ expect(reports[0]).toMatch(/^Remark adapter: the file\b/);
+ });
+
+ it('fails the attach when the plugin catches a processor access', () => {
+ const sneaky = function sneaky(this: {data(key: string): unknown}) {
+ try {
+ this.data('micromarkExtensions');
+ } catch {
+ // Swallowed; the attacher returns a perfectly ordinary transformer.
+ }
+ return (tree: MarkdownRemarkRoot) => tree;
+ };
+ const transform = createMarkdownRemarkTransform(
+ sneaky as unknown as MarkdownRemarkPlugin<[]>,
+ );
+ const source = 'Prose.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const reports: string[] = [];
+
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: processor registration is outside the adapter',
+ ]);
+ });
+
+ it('fails the run when the plugin catches a processor access at run time', () => {
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ function attacher(this: {data(key: string): unknown}) {
+ // A real plugin closes over the processor at attach time and reaches
+ // for it later; the guard has to hold then too.
+ const data = this.data.bind(this);
+ return (tree: MarkdownRemarkRoot) => {
+ try {
+ data('micromarkExtensions');
+ } catch {
+ // Swallowed mid-transform.
+ }
+ return tree;
+ };
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: processor registration is outside the adapter',
+ ]);
+ });
+
+ it('keeps the first verdict when a plugin catches a guard and then fails', () => {
+ const {reports} = runAdapter('Prose.', () => (_tree, file) => {
+ try {
+ probe(file, 'path');
+ } catch {
+ // ignored
+ }
+ file.fail('a different explanation');
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "path" in this profile',
+ ]);
+ });
+
+ it('rejects output when a hostile then accessor trips a guard late', () => {
+ // `then` is read after the transformer returns, so a guard that fires
+ // inside the accessor lands after the first sticky check. The validated
+ // output must still never be accepted.
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ const hostile = asTree(tree) as unknown as Record<string, unknown>;
+ Object.defineProperty(hostile, 'then', {
+ configurable: true,
+ get() {
+ try {
+ probe(file, 'cwd');
+ } catch {
+ // Swallowed inside the accessor, mid-inspection.
+ }
+ return undefined;
+ },
+ });
+ return tree;
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "cwd" in this profile',
+ ]);
+ });
+
+ it('rejects output when a guard fires while the result is being validated', () => {
+ // A getter on a node the adapter reads during validation is the same
+ // trap by another route: the refusal lands after every earlier check.
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ const paragraph = asTree(tree).children?.[0] as unknown as Record<
+ string,
+ unknown
+ >;
+ let tripped = false;
+ const actual = paragraph.children as unknown[];
+ Object.defineProperty(paragraph, 'children', {
+ configurable: true,
+ get(): unknown[] {
+ if (!tripped) {
+ tripped = true;
+ try {
+ probe(file, 'path');
+ } catch {
+ // Swallowed during validation.
+ }
+ }
+ return actual;
+ },
+ });
+ return tree;
+ },
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "path" in this profile',
+ ]);
+ });
+
+ it('ignores a message a plugin marks fatal by hand', () => {
+ const {root, result, reports} = runAdapter(
+ 'Prose.',
+ () => (_tree, file) => {
+ const message = file.message('advisory');
+ message.fatal = true;
+ file.messages.push({
+ reason: 'forged',
+ fatal: true,
+ place: null,
+ ruleId: null,
+ toString: () => 'forged',
+ });
+ },
+ );
+
+ // A run that did not actually fail still succeeds, silently.
+ expect(result).toBe(root);
+ expect(reports).toEqual([]);
+ });
+});
+
+interface RejectionCase {
+ readonly name: string;
+ readonly plugin: MarkdownRemarkPlugin<[]>;
+ readonly reason: RegExp;
+ readonly source?: string;
+ readonly display?: 'inline' | 'block';
+ readonly sourceIds?: ReadonlySet<string>;
+ readonly plugins?: ReadonlyArray<MarkdownPluginEntry>;
+}
+
+const rejectionSource = '# Astryx heading\n\nProse with [a link](/docs).';
+
+function mutateFirst(
+ tree: MarkdownRemarkRoot,
+ type: string,
+ mutate: (node: MutableNode) => void,
+): void {
+ let done = false;
+ visit(asTree(tree), node => {
+ if (!done && node.type === type) {
+ done = true;
+ mutate(node);
+ }
+ });
+}
+
+const rejectionCases: RejectionCase[] = [
+ {
+ name: 'an asynchronous transformer',
+ plugin: () => async () => undefined,
+ reason: /asynchronous transformer/,
+ },
+ {
+ name: 'a callback-style transformer',
+ plugin: () =>
+ ((_tree: unknown, _file: unknown, _next: unknown) => undefined) as never,
+ reason: /callback-style/,
+ },
+ {
+ name: 'a parser or compiler plugin that registers processor state',
+ plugin: function parserPlugin(this: {data(key: string): void}) {
+ this.data('micromarkExtensions');
+ return () => undefined;
+ },
+ reason: /processor registration/,
+ },
+ {
+ name: 'a plugin that returns no transformer',
+ plugin: () => undefined,
+ reason: /transform-only plugin/,
+ },
+ {
+ name: 'a plugin that returns a promise from its attacher',
+ plugin: (() => ({then: () => undefined})) as never,
+ reason: /asynchronous plugin/,
+ },
+ {
+ name: 'raw HTML',
+ plugin: () => tree =>
+ void asTree(tree).children?.push({type: 'html', value: '<b>x</b>'}),
+ reason: /raw HTML/,
+ },
+ {
+ name: 'an unsupported node kind',
+ plugin: () => tree =>
+ void asTree(tree).children?.push({
+ type: 'footnoteDefinition',
+ identifier: 'a',
+ children: [],
+ }),
+ reason: /"footnoteDefinition" is outside the supported MDAST subset/,
+ },
+ {
+ name: 'a forged source position',
+ plugin: () => tree =>
+ void asTree(tree).children?.push({
+ type: 'paragraph',
+ children: [{type: 'text', value: 'forged'}],
+ position: {start: {offset: 0}, end: {offset: 4}},
+ }),
+ reason: /cannot carry a source position/,
+ },
+ {
+ name: 'a shifted source position',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.position = {start: {offset: 999}, end: {offset: 1200}};
+ }),
+ reason: /position must stay exactly as Core authored it/,
+ },
+ {
+ name: 'a shifted line or column on an unchanged offset',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ const position = node.position as {
+ start: {offset: number};
+ end: {offset: number};
+ };
+ node.position = {
+ start: {line: 99, column: 1, offset: position.start.offset},
+ end: {line: 99, column: 9, offset: position.end.offset},
+ };
+ }),
+ reason: /position must stay exactly as Core authored it/,
+ },
+ {
+ name: 'a removed source position',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ delete node.position;
+ }),
+ reason: /position must stay exactly as Core authored it/,
+ },
+ {
+ name: 'provenance rebuilt from a copied position',
+ plugin: () => tree => {
+ const root = asTree(tree);
+ const paragraph = root.children?.find(node => node.type === 'paragraph');
+ root.children = root.children?.map(node =>
+ node === paragraph
+ ? {
+ type: 'paragraph',
+ position: paragraph.position,
+ children: [{type: 'text', value: 'rebuilt'}],
+ }
+ : node,
+ );
+ },
+ reason: /cannot carry a source position/,
+ },
+
+ {
+ name: 'a changed source heading depth',
+ plugin: () => tree =>
+ mutateFirst(tree, 'heading', node => {
+ node.depth = 4;
+ }),
+ reason: /heading's depth cannot change/,
+ },
+ {
+ name: 'a retyped source node',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.type = 'blockquote';
+ }),
+ reason: /cannot be retyped/,
+ },
+ {
+ name: 'a duplicated source node',
+ plugin: () => tree => {
+ const root = asTree(tree);
+ const first = root.children?.[0];
+ if (first != null) {
+ root.children?.push(first);
+ }
+ },
+ reason: /cannot be duplicated/,
+ },
+ {
+ name: 'an authored Astryx extension node',
+ plugin: () => tree =>
+ void asTree(tree).children?.push({
+ type: 'extension',
+ plugin: 'notes',
+ name: 'note',
+ display: 'block',
+ data: {body: 'forged'},
+ }),
+ reason: /"extension" node cannot be authored or changed/,
+ },
+ {
+ name: 'a rewritten Astryx citation',
+ source: 'Prose with a citation [ref].',
+ sourceIds: new Set(['ref']),
+ plugin: () => tree =>
+ mutateFirst(tree, 'citation', node => {
+ node.sourceId = 'other';
+ }),
+ reason: /"citation" node cannot be authored or changed/,
+ },
+ {
+ name: "an edited Astryx extension node's data",
+ source: ':::note\nOwned body.\n:::',
+ plugins: [notePlugin],
+ plugin: () => tree =>
+ mutateFirst(tree, 'extension', node => {
+ node.data = {body: 'rewritten'};
+ }),
+ reason: /"extension" node cannot be authored or changed/,
+ },
+ {
+ name: "an edited Astryx extension node's authored source",
+ source: ':::note\nOwned body.\n:::',
+ plugins: [notePlugin],
+ plugin: () => tree =>
+ mutateFirst(tree, 'extension', node => {
+ node.source = ':::note\nforged\n:::';
+ }),
+ reason: /"extension" node cannot be authored or changed/,
+ },
+ {
+ name: 'a raw-markup data channel',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.data = {hName: 'section'};
+ }),
+ reason: /raw-markup data channel "hName"/,
+ },
+ {
+ name: 'unrepresentable node data',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.data = {render: () => null};
+ }),
+ reason: /data must be finite JSON-like/,
+ },
+ {
+ name: 'unrepresentable file data',
+ plugin: () => (_tree, file) => {
+ file.data.cache = () => null;
+ },
+ reason: /file data must be finite JSON-like/,
+ },
+ {
+ name: 'non-string fence metadata',
+ source: '```ts\nconst a = 1;\n```',
+ plugin: () => tree =>
+ mutateFirst(tree, 'code', node => {
+ node.meta = 42;
+ }),
+ reason: /requires a string or null "meta"/,
+ },
+ {
+ name: 'an unrepresentable link title',
+ plugin: () => tree =>
+ mutateFirst(tree, 'link', node => {
+ node.title = 'Docs';
+ }),
+ reason: /"title" has no Astryx representation/,
+ },
+ {
+ name: 'an unsupported field on a supported node',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.hProperties = {className: 'x'};
+ }),
+ reason: /unsupported field "hProperties"/,
+ },
+ {
+ name: 'a rejected link destination',
+ plugin: () => tree =>
+ mutateFirst(tree, 'link', node => {
+ node.url = 'javascript:alert(1)';
+ }),
+ reason: /rejected by the navigation owner/,
+ },
+ {
+ name: 'an image without its text alternative',
+ source: '![alt](/logo.png)',
+ plugin: () => tree =>
+ mutateFirst(tree, 'image', node => {
+ node.alt = null;
+ }),
+ reason: /requires its text alternative/,
+ },
+ {
+ name: 'invalid built-in structure',
+ plugin: () => tree =>
+ mutateFirst(tree, 'paragraph', node => {
+ node.children?.push({type: 'thematicBreak'});
+ }),
+ reason: /cannot be a child of a "paragraph" node/,
+ },
+ {
+ name: 'a nested link',
+ plugin: () => tree =>
+ mutateFirst(tree, 'link', node => {
+ node.children = [
+ {type: 'link', url: '/inner', title: null, children: []},
+ ];
+ }),
+ reason: /nested inside another link/,
+ },
+ {
+ name: 'a loose list item',
+ source: '- one\n- two',
+ plugin: () => tree =>
+ mutateFirst(tree, 'listItem', node => {
+ node.spread = true;
+ }),
+ reason: /loose list item/,
+ },
+ {
+ name: 'a ragged transformed table',
+ source: '| a | b |\n| - | - |\n| c | d |',
+ plugin: () => tree =>
+ mutateFirst(tree, 'tableRow', node => {
+ node.children?.pop();
+ }),
+ reason: /ragged rows/,
+ },
+ {
+ name: 'block output from an inline entry point',
+ display: 'inline',
+ source: 'Inline Astryx prose',
+ plugin: () => tree =>
+ void asTree(tree).children?.push({
+ type: 'paragraph',
+ children: [{type: 'text', value: 'extra'}],
+ }),
+ reason: /one paragraph of phrasing content/,
+ },
+ {
+ name: 'a transformer that throws',
+ plugin: () => () => {
+ throw new Error('boom');
+ },
+ reason: /^Remark adapter: the plugin threw an error$/,
+ },
+ {
+ name: 'a transformer that fails the file',
+ plugin: () => (_tree, file) => file.fail('unsupported document'),
+ reason: /^Remark adapter: the plugin reported the document as unsupported$/,
+ },
+ {
+ name: 'a transformer that returns a non-root node',
+ plugin: () => () => ({type: 'paragraph', children: []}) as never,
+ reason: /cannot be a child of|must return the document root|unsupported/,
+ },
+];
+
+describe('Remark adapter — rejection matrix', () => {
+ it.each(rejectionCases)(
+ 'keeps the last valid document after $name',
+ ({plugin, reason, source, display, sourceIds, plugins}) => {
+ const {root, result, reports} = runAdapter(
+ source ?? rejectionSource,
+ plugin,
+ {display, sourceIds, plugins},
+ );
+
+ expect(result).toBe(root);
+ expect(reports).toHaveLength(1);
+ expect(reports[0]).toMatch(/^Remark adapter: /);
+ expect(reports[0]).toMatch(reason);
+ // Diagnostics name contracts, never document source.
+ expect(reports[0]).not.toContain('Astryx heading');
+ },
+ );
+
+ it('renders readable source after a rejected transform', () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const broken = createMarkdownPlugin({
+ name: 'broken-remark',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(() => tree => {
+ asTree(tree).children?.push({
+ type: 'html',
+ value: '<script>x</script>',
+ });
+ }),
+ });
+
+ render(
+ <Markdown plugins={[broken]}>
+ {'# Still readable\n\nProse survives.'}
+ </Markdown>,
+ );
+
+ expect(screen.getByRole('heading', {level: 1})).toHaveTextContent(
+ 'Still readable',
+ );
+ expect(screen.getByText('Prose survives.')).toBeInTheDocument();
+ expect(document.body.innerHTML).not.toContain('<script>');
+ expect(warning).toHaveBeenCalled();
+ warning.mockRestore();
+ });
+
+ it('keeps later plugins running after one adapted plugin fails', () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const failing = createMarkdownPlugin({
+ name: 'failing-remark',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(() => () => {
+ throw new Error('boom');
+ }),
+ });
+
+ const blocks = parseMarkdown('Astryx ships', {
+ plugins: [failing, strongTermPlugin],
+ });
+
+ expect(blocks).toMatchObject([
+ {
+ type: 'paragraph',
+ children: [
+ {type: 'bold', children: [{type: 'text', content: 'Astryx'}]},
+ {type: 'text', content: ' ships'},
+ ],
+ },
+ ]);
+ warning.mockRestore();
+ });
+
+ it('rejects provenance smuggled in from another document', () => {
+ let stashed: MutableNode | undefined;
+ const transform = createMarkdownRemarkTransform(() => tree => {
+ const root = asTree(tree);
+ if (stashed == null) {
+ stashed = root.children?.[0];
+ return;
+ }
+ root.children?.push(stashed);
+ });
+ const reports: string[] = [];
+ const run = (source: string): MarkdownAstRoot<MarkdownExtensionNode> => {
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const result = transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ });
+ expect(result).toBe(root);
+ return result;
+ };
+
+ run('First document.');
+ run('Second document.');
+
+ expect(reports).toEqual([
+ 'Remark adapter: a "paragraph" node carries forged provenance',
+ ]);
+ });
+
+ it('rejects a plugin value that is not a function', () => {
+ expect(() =>
+ createMarkdownRemarkTransform({} as unknown as MarkdownRemarkPlugin<[]>),
+ ).toThrow(/plugin must be a function/);
+ });
+});
+
+/* ------------------------------------------------------------------ *
+ * Compile fixture: a conventional Unified/Remark plugin type
+ *
+ * These declarations mirror `unified`'s own shapes without depending on the
+ * package: an attacher bound to a processor, and a transformer that takes the
+ * callback parameter and declares an asynchronous return union. Existing
+ * typed plugins must type-check at the callsite; the run-time behavior for an
+ * actual promise and for a callback-style transformer is asserted above.
+ * ------------------------------------------------------------------ */
+
+interface UnifiedPoint {
+ line: number;
+ column: number;
+ offset?: number | undefined;
+}
+
+interface UnifiedNode {
+ type: string;
+ children?: UnifiedNode[];
+ value?: string;
+ position?: {start: UnifiedPoint; end: UnifiedPoint} | undefined;
+ data?: Record<string, unknown> | undefined;
+}
+
+interface UnifiedRoot extends UnifiedNode {
+ type: 'root';
+ children: UnifiedNode[];
+}
+
+interface UnifiedVFile {
+ value: string | Uint8Array;
+ data: Record<string, unknown>;
+ cwd: string;
+ message(reason: string | Error): {reason: string};
+ fail(reason: string | Error): never;
+}
+
+interface UnifiedProcessor {
+ data(key: string): unknown;
+ use(plugin: unknown): UnifiedProcessor;
+}
+
+/* eslint-disable @typescript-eslint/no-invalid-void-type -- Unified's own
+ transformer and attacher types include `void`; the fixture is only faithful
+ if it keeps them. */
+type UnifiedTransformer = (
+ tree: UnifiedRoot,
+ file: UnifiedVFile,
+ next: (error?: Error | null, tree?: UnifiedRoot) => undefined,
+) => Promise<UnifiedRoot | undefined> | UnifiedRoot | undefined | void;
+
+type UnifiedPlugin<Parameters extends unknown[] = []> = (
+ this: UnifiedProcessor,
+ ...parameters: Parameters
+) => UnifiedTransformer | undefined | void;
+/* eslint-enable @typescript-eslint/no-invalid-void-type */
+
+const remarkConventional: UnifiedPlugin<[{flag: boolean}?]> =
+ options => tree => {
+ if (options?.flag === true) {
+ tree.children = [];
+ }
+ };
+
+const remarkNoSettings: UnifiedPlugin = () => tree => tree;
+
+describe('Remark adapter — conventional plugin types', () => {
+ it('accepts a conventional Unified plugin at the callsite', () => {
+ // Compile fixture: these calls failing to type-check is the regression.
+ const withSettings = createMarkdownRemarkTransform(remarkConventional, {
+ flag: false,
+ });
+ const withoutSettings = createMarkdownRemarkTransform(remarkNoSettings);
+ const inlineAstryxPlugin = createMarkdownRemarkTransform(
+ () => (tree, file) => {
+ // The strict overload still types the tree and file for new plugins.
+ expectTypeOf(tree).toEqualTypeOf<MarkdownRemarkRoot>();
+ expectTypeOf(file).toEqualTypeOf<MarkdownRemarkFile>();
+ return tree;
+ },
+ );
+
+ expectTypeOf(withSettings).toEqualTypeOf<MarkdownTransform<never>>();
+ expectTypeOf(withoutSettings).toEqualTypeOf<MarkdownTransform<never>>();
+ expectTypeOf(inlineAstryxPlugin).toEqualTypeOf<MarkdownTransform<never>>();
+ expectTypeOf(createMarkdownRemarkTransform).parameter(0).not.toBeNever();
+
+ // A conventional plugin also runs: a no-op leaves the document identical.
+ const source = 'Prose stays put.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const reports: string[] = [];
+ expect(
+ withoutSettings(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ expect(reports).toEqual([]);
+ });
+
+ it('still rejects an actual promise from a conventional plugin', () => {
+ const remarkAsync: UnifiedPlugin = () => async tree => tree;
+ const transform = createMarkdownRemarkTransform(remarkAsync);
+ const source = 'Prose stays put.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const reports: string[] = [];
+
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ expect(reports).toEqual([
+ 'Remark adapter: an asynchronous transformer is outside the adapter',
+ ]);
+ });
+});
+
+describe('Remark adapter — a refused promise is never left unhandled', () => {
+ /** Collects unhandled rejections for the duration of `work`. */
+ async function withUnhandledRejections(work: () => void): Promise<unknown[]> {
+ const seen: unknown[] = [];
+ const onUnhandled = (reason: unknown): void => {
+ seen.push(reason);
+ };
+ process.on('unhandledRejection', onUnhandled);
+ try {
+ work();
+ // Unhandled rejections are reported a macrotask later.
+ await new Promise(resolve => setTimeout(resolve, 50));
+ } finally {
+ process.off('unhandledRejection', onUnhandled);
+ }
+ return seen;
+ }
+
+ it('refuses an already-rejected transformer result without an unhandled rejection', async () => {
+ const reports: string[] = [];
+ const seen = await withUnhandledRejections(() => {
+ const source = 'Astryx confidential-token';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const transform = createMarkdownRemarkTransform(
+ () => () =>
+ Promise.reject(
+ new Error('failed on "confidential-token"'),
+ ) as unknown as MarkdownRemarkRoot,
+ );
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: an asynchronous transformer is outside the adapter',
+ ]);
+ expect(seen).toEqual([]);
+ });
+
+ it('refuses a rejected attacher result without an unhandled rejection', async () => {
+ const reports: string[] = [];
+ const seen = await withUnhandledRejections(() => {
+ const source = 'Astryx confidential-token';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const rejectingAttacher = async (): Promise<never> => {
+ throw new Error('attach failed on "confidential-token"');
+ };
+ const transform = createMarkdownRemarkTransform(
+ rejectingAttacher as unknown as MarkdownRemarkPlugin<[]>,
+ );
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: an asynchronous plugin is outside the adapter',
+ ]);
+ expect(seen).toEqual([]);
+ });
+
+ it('defuses a rejected promise even when a caught guard outranks it', async () => {
+ // The ordering trap: the sticky verdict is reported, but the promise
+ // must still be handled on the way past.
+ const reports: string[] = [];
+ const seen = await withUnhandledRejections(() => {
+ const source = 'Astryx confidential-token';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const transform = createMarkdownRemarkTransform(
+ () => (_tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ try {
+ probe(file, 'cwd');
+ } catch {
+ // Swallowed, then an async result on top of it.
+ }
+ return Promise.reject(
+ new Error('async failure quoting confidential-token'),
+ ) as unknown as MarkdownRemarkRoot;
+ },
+ );
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ });
+
+ // The caught guard is what gets reported...
+ expect(reports).toEqual([
+ 'Remark adapter: the file has no "cwd" in this profile',
+ ]);
+ // ...and the promise is still handled.
+ expect(seen).toEqual([]);
+ });
+
+ it('defuses a rejected promise even when the plugin also caught its own fail()', async () => {
+ const reports: string[] = [];
+ const seen = await withUnhandledRejections(() => {
+ const source = 'Prose.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const transform = createMarkdownRemarkTransform(
+ () => (_tree: MarkdownRemarkRoot, file: MarkdownRemarkFile) => {
+ try {
+ file.fail('cannot handle "confidential-token"');
+ } catch {
+ // Swallowed.
+ }
+ return Promise.reject(
+ new Error('and an async failure too'),
+ ) as unknown as MarkdownRemarkRoot;
+ },
+ );
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: the plugin reported the document as unsupported',
+ ]);
+ expect(seen).toEqual([]);
+ });
+
+ it('refuses a thenable whose then throws', async () => {
+ const reports: string[] = [];
+ const seen = await withUnhandledRejections(() => {
+ const source = 'Prose.';
+ const root = deepFreeze(
+ parseMarkdownAst(source) as MarkdownAstRoot<MarkdownExtensionNode>,
+ );
+ const transform = createMarkdownRemarkTransform(
+ () => () =>
+ ({
+ then() {
+ throw new Error('hostile thenable');
+ },
+ }) as unknown as MarkdownRemarkRoot,
+ );
+ expect(
+ transform(root, {
+ source,
+ isFinal: true,
+ display: 'block',
+ report: message => reports.push(message),
+ }),
+ ).toBe(root);
+ });
+
+ expect(reports).toEqual([
+ 'Remark adapter: an asynchronous transformer is outside the adapter',
+ ]);
+ expect(seen).toEqual([]);
+ });
+
+ it('renders readable server output for a rejected async plugin, quietly', async () => {
+ const asyncPlugin = createMarkdownPlugin({
+ name: 'async-remark',
+ apiVersion: 1,
+ transform: createMarkdownRemarkTransform(
+ () => () =>
+ Promise.reject(
+ new Error('server-side failure quoting confidential-token'),
+ ) as unknown as MarkdownRemarkRoot,
+ ),
+ });
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let html = '';
+ const seen = await withUnhandledRejections(() => {
+ html = renderToString(
+ <Markdown plugins={[asyncPlugin]}>
+ {'# Still readable\n\nProse survives.'}
+ </Markdown>,
+ );
+ });
+
+ expect(html).toContain('Still readable');
+ expect(html).toContain('Prose survives.');
+ expect(html).not.toContain('confidential-token');
+ expect(seen).toEqual([]);
+ warning.mockRestore();
+ });
+});
+
+describe('Remark adapter — optional by construction', () => {
+ it('stays out of the Markdown entry point and parser modules', () => {
+ for (const file of [
+ 'index.ts',
+ 'Markdown.tsx',
+ 'parser.ts',
+ 'plugins/protocol.ts',
+ ]) {
+ const contents = fs.readFileSync(path.join(__dirname, file), 'utf8');
+ expect(contents).not.toContain('./remark');
+ }
+ });
+
+ it('is published as its own entry point', () => {
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf8'),
+ ) as {exports: Record<string, {source?: string}>};
+
+ expect(manifest.exports['./Markdown/remark']).toMatchObject({
+ source: './src/Markdown/remark.ts',
+ });
+ });
+});
diff --git a/packages/core/src/Markdown/remark.ts b/packages/core/src/Markdown/remark.ts
new file mode 100644
index 0000000000..88e11fd320
--- /dev/null
+++ b/packages/core/src/Markdown/remark.ts
@@ -0,0 +1,1574 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file remark.ts
+ * @input Synchronous transform-only Remark plugins over the supported MDAST subset
+ * @output A Markdown transform that applies a validated round trip or fails closed
+ * @position Optional tree-shakeable compatibility adapter; never imported by Markdown
+ */
+
+import type {
+ MarkdownAstDataValue,
+ MarkdownAstExtensionNode,
+ MarkdownAstRoot,
+} from './ast';
+import {
+ isMarkdownPluginData,
+ type MarkdownTransform,
+ type MarkdownTransformContext,
+} from './plugins/protocol';
+import {isSafeMarkdownParserUrl} from './url';
+
+/* ------------------------------------------------------------------ *
+ * Public mutable tree the adapted plugin observes
+ * ------------------------------------------------------------------ */
+
+export interface MarkdownRemarkPoint {
+ line?: number;
+ column?: number;
+ offset?: number;
+}
+
+export interface MarkdownRemarkPosition {
+ start: MarkdownRemarkPoint;
+ end: MarkdownRemarkPoint;
+}
+
+export interface MarkdownRemarkNodeBase {
+ position?: MarkdownRemarkPosition;
+ data?: {[key: string]: unknown};
+}
+
+export interface MarkdownRemarkText extends MarkdownRemarkNodeBase {
+ type: 'text';
+ value: string;
+}
+
+export interface MarkdownRemarkInlineCode extends MarkdownRemarkNodeBase {
+ type: 'inlineCode';
+ value: string;
+}
+
+export interface MarkdownRemarkInlineMath extends MarkdownRemarkNodeBase {
+ type: 'inlineMath';
+ value: string;
+}
+
+export interface MarkdownRemarkBreak extends MarkdownRemarkNodeBase {
+ type: 'break';
+}
+
+export interface MarkdownRemarkPhrasingParent<
+ Type extends 'strong' | 'emphasis' | 'delete',
+> extends MarkdownRemarkNodeBase {
+ type: Type;
+ children: MarkdownRemarkPhrasingContent[];
+}
+
+export interface MarkdownRemarkLink extends MarkdownRemarkNodeBase {
+ type: 'link';
+ url: string;
+ /** Always `null` on input; a non-empty title cannot round-trip. */
+ title?: string | null;
+ children: MarkdownRemarkPhrasingContent[];
+}
+
+export interface MarkdownRemarkImage extends MarkdownRemarkNodeBase {
+ type: 'image';
+ url: string;
+ /** Always `null` on input; a non-empty title cannot round-trip. */
+ title?: string | null;
+ alt: string;
+}
+
+/** Astryx-owned citation. Read-only inside the adapter. */
+export interface MarkdownRemarkCitation extends MarkdownRemarkNodeBase {
+ type: 'citation';
+ sourceId: string;
+}
+
+/** Astryx-owned plugin extension node. Read-only inside the adapter. */
+export interface MarkdownRemarkExtension extends MarkdownRemarkNodeBase {
+ type: 'extension';
+ plugin: string;
+ name: string;
+ display: 'inline' | 'block';
+ source?: string;
+}
+
+export type MarkdownRemarkPhrasingContent =
+ | MarkdownRemarkText
+ | MarkdownRemarkInlineCode
+ | MarkdownRemarkInlineMath
+ | MarkdownRemarkBreak
+ | MarkdownRemarkPhrasingParent<'strong'>
+ | MarkdownRemarkPhrasingParent<'emphasis'>
+ | MarkdownRemarkPhrasingParent<'delete'>
+ | MarkdownRemarkLink
+ | MarkdownRemarkImage
+ | MarkdownRemarkCitation
+ | MarkdownRemarkExtension;
+
+export interface MarkdownRemarkHeading extends MarkdownRemarkNodeBase {
+ type: 'heading';
+ depth: 1 | 2 | 3 | 4 | 5 | 6;
+ children: MarkdownRemarkPhrasingContent[];
+}
+
+export interface MarkdownRemarkParagraph extends MarkdownRemarkNodeBase {
+ type: 'paragraph';
+ children: MarkdownRemarkPhrasingContent[];
+}
+
+export interface MarkdownRemarkCode extends MarkdownRemarkNodeBase {
+ type: 'code';
+ lang: string | null;
+ /** The authored info string after the language, `null` when absent. */
+ meta?: string | null;
+ value: string;
+}
+
+export interface MarkdownRemarkMath extends MarkdownRemarkNodeBase {
+ type: 'math';
+ value: string;
+}
+
+export interface MarkdownRemarkBlockquote extends MarkdownRemarkNodeBase {
+ type: 'blockquote';
+ children: MarkdownRemarkBlockContent[];
+}
+
+export interface MarkdownRemarkListItem extends MarkdownRemarkNodeBase {
+ type: 'listItem';
+ checked?: boolean | null;
+ /** Only a falsy value round-trips; Astryx has no loose-item contract. */
+ spread?: boolean | null;
+ children: MarkdownRemarkBlockContent[];
+}
+
+export interface MarkdownRemarkList extends MarkdownRemarkNodeBase {
+ type: 'list';
+ ordered: boolean;
+ start?: number | null;
+ spread?: boolean | null;
+ /** Astryx-preserved ordered-list marker delimiter. */
+ delimiter?: '.' | ')';
+ children: MarkdownRemarkListItem[];
+}
+
+export type MarkdownRemarkTableAlignment = 'left' | 'center' | 'right' | null;
+
+export interface MarkdownRemarkTableCell extends MarkdownRemarkNodeBase {
+ type: 'tableCell';
+ children: MarkdownRemarkPhrasingContent[];
+}
+
+export interface MarkdownRemarkTableRow extends MarkdownRemarkNodeBase {
+ type: 'tableRow';
+ children: MarkdownRemarkTableCell[];
+}
+
+export interface MarkdownRemarkTable extends MarkdownRemarkNodeBase {
+ type: 'table';
+ align: MarkdownRemarkTableAlignment[];
+ children: MarkdownRemarkTableRow[];
+}
+
+export interface MarkdownRemarkThematicBreak extends MarkdownRemarkNodeBase {
+ type: 'thematicBreak';
+}
+
+export type MarkdownRemarkBlockContent =
+ | MarkdownRemarkHeading
+ | MarkdownRemarkParagraph
+ | MarkdownRemarkCode
+ | MarkdownRemarkMath
+ | MarkdownRemarkBlockquote
+ | MarkdownRemarkList
+ | MarkdownRemarkTable
+ | MarkdownRemarkThematicBreak
+ | MarkdownRemarkImage
+ | MarkdownRemarkExtension;
+
+export interface MarkdownRemarkRoot extends MarkdownRemarkNodeBase {
+ type: 'root';
+ children: MarkdownRemarkBlockContent[];
+}
+
+/* ------------------------------------------------------------------ *
+ * Public constrained file and plugin shapes
+ * ------------------------------------------------------------------ */
+
+export interface MarkdownRemarkMessage {
+ reason: string;
+ fatal: boolean;
+ place: unknown;
+ ruleId: string | null;
+ toString(): string;
+}
+
+/**
+ * The isolated per-invocation file. It exposes readonly source text, finite
+ * JSON-like data, and diagnostics — never processor registration, cross-run
+ * state, a compiler, I/O, or asynchronous completion.
+ */
+export interface MarkdownRemarkFile {
+ readonly value: string;
+ readonly data: {[key: string]: unknown};
+ readonly messages: MarkdownRemarkMessage[];
+ message(
+ reason: string | Error,
+ place?: unknown,
+ ruleId?: string,
+ ): MarkdownRemarkMessage;
+ fail(reason: string | Error, place?: unknown, ruleId?: string): never;
+ toString(): string;
+}
+
+/**
+ * A Remark transformer either mutates the tree and returns nothing or returns
+ * a replacement root, and an attacher may legitimately return nothing at all.
+ * Both shapes have to stay assignable, so `void` belongs in these unions.
+ */
+// eslint-disable-next-line @typescript-eslint/no-invalid-void-type -- see above
+type Returned<Value> = Value | undefined | void;
+
+export type MarkdownRemarkTransformer = (
+ tree: MarkdownRemarkRoot,
+ file: MarkdownRemarkFile,
+) => Returned<MarkdownRemarkRoot>;
+
+export type MarkdownRemarkPlugin<
+ Settings extends ReadonlyArray<unknown> = readonly [],
+> = (...settings: Settings) => Returned<MarkdownRemarkTransformer>;
+
+/**
+ * The structural shape a conventional Unified/Remark plugin already has. Its
+ * declared transformer may take Unified's callback parameter and may declare
+ * an asynchronous return union, so an existing typed plugin type-checks at the
+ * callsite without being rewritten. The adapter rejects an actual promise, and
+ * a callback-style transformer, at run time instead.
+ *
+ * Authoring a new plugin against Astryx? Annotate it with
+ * `MarkdownRemarkPlugin` to keep a typed tree and file.
+ */
+export type MarkdownRemarkCompatibleTransformer = (...args: never[]) => unknown;
+
+export type MarkdownRemarkCompatiblePlugin<
+ Settings extends ReadonlyArray<unknown> = readonly [],
+> = (...settings: Settings) => Returned<MarkdownRemarkCompatibleTransformer>;
+
+/* ------------------------------------------------------------------ *
+ * Internal helpers
+ * ------------------------------------------------------------------ */
+
+type UnknownRecord = Record<string, unknown>;
+
+/** Links a mutable copy back to the canonical node it was copied from. */
+const REMARK_ORIGIN = Symbol('astryx.markdown.remarkOrigin');
+
+/** hast escape channels; they are raw-markup sinks, not Markdown data. */
+const RAW_MARKUP_DATA_KEYS: ReadonlyArray<string> = [
+ 'hName',
+ 'hProperties',
+ 'hChildren',
+];
+
+const PHRASING_TYPES = new Set([
+ 'text',
+ 'inlineCode',
+ 'inlineMath',
+ 'break',
+ 'strong',
+ 'emphasis',
+ 'delete',
+ 'link',
+ 'image',
+ 'citation',
+]);
+
+const BLOCK_TYPES = new Set([
+ 'heading',
+ 'paragraph',
+ 'code',
+ 'math',
+ 'blockquote',
+ 'list',
+ 'table',
+ 'thematicBreak',
+ 'image',
+]);
+
+const PHRASING_PARENTS = new Set([
+ 'heading',
+ 'paragraph',
+ 'strong',
+ 'emphasis',
+ 'delete',
+ 'link',
+ 'tableCell',
+]);
+
+const BLOCK_PARENTS = new Set(['root', 'blockquote', 'listItem']);
+
+const FIELDS_BY_TYPE: Readonly<Record<string, ReadonlyArray<string>>> = {
+ root: ['children'],
+ paragraph: ['children'],
+ heading: ['depth', 'children'],
+ blockquote: ['children'],
+ strong: ['children'],
+ emphasis: ['children'],
+ delete: ['children'],
+ tableRow: ['children'],
+ tableCell: ['children'],
+ text: ['value'],
+ inlineCode: ['value'],
+ inlineMath: ['value'],
+ math: ['value'],
+ code: ['lang', 'meta', 'value'],
+ link: ['url', 'title', 'children'],
+ image: ['url', 'title', 'alt'],
+ list: ['ordered', 'start', 'spread', 'delimiter', 'children'],
+ listItem: ['checked', 'spread', 'children'],
+ table: ['align', 'children'],
+ thematicBreak: [],
+ break: [],
+ citation: ['sourceId'],
+ extension: ['plugin', 'name', 'display', 'source'],
+};
+
+/**
+ * MDAST node kinds Astryx recognizes by name but deliberately does not
+ * support. Naming them makes a rejection actionable while keeping every
+ * diagnostic built from adapter-owned vocabulary only.
+ */
+const NAMED_UNSUPPORTED_TYPES: ReadonlySet<string> = new Set([
+ 'html',
+ 'yaml',
+ 'toml',
+ 'definition',
+ 'footnote',
+ 'footnoteDefinition',
+ 'footnoteReference',
+ 'imageReference',
+ 'linkReference',
+ 'containerDirective',
+ 'leafDirective',
+ 'textDirective',
+ 'mdxjsEsm',
+ 'mdxFlowExpression',
+ 'mdxTextExpression',
+ 'mdxJsxFlowElement',
+ 'mdxJsxTextElement',
+]);
+
+/**
+ * VFile keys the profile knows about and refuses. Naming them makes the
+ * refusal actionable while keeping diagnostics free of plugin-chosen text.
+ */
+const NAMED_UNSUPPORTED_FILE_KEYS: ReadonlySet<string> = new Set([
+ 'path',
+ 'cwd',
+ 'history',
+ 'basename',
+ 'dirname',
+ 'extname',
+ 'stem',
+ 'stored',
+ 'result',
+ 'map',
+ 'contents',
+]);
+
+/** The one reason reported when a plugin declares the document unsupported. */
+const FAILED_BY_PLUGIN = 'the plugin reported the document as unsupported';
+
+/**
+ * A closed rejection.
+ *
+ * Its reason is assembled only from this module's own constants, so it can
+ * never carry document source, plugin-authored text, or a plugin-chosen
+ * identifier — see `knownType` and `knownField`.
+ */
+class RemarkAdapterRejection extends Error {}
+
+/**
+ * The reason for each rejection this module raised, keyed by the thrown
+ * object.
+ *
+ * A plugin that catches one of our rejections can reach the class through
+ * `error.constructor` and throw a forgery, and `message` is writable on any
+ * Error — so neither the class nor the message is evidence. Only a throw this
+ * registry recorded is trusted, and its reason is read from here.
+ */
+const adapterReasons = new WeakMap<RemarkAdapterRejection, string>();
+
+/**
+ * Sticky failure state for the run currently on the stack.
+ *
+ * Every rejection this module raises is recorded here, not only on the throw:
+ * a plugin can wrap any adapter call in `try`/`catch` — a prohibited file
+ * read, a write, a `delete`, a processor access — and carry on as if it had
+ * not happened. The run must still fail, so the verdict lives somewhere the
+ * plugin cannot reach or rewrite.
+ *
+ * Runs never overlap: the adapter is synchronous and rejects anything
+ * asynchronous, so a single module-level slot is the whole story.
+ */
+let activeRun: RunState | null = null;
+
+interface RunState {
+ failed: boolean;
+ reason: string | null;
+}
+
+function createRunState(): RunState {
+ return {failed: false, reason: null};
+}
+
+function reject(reason: string): never {
+ if (activeRun != null && !activeRun.failed) {
+ activeRun.failed = true;
+ activeRun.reason = reason;
+ }
+ const rejection = new RemarkAdapterRejection(reason);
+ adapterReasons.set(rejection, reason);
+ throw rejection;
+}
+
+/**
+ * Runs `work` with `state` as the sticky failure target, restoring whatever
+ * was active before.
+ */
+function withRunState<Result>(state: RunState, work: () => Result): Result {
+ const previous = activeRun;
+ activeRun = state;
+ try {
+ return work();
+ } finally {
+ activeRun = previous;
+ }
+}
+
+/**
+ * Reports whether a value is thenable and, if it is, attaches a handler.
+ *
+ * An already-rejected promise with no handler becomes an unhandled rejection:
+ * it ends a Node SSR process by default, and its reason came from the plugin,
+ * so it would print document text the diagnostics work hard to keep out. The
+ * value is refused either way; attaching a handler only makes the refusal
+ * quiet.
+ *
+ * `then` is read exactly once. It may be a hostile getter — reading it can
+ * throw, or trip a guard of its own — so this never reads it a second time to
+ * re-ask the same question.
+ */
+function defuseThenable(value: unknown): boolean {
+ if (
+ (typeof value !== 'object' && typeof value !== 'function') ||
+ value === null
+ ) {
+ return false;
+ }
+ let then: unknown;
+ try {
+ then = (value as {then?: unknown}).then;
+ } catch {
+ // A `then` accessor that throws is a thenable-shaped hostile value.
+ return true;
+ }
+ if (typeof then !== 'function') {
+ return false;
+ }
+ try {
+ then.call(
+ value,
+ () => {},
+ () => {},
+ );
+ } catch {
+ // A `then` that throws when called is refused all the same.
+ }
+ return true;
+}
+
+/** Echoes a node type only when it is adapter-owned vocabulary. */
+function knownType(type: unknown): string {
+ return typeof type === 'string' &&
+ (Object.prototype.hasOwnProperty.call(FIELDS_BY_TYPE, type) ||
+ NAMED_UNSUPPORTED_TYPES.has(type))
+ ? type
+ : 'unknown';
+}
+
+/**
+ * Echoes a file key only when it is a name this module already documents —
+ * the supported surface, or an unsupported VFile key the profile explicitly
+ * names. A plugin-chosen key is never echoed.
+ */
+function knownFileKey(property: string | symbol): string {
+ const key = typeof property === 'symbol' ? 'unknown' : property;
+ return FILE_SURFACE.has(key) || NAMED_UNSUPPORTED_FILE_KEYS.has(key)
+ ? key
+ : 'unknown';
+}
+
+/** Echoes a field name only when it is adapter-owned vocabulary. */
+function knownField(type: string, field: string): string {
+ return field === 'position' ||
+ field === 'data' ||
+ field === 'type' ||
+ RAW_MARKUP_DATA_KEYS.includes(field) ||
+ (FIELDS_BY_TYPE[type]?.includes(field) ?? false)
+ ? field
+ : 'unknown';
+}
+
+function isPlainObject(value: unknown): value is UnknownRecord {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ return false;
+ }
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+const POINT_FIELDS: ReadonlyArray<string> = ['line', 'column', 'offset'];
+const POSITION_FIELDS: ReadonlyArray<string> = ['start', 'end'];
+
+function samePoint(left: unknown, right: unknown): boolean {
+ if (!isPlainObject(left) || !isPlainObject(right)) {
+ return false;
+ }
+ for (const point of [left, right]) {
+ for (const field of Object.keys(point)) {
+ if (!POINT_FIELDS.includes(field)) {
+ return false;
+ }
+ }
+ }
+ return POINT_FIELDS.every(field => left[field] === right[field]);
+}
+
+/**
+ * Exact provenance equality: every line, column, and offset on both points.
+ * Comparing offsets alone would let a shifted line or column through, and the
+ * adapter must never quietly restore Core's position over a changed one.
+ */
+function samePosition(left: unknown, right: unknown): boolean {
+ if (left === undefined || right === undefined) {
+ return left === right;
+ }
+ if (!isPlainObject(left) || !isPlainObject(right)) {
+ return false;
+ }
+ for (const position of [left, right]) {
+ for (const field of Object.keys(position)) {
+ if (!POSITION_FIELDS.includes(field)) {
+ return false;
+ }
+ }
+ }
+ return samePoint(left.start, right.start) && samePoint(left.end, right.end);
+}
+
+function copyPoint(point: unknown): MarkdownRemarkPoint | undefined {
+ if (!isPlainObject(point)) {
+ return undefined;
+ }
+ const copy: MarkdownRemarkPoint = {};
+ if (typeof point.line === 'number') {
+ copy.line = point.line;
+ }
+ if (typeof point.column === 'number') {
+ copy.column = point.column;
+ }
+ if (typeof point.offset === 'number') {
+ copy.offset = point.offset;
+ }
+ return copy;
+}
+
+function copyPosition(position: unknown): MarkdownRemarkPosition | undefined {
+ if (!isPlainObject(position)) {
+ return undefined;
+ }
+ const start = copyPoint(position.start);
+ const end = copyPoint(position.end);
+ return start == null || end == null ? undefined : {start, end};
+}
+
+function copyData<Value>(value: Value): Value {
+ if (Array.isArray(value)) {
+ const copy: unknown[] = [];
+ for (const entry of value) {
+ copy.push(copyData(entry));
+ }
+ return copy as Value;
+ }
+ if (isPlainObject(value)) {
+ const copy: UnknownRecord = {};
+ for (const [key, nested] of Object.entries(value)) {
+ copy[key] = copyData(nested);
+ }
+ return copy as Value;
+ }
+ return value;
+}
+
+function sameJsonValue(left: unknown, right: unknown): boolean {
+ if (left === right) {
+ return true;
+ }
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return (
+ left.length === right.length &&
+ left.every((item, index) => sameJsonValue(item, right[index]))
+ );
+ }
+ if (isPlainObject(left) && isPlainObject(right)) {
+ const leftKeys = Object.keys(left);
+ const rightKeys = Object.keys(right);
+ return (
+ leftKeys.length === rightKeys.length &&
+ leftKeys.every(
+ key => key in right && sameJsonValue(left[key], right[key]),
+ )
+ );
+ }
+ return false;
+}
+
+/* ------------------------------------------------------------------ *
+ * Canonical tree → fresh mutable Remark tree
+ * ------------------------------------------------------------------ */
+
+interface OriginIndex {
+ readonly all: Set<UnknownRecord>;
+}
+
+function createOriginIndex(): OriginIndex {
+ return {all: new Set()};
+}
+
+function indexOrigin(node: UnknownRecord, index: OriginIndex): void {
+ index.all.add(node);
+}
+
+function toRemarkChildren(
+ children: unknown,
+ index: OriginIndex,
+): UnknownRecord[] {
+ return Array.isArray(children)
+ ? children.map(child => toRemarkNode(child as UnknownRecord, index))
+ : [];
+}
+
+function toRemarkNode(node: UnknownRecord, index: OriginIndex): UnknownRecord {
+ indexOrigin(node, index);
+ const copy: UnknownRecord = {type: node.type};
+ switch (node.type) {
+ case 'root':
+ case 'paragraph':
+ case 'blockquote':
+ case 'strong':
+ case 'emphasis':
+ case 'delete':
+ case 'tableRow':
+ case 'tableCell':
+ case 'listItem':
+ if (node.type === 'listItem' && typeof node.checked === 'boolean') {
+ copy.checked = node.checked;
+ }
+ copy.children = toRemarkChildren(node.children, index);
+ break;
+ case 'heading':
+ copy.depth = node.depth;
+ copy.children = toRemarkChildren(node.children, index);
+ break;
+ case 'text':
+ case 'inlineCode':
+ case 'inlineMath':
+ case 'math':
+ copy.value = node.value;
+ break;
+ case 'code':
+ copy.lang = node.lang ?? null;
+ // Astryx stores an absent info string as no key; MDAST spells it
+ // `null`. Both conversions translate, so authored fence metadata —
+ // which the semantic-fence helper reads — survives the round trip.
+ copy.meta = node.meta ?? null;
+ copy.value = node.value;
+ break;
+ case 'link':
+ copy.url = node.url;
+ copy.title = null;
+ copy.children = toRemarkChildren(node.children, index);
+ break;
+ case 'image':
+ copy.url = node.url;
+ copy.title = null;
+ copy.alt = node.alt;
+ break;
+ case 'list':
+ copy.ordered = node.ordered;
+ if (node.start !== undefined) {
+ copy.start = node.start;
+ }
+ if (node.spread !== undefined) {
+ copy.spread = node.spread;
+ }
+ if (node.delimiter !== undefined) {
+ copy.delimiter = node.delimiter;
+ }
+ copy.children = toRemarkChildren(node.children, index);
+ break;
+ case 'table':
+ copy.align = Array.isArray(node.align) ? [...node.align] : [];
+ copy.children = toRemarkChildren(node.children, index);
+ break;
+ case 'citation':
+ copy.sourceId = node.sourceId;
+ break;
+ case 'extension':
+ copy.plugin = node.plugin;
+ copy.name = node.name;
+ copy.display = node.display;
+ if (node.source !== undefined) {
+ copy.source = node.source;
+ }
+ break;
+ default:
+ break;
+ }
+ if (node.data !== undefined) {
+ copy.data = copyData(node.data);
+ }
+ const position = copyPosition(node.position);
+ if (position != null) {
+ copy.position = position;
+ }
+ // Enumerable so an immutable-style plugin that spreads a node keeps its
+ // provenance; symbol-keyed so it never reaches JSON, data, or rendering.
+ Object.defineProperty(copy, REMARK_ORIGIN, {
+ configurable: false,
+ enumerable: true,
+ value: node,
+ writable: false,
+ });
+ return copy;
+}
+
+/* ------------------------------------------------------------------ *
+ * Mutated Remark tree → validated canonical tree
+ * ------------------------------------------------------------------ */
+
+interface BackContext {
+ readonly index: OriginIndex;
+ readonly used: Set<UnknownRecord>;
+}
+
+/**
+ * Resolves the canonical node a transformed node came from.
+ *
+ * Provenance travels on an enumerable symbol the adapter puts on every copy,
+ * so a plugin that spreads a node (`{...node}`) keeps it. Nothing else counts:
+ * a node that merely looks like a source node — same position, same
+ * discriminants, rebuilt from scratch — is a forgery, not provenance, and is
+ * rejected rather than matched.
+ */
+function resolveOrigin(
+ node: UnknownRecord,
+ type: string,
+ context: BackContext,
+): UnknownRecord | null {
+ const linked = (node as {[REMARK_ORIGIN]?: unknown})[REMARK_ORIGIN];
+ if (linked === undefined) {
+ return null;
+ }
+ if (!isPlainObject(linked) || !context.index.all.has(linked)) {
+ reject(`a "${knownType(type)}" node carries forged provenance`);
+ }
+ if (linked.type !== type) {
+ reject(`a source "${knownType(linked.type)}" node cannot be retyped`);
+ }
+ if (context.used.has(linked)) {
+ reject(`a source "${knownType(type)}" node cannot be duplicated`);
+ }
+ context.used.add(linked);
+ return linked;
+}
+
+function assertKnownFields(type: string, node: UnknownRecord): void {
+ const allowed = FIELDS_BY_TYPE[type];
+ for (const key of Object.keys(node)) {
+ if (
+ key !== 'type' &&
+ key !== 'position' &&
+ key !== 'data' &&
+ !allowed.includes(key)
+ ) {
+ reject(
+ `a "${knownType(type)}" node cannot carry the unsupported field "${knownField(type, key)}"`,
+ );
+ }
+ }
+}
+
+function convertData(
+ type: string,
+ value: unknown,
+): MarkdownAstDataValue | undefined {
+ if (value === undefined) {
+ return undefined;
+ }
+ if (isPlainObject(value)) {
+ for (const key of RAW_MARKUP_DATA_KEYS) {
+ if (key in value) {
+ reject(
+ `a "${knownType(type)}" node cannot carry the raw-markup data channel "${key}"`,
+ );
+ }
+ }
+ }
+ if (!isMarkdownPluginData(value)) {
+ reject(
+ `a "${knownType(type)}" node's data must be finite JSON-like values`,
+ );
+ }
+ return copyData(value);
+}
+
+function requireString(type: string, field: string, value: unknown): string {
+ if (typeof value !== 'string') {
+ reject(
+ `a "${knownType(type)}" node requires a string "${knownField(type, field)}"`,
+ );
+ }
+ return value;
+}
+
+function requireAbsentText(type: string, field: string, value: unknown): void {
+ if (value !== undefined && value !== null && value !== '') {
+ reject(
+ `a "${knownType(type)}" node's "${knownField(type, field)}" has no Astryx representation`,
+ );
+ }
+}
+
+function assertPlacement(
+ type: string,
+ node: UnknownRecord,
+ parentType: string | null,
+ insideLink: boolean,
+): void {
+ if (parentType == null) {
+ return;
+ }
+ if (type === 'root') {
+ reject('a document can only contain one root');
+ }
+ const display = type === 'extension' ? node.display : undefined;
+ const phrasing = PHRASING_TYPES.has(type) || display === 'inline';
+ const block = BLOCK_TYPES.has(type) || display === 'block';
+ if (
+ (PHRASING_PARENTS.has(parentType) && !phrasing) ||
+ (BLOCK_PARENTS.has(parentType) && !block) ||
+ (parentType === 'list' && type !== 'listItem') ||
+ (parentType === 'table' && type !== 'tableRow') ||
+ (parentType === 'tableRow' && type !== 'tableCell')
+ ) {
+ reject(
+ `a "${knownType(type)}" node cannot be a child of a "${knownType(parentType)}" node`,
+ );
+ }
+ if (insideLink && type === 'link') {
+ reject('a link cannot be nested inside another link');
+ }
+}
+
+function sameCanonicalFields(
+ origin: UnknownRecord,
+ fields: UnknownRecord,
+): boolean {
+ // Canonical nodes may carry explicitly undefined optional keys; an absent
+ // key and an undefined key mean the same thing.
+ const originKeys = Object.keys(origin).filter(
+ key => key !== 'type' && origin[key] !== undefined,
+ );
+ const fieldKeys = Object.keys(fields).filter(
+ key => fields[key] !== undefined,
+ );
+ if (originKeys.length !== fieldKeys.length) {
+ return false;
+ }
+ for (const key of fieldKeys) {
+ const next = fields[key];
+ const previous = origin[key];
+ if (next === previous) {
+ continue;
+ }
+ if (Array.isArray(next) && Array.isArray(previous)) {
+ if (
+ next.length !== previous.length ||
+ next.some((item, position) => item !== previous[position])
+ ) {
+ return false;
+ }
+ continue;
+ }
+ if (!sameJsonValue(next, previous)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function buildCanonicalNode(
+ type: string,
+ fields: UnknownRecord,
+ origin: UnknownRecord | null,
+): UnknownRecord {
+ if (origin != null && sameCanonicalFields(origin, fields)) {
+ return origin;
+ }
+ const built: UnknownRecord = {type, ...fields};
+ if (origin != null) {
+ // Carries Core's own enumerable symbol markers (source-heading identity)
+ // onto the replacement so Core still recognizes the node it authored.
+ for (const marker of Object.getOwnPropertySymbols(origin)) {
+ if (Object.prototype.propertyIsEnumerable.call(origin, marker)) {
+ Object.defineProperty(built, marker, {
+ configurable: false,
+ enumerable: true,
+ value: (origin as UnknownRecord & {[key: symbol]: unknown})[marker],
+ writable: false,
+ });
+ }
+ }
+ }
+ return built;
+}
+
+function fromRemarkChildren(
+ children: unknown,
+ type: string,
+ insideLink: boolean,
+ context: BackContext,
+): UnknownRecord[] {
+ if (!Array.isArray(children)) {
+ reject(`a "${knownType(type)}" node requires a children array`);
+ }
+ return children.map(child =>
+ fromRemarkNode(child, type, insideLink || type === 'link', context),
+ );
+}
+
+function fromRemarkNode(
+ value: unknown,
+ parentType: string | null,
+ insideLink: boolean,
+ context: BackContext,
+): UnknownRecord {
+ if (!isPlainObject(value)) {
+ reject('every transformed node must be a plain object');
+ }
+ const type = value.type;
+ if (typeof type !== 'string') {
+ reject('every transformed node requires a string type');
+ }
+ if (type === 'html') {
+ reject('raw HTML has no Astryx representation');
+ }
+ if (!(type in FIELDS_BY_TYPE)) {
+ reject(
+ `the node type "${knownType(type)}" is outside the supported MDAST subset`,
+ );
+ }
+ assertKnownFields(type, value);
+ assertPlacement(type, value, parentType, insideLink);
+
+ const origin = resolveOrigin(value, type, context);
+ if (origin == null) {
+ if (value.position !== undefined) {
+ reject(`a new "${knownType(type)}" node cannot carry a source position`);
+ }
+ } else if (!samePosition(value.position, origin.position)) {
+ // Covers a removed, rebuilt, offset-shifted, and line/column-shifted
+ // position alike. Core's position is never restored over a changed one.
+ reject(
+ `a source "${knownType(type)}" node's position must stay exactly as Core authored it`,
+ );
+ }
+
+ const fields: UnknownRecord = {};
+ switch (type) {
+ case 'root':
+ case 'paragraph':
+ case 'blockquote':
+ case 'strong':
+ case 'emphasis':
+ case 'delete':
+ case 'tableRow':
+ case 'tableCell':
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ case 'heading': {
+ const depth = value.depth;
+ if (
+ typeof depth !== 'number' ||
+ !Number.isInteger(depth) ||
+ depth < 1 ||
+ depth > 6
+ ) {
+ reject('a heading requires a depth between 1 and 6');
+ }
+ if (origin != null && origin.depth !== depth) {
+ reject("a source heading's depth cannot change");
+ }
+ fields.depth = depth;
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ }
+ case 'listItem': {
+ const checked = value.checked;
+ if (checked !== undefined && checked !== null) {
+ if (typeof checked !== 'boolean') {
+ reject('a list item requires a boolean "checked" value');
+ }
+ fields.checked = checked;
+ }
+ if (value.spread === true) {
+ reject('a loose list item has no Astryx representation');
+ }
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ }
+ case 'text':
+ case 'inlineCode':
+ case 'inlineMath':
+ case 'math':
+ fields.value = requireString(type, 'value', value.value);
+ break;
+ case 'code': {
+ const lang = value.lang;
+ if (lang !== undefined && lang !== null && typeof lang !== 'string') {
+ reject('a code node requires a string or null "lang"');
+ }
+ const meta = value.meta;
+ if (meta !== undefined && meta !== null && typeof meta !== 'string') {
+ reject('a code node requires a string or null "meta"');
+ }
+ fields.lang = lang ?? null;
+ if (meta != null && meta !== '') {
+ fields.meta = meta;
+ }
+ fields.value = requireString(type, 'value', value.value);
+ break;
+ }
+ case 'link': {
+ const url = requireString(type, 'url', value.url);
+ if (!isSafeMarkdownParserUrl(url)) {
+ reject('a link destination was rejected by the navigation owner');
+ }
+ requireAbsentText(type, 'title', value.title);
+ fields.url = url;
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ }
+ case 'image': {
+ const url = requireString(type, 'url', value.url);
+ if (!isSafeMarkdownParserUrl(url)) {
+ reject('an image source was rejected by the resource owner');
+ }
+ requireAbsentText(type, 'title', value.title);
+ if (typeof value.alt !== 'string') {
+ reject('an image requires its text alternative');
+ }
+ fields.url = url;
+ fields.alt = value.alt;
+ break;
+ }
+ case 'list': {
+ if (typeof value.ordered !== 'boolean') {
+ reject('a list requires a boolean "ordered" value');
+ }
+ fields.ordered = value.ordered;
+ const start = value.start;
+ if (start !== undefined && start !== null) {
+ if (typeof start !== 'number' || !Number.isFinite(start)) {
+ reject('a list requires a finite "start" value');
+ }
+ fields.start = start;
+ }
+ if (typeof value.spread === 'boolean') {
+ fields.spread = value.spread;
+ }
+ const delimiter = value.delimiter;
+ if (delimiter !== undefined) {
+ if (delimiter !== '.' && delimiter !== ')') {
+ reject('a list requires a "." or ")" delimiter');
+ }
+ fields.delimiter = delimiter;
+ }
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ }
+ case 'table': {
+ const align = value.align;
+ if (
+ !Array.isArray(align) ||
+ !align.every(
+ entry =>
+ entry === null ||
+ entry === 'left' ||
+ entry === 'center' ||
+ entry === 'right',
+ )
+ ) {
+ reject('a table requires normalized alignment values');
+ }
+ fields.align = [...align];
+ fields.children = fromRemarkChildren(
+ value.children,
+ type,
+ insideLink,
+ context,
+ );
+ break;
+ }
+ case 'thematicBreak':
+ case 'break':
+ break;
+ case 'citation':
+ case 'extension': {
+ // Astryx owns these outright: the adapter can show one to a plugin but
+ // never lets one be authored or edited, so every field must come back
+ // exactly as it went out.
+ const unchanged =
+ origin != null &&
+ sameJsonValue(value.data, origin.data) &&
+ (type === 'citation'
+ ? value.sourceId === origin.sourceId
+ : value.plugin === origin.plugin &&
+ value.name === origin.name &&
+ value.display === origin.display &&
+ value.source === origin.source);
+ if (!unchanged) {
+ reject(
+ `an Astryx "${knownType(type)}" node cannot be authored or changed here`,
+ );
+ }
+ // Equality across every owned field proves the node round-tripped, so
+ // the canonical node itself stays in place.
+ return origin;
+ }
+ default:
+ reject(
+ `the node type "${knownType(type)}" is outside the supported MDAST subset`,
+ );
+ }
+
+ const data = convertData(type, value.data);
+ if (data !== undefined) {
+ fields.data = data;
+ }
+ if (origin != null && origin.position !== undefined) {
+ fields.position = origin.position;
+ }
+
+ const node = buildCanonicalNode(type, fields, origin);
+ if (type === 'table' && node !== origin) {
+ const rows = fields.children as UnknownRecord[];
+ const width = (rows[0]?.children as unknown[] | undefined)?.length ?? 0;
+ if (
+ rows.some(
+ row => (row.children as unknown[] | undefined)?.length !== width,
+ )
+ ) {
+ reject('a transformed table cannot have ragged rows');
+ }
+ }
+ return node;
+}
+
+/* ------------------------------------------------------------------ *
+ * Constrained file and processor guard
+ * ------------------------------------------------------------------ */
+
+function createMessage(
+ reason: string | Error,
+ place: unknown,
+ ruleId: string | undefined,
+): MarkdownRemarkMessage {
+ const text = reason instanceof Error ? reason.message : reason;
+ return {
+ reason: text,
+ fatal: false,
+ place: place ?? null,
+ ruleId: ruleId ?? null,
+ toString() {
+ return text;
+ },
+ };
+}
+
+/**
+ * The documented surface of the constrained file. Everything else — `path`,
+ * `cwd`, `history`, `basename`, `dirname`, `extname`, `stem`, `stored`, and
+ * any other key — is unsupported: the adapter has no filesystem, no processor,
+ * and no run history to answer with.
+ */
+const FILE_SURFACE: ReadonlySet<string> = new Set([
+ 'value',
+ 'data',
+ 'messages',
+ 'message',
+ 'fail',
+ 'toString',
+]);
+
+/**
+ * Adapter-owned data for one invocation.
+ *
+ * It lives here rather than on the file the plugin holds, because everything
+ * the plugin can reach it can also rewrite — a plugin must not be able to
+ * fake a `fatal` message or hide one it caused. The failure verdict itself
+ * belongs to the run (`RunState`), which every rejection records.
+ */
+interface FileState {
+ readonly data: UnknownRecord;
+}
+
+function createConstrainedFile(source: string): {
+ readonly file: MarkdownRemarkFile;
+ readonly state: FileState;
+} {
+ const messages: MarkdownRemarkMessage[] = [];
+ const state: FileState = {data: {}};
+ const target: MarkdownRemarkFile = {
+ get value() {
+ return source;
+ },
+ get data() {
+ return state.data;
+ },
+ get messages() {
+ return messages;
+ },
+ message(reason, place, ruleId) {
+ const message = createMessage(reason, place, ruleId);
+ messages.push(message);
+ return message;
+ },
+ fail(reason, place, ruleId) {
+ const message = createMessage(reason, place, ruleId);
+ message.fatal = true;
+ messages.push(message);
+ // `reject` records the verdict in run state, so a plugin that catches
+ // this and carries on has still declared the document unsupported and
+ // the run cannot succeed behind its back.
+ reject(FAILED_BY_PLUGIN);
+ },
+ toString() {
+ return source;
+ },
+ };
+
+ // Fails closed on every unsupported read and on every write. Returning
+ // `undefined` for `file.cwd` would let a plugin silently take a path that
+ // depends on a capability this profile does not have.
+ /* eslint-disable @typescript-eslint/promise-function-async -- these are
+ Proxy traps, not async work; the adapter is synchronous throughout. */
+ const file = new Proxy(target, {
+ get(_target, property, receiver) {
+ if (typeof property === 'symbol') {
+ // JS protocol (inspection, iteration, `instanceof`), not VFile
+ // surface. Answering `undefined` here cannot mislead a plugin.
+ return Reflect.get(target, property, receiver) as unknown;
+ }
+ if (!FILE_SURFACE.has(property)) {
+ reject(`the file has no "${knownFileKey(property)}" in this profile`);
+ }
+ return Reflect.get(target, property, receiver) as unknown;
+ },
+ set(_target, property) {
+ reject(
+ `the file's "${knownFileKey(property)}" cannot be assigned in this profile`,
+ );
+ },
+ defineProperty(_target, property) {
+ reject(
+ `the file's "${knownFileKey(property)}" cannot be assigned in this profile`,
+ );
+ },
+ deleteProperty(_target, property) {
+ reject(
+ `the file's "${knownFileKey(property)}" cannot be assigned in this profile`,
+ );
+ },
+ // Truthfully answers "no such capability" so a plugin that feature-detects
+ // can take its own graceful path instead of being rejected.
+ has(_target, property) {
+ return typeof property === 'symbol' || FILE_SURFACE.has(property);
+ },
+ ownKeys() {
+ return [...FILE_SURFACE];
+ },
+ getOwnPropertyDescriptor(_target, property) {
+ return typeof property !== 'symbol' && !FILE_SURFACE.has(property)
+ ? undefined
+ : Reflect.getOwnPropertyDescriptor(target, property);
+ },
+ });
+ /* eslint-enable @typescript-eslint/promise-function-async */
+
+ return {file, state};
+}
+
+/**
+ * Stands in for Unified's processor. Any access fails closed, so parser,
+ * compiler, and cross-run `data()` registration cannot be mistaken for
+ * supported behavior.
+ */
+const PROCESSOR_ACCESS = 'processor registration is outside the adapter';
+
+const processorGuard: unknown = new Proxy(Object.freeze({}), {
+ get() {
+ reject(PROCESSOR_ACCESS);
+ },
+ set() {
+ reject(PROCESSOR_ACCESS);
+ },
+ defineProperty() {
+ reject(PROCESSOR_ACCESS);
+ },
+ deleteProperty() {
+ reject(PROCESSOR_ACCESS);
+ },
+ apply() {
+ reject(PROCESSOR_ACCESS);
+ },
+ has() {
+ // Truthful: this stand-in offers no processor capability at all.
+ return false;
+ },
+ ownKeys() {
+ return [];
+ },
+});
+
+/* ------------------------------------------------------------------ *
+ * Public adapter
+ * ------------------------------------------------------------------ */
+
+/**
+ * The one reason reported for a failed run.
+ *
+ * A rejection's reason is built from this module's own vocabulary, so it is
+ * safe to report. Anything a plugin authored — a thrown error's message, a
+ * `file.fail()` reason, a `file.message()` diagnostic — is not: the plugin
+ * read the document, so its text may quote it. Those stay on the file, which
+ * only the plugin sees.
+ */
+function describeFailure(error: unknown): string {
+ const reason =
+ error instanceof RemarkAdapterRejection
+ ? adapterReasons.get(error)
+ : undefined;
+ return reason ?? 'the plugin threw an error';
+}
+
+/**
+ * Adapt one synchronous transform-only Remark plugin to a Markdown transform.
+ *
+ * The adapted plugin receives a fresh mutable copy of the canonical document
+ * and an isolated constrained file. Every returned or mutated tree round-trips
+ * through the supported MDAST subset before it becomes observable; anything
+ * unsupported — a parser or compiler plugin, asynchronous work, processor
+ * state, raw HTML, an unsupported node, a forged position, or unrepresentable
+ * metadata — keeps the last valid document and reports one diagnostic.
+ *
+ * Compatibility is per plugin and proven by fixtures, never inferred from a
+ * package name.
+ *
+ * @example
+ * ```
+ * import {createMarkdownPlugin} from '@astryxdesign/core/Markdown';
+ * import {createMarkdownRemarkTransform} from '@astryxdesign/core/Markdown/remark';
+ *
+ * const shouting = createMarkdownPlugin({
+ * name: 'shouting-headings',
+ * apiVersion: 1,
+ * transform: createMarkdownRemarkTransform(remarkShoutingHeadings),
+ * });
+ * ```
+ */
+export function createMarkdownRemarkTransform<
+ Settings extends ReadonlyArray<unknown> = readonly [],
+>(
+ plugin: MarkdownRemarkPlugin<Settings>,
+ ...settings: Settings
+): MarkdownTransform<never>;
+export function createMarkdownRemarkTransform<
+ Settings extends ReadonlyArray<unknown> = readonly [],
+>(
+ plugin: MarkdownRemarkCompatiblePlugin<Settings>,
+ ...settings: Settings
+): MarkdownTransform<never>;
+export function createMarkdownRemarkTransform(
+ plugin: MarkdownRemarkCompatiblePlugin<ReadonlyArray<unknown>>,
+ ...settings: ReadonlyArray<unknown>
+): MarkdownTransform<never> {
+ if (typeof plugin !== 'function') {
+ throw new TypeError('Markdown Remark adapter: plugin must be a function');
+ }
+
+ let attached = false;
+ let transformer: MarkdownRemarkTransformer | null = null;
+ let attachFailure: string | null = null;
+
+ const attach = (): void => {
+ attached = true;
+ // The attacher can touch the processor guard and catch the rejection, so
+ // it gets its own sticky state; a swallowed capability access is still a
+ // failed attach.
+ const attachState = createRunState();
+ withRunState(attachState, () => {
+ try {
+ const created = (
+ plugin as (this: unknown, ...args: ReadonlyArray<unknown>) => unknown
+ ).apply(processorGuard, settings as unknown as unknown[]);
+ // Defuse before any verdict: an attacher that both tripped a guard
+ // and returned a rejected promise must not leave that promise
+ // unhandled just because the guard is reported instead.
+ const attacherIsAsync = defuseThenable(created);
+ if (attachState.failed) {
+ reject(attachState.reason ?? FAILED_BY_PLUGIN);
+ }
+ if (attacherIsAsync) {
+ reject('an asynchronous plugin is outside the adapter');
+ }
+ if (typeof created !== 'function') {
+ attachFailure =
+ 'only a transform-only plugin returning one synchronous transformer is supported';
+ return;
+ }
+ if (created.length >= 3) {
+ attachFailure =
+ 'a callback-style (asynchronous) transformer is outside the adapter';
+ return;
+ }
+ transformer = created as MarkdownRemarkTransformer;
+ } catch (error) {
+ attachFailure = describeFailure(error);
+ }
+ });
+ if (attachState.failed && attachFailure == null) {
+ attachFailure = attachState.reason;
+ transformer = null;
+ }
+ };
+
+ return (
+ document: MarkdownAstRoot<MarkdownAstExtensionNode>,
+ context: MarkdownTransformContext,
+ ): MarkdownAstRoot<MarkdownAstExtensionNode> => {
+ if (!attached) {
+ attach();
+ }
+ const runner = transformer;
+ if (runner == null) {
+ context.report(`Remark adapter: ${attachFailure ?? 'the plugin failed'}`);
+ return document;
+ }
+
+ const index = createOriginIndex();
+ const {file, state} = createConstrainedFile(context.source);
+ const run = createRunState();
+
+ return withRunState(run, () => {
+ try {
+ const tree = toRemarkNode(
+ document as unknown as UnknownRecord,
+ index,
+ ) as unknown as MarkdownRemarkRoot;
+ const returned = runner(tree, file);
+ // Defuse first, whatever else is wrong. A transformer that both
+ // swallowed a guard refusal and returned a rejected promise still
+ // gets that promise handled — the sticky verdict decides only what
+ // is *reported*, never whether the promise is left dangling.
+ const returnedIsAsync = defuseThenable(returned);
+ if (run.failed) {
+ // The plugin tripped a guard — a prohibited file key, a processor
+ // access, its own fail() — and swallowed the rejection. The verdict
+ // stands, and its original reason is the one reported.
+ reject(run.reason ?? FAILED_BY_PLUGIN);
+ }
+ if (returnedIsAsync) {
+ reject('an asynchronous transformer is outside the adapter');
+ }
+ const output = returned ?? tree;
+ if (!isMarkdownPluginData(state.data)) {
+ reject('file data must be finite JSON-like values');
+ }
+
+ const back: BackContext = {index, used: new Set()};
+ const root = fromRemarkNode(output, null, false, back);
+ if (root.type !== 'root') {
+ reject('a transformer must return the document root');
+ }
+ const children = root.children as UnknownRecord[];
+ if (
+ context.display === 'inline' &&
+ (children.length !== 1 || children[0]?.type !== 'paragraph')
+ ) {
+ reject(
+ 'an inline document must stay one paragraph of phrasing content',
+ );
+ }
+ if (run.failed) {
+ // Last word before the output becomes observable. A guard can fire
+ // after the earlier check — a hostile `then` accessor, a getter on
+ // a returned node — and a refusal the plugin caught must never end
+ // with its output accepted.
+ reject(run.reason ?? FAILED_BY_PLUGIN);
+ }
+ return root as unknown as MarkdownAstRoot<MarkdownAstExtensionNode>;
+ } catch (error) {
+ // Exactly one report per failed run, and never a second for the
+ // plugin's own messages — see `describeFailure`. The first recorded
+ // rejection outranks a later error, so swallowing one and throwing
+ // something friendlier cannot change what is reported.
+ context.report(
+ `Remark adapter: ${run.reason ?? describeFailure(error)}`,
+ );
+ return document;
+ }
+ });
+ };
+}
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 953f956915..ffc10330c2 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -107,7 +107,7 @@ const STATIC_EXPORTS = {
*
* See: https://github.com/facebook/astryx/issues/1977
*/
-const MODULE_SUBPATH_EXPORTS = ['Markdown/plugins'];
+const DIRECTORY_MODULE_SUBPATH_EXPORTS = ['Markdown/plugins'];
const UTIL_SUBPATH_DIRS = [
'Calendar',
@@ -119,6 +119,19 @@ const UTIL_SUBPATH_DIRS = [
'Typeahead',
];
+/**
+ * Optional module subpath exports.
+ *
+ * Separately imported modules that deliberately stay out of their component's
+ * own entry point, so a bundle that never imports the subpath never pulls the
+ * module in. Unlike `UTIL_SUBPATH_DIRS` these are not server-safe re-exports
+ * of an existing component — each one is its own opt-in module.
+ *
+ * `Markdown/remark` is the limited Remark compatibility adapter
+ * (`module:Markdown/remark`, `spec:AST-036` FR24).
+ */
+const FILE_MODULE_SUBPATH_EXPORTS = ['Markdown/remark'];
+
/**
* Discover all exportable directories under src/.
* A directory is exportable if it contains an index.ts file.
@@ -180,7 +193,7 @@ function buildExports() {
}
// Explicit nested module entry points.
- for (const modulePath of MODULE_SUBPATH_EXPORTS) {
+ for (const modulePath of DIRECTORY_MODULE_SUBPATH_EXPORTS) {
exports[`./${modulePath}`] = {
source: `./src/${modulePath}/index.ts`,
types: `./dist/${modulePath}/index.d.ts`,
@@ -197,6 +210,15 @@ function buildExports() {
};
}
+ // Optional, separately imported module subpaths
+ for (const subpath of FILE_MODULE_SUBPATH_EXPORTS) {
+ exports[`./${subpath}`] = {
+ source: `./src/${subpath}.ts`,
+ types: `./dist/${subpath}.d.ts`,
+ default: `./dist/${subpath}.js`,
+ };
+ }
+
return exports;
}