From 88df3a1f091eb90a81b8aa244e79f1267768466e Mon Sep 17 00:00:00 2001 From: onmax Date: Wed, 18 Nov 2026 17:11:44 +0100 Subject: [PATCH] feat(render): add comark/render/markdown, which renders Markdown without YAML `renderMarkdown` from `comark/render/markdown` writes CommonMark and GFM with the same handlers as `comark/render`, but leaves out the component serializer and frontmatter, the two paths that need js-yaml. Components are written as HTML (`markdown/html`) and frontmatter is dropped. The `mdc` handler moves out of the shared handler map and `comark/render` adds it back, so its output is unchanged. `comarkYamlAttributes` moves from `attributes.ts` into `mdc.ts`, its only caller, so the new entry's import graph has no YAML even without tree-shaking. --- AGENTS.md | 4 +- docs/content/5.reference/0.render.md | 32 ++++++ packages/comark/package.json | 3 +- .../src/internal/stringify/attributes.ts | 51 ---------- .../src/internal/stringify/handlers/index.ts | 4 +- .../src/internal/stringify/handlers/mdc.ts | 49 +++++++++- packages/comark/src/render/index.ts | 5 +- packages/comark/src/render/markdown.ts | 40 ++++++++ packages/comark/test/render-markdown.test.ts | 97 +++++++++++++++++++ test/bundle.test.ts | 2 +- 10 files changed, 229 insertions(+), 58 deletions(-) create mode 100644 packages/comark/src/render/markdown.ts create mode 100644 packages/comark/test/render-markdown.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1e9ef3741..1f0e4d075 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,7 @@ packages/comark/ │ ├── context.ts # Live renderer context: ComarkContext, ComarkDocument, ComarkPatch (comark/context) │ ├── render/ │ │ ├── index.ts # AST to Markdown string: renderMarkdown() (comark/render) +│ │ ├── markdown.ts # CommonMark/GFM string without YAML or component syntax (comark/render/markdown) │ │ └── html.ts # HTML-only string engine used by @comark/html (comark/render/html) │ ├── types.ts # MarkdownDocument, Node, ElementNode, TextNode, CommentNode, ParserOptions │ ├── plugins/ # Core plugins (comark/plugins/*) @@ -123,7 +124,7 @@ Framework-free HTML string rendering (`createHtmlRenderer`, `renderHtml`, `rende - Renders through `comark/render/html`, which registers only the `html` and `comment` handlers so Markdown serializers are never bundled. - `@comark/html/render` stays free of `js-yaml`; the root entry and plugins import the parser, which loads YAML for frontmatter. -- Shares `internal/stringify/state.ts` with `comark/render`. HTML attribute escaping lives in `html-attributes.ts`; Markdown/YAML attribute serialization stays in `attributes.ts`. +- Shares `internal/stringify/state.ts` with `comark/render`. HTML attribute escaping lives in `html-attributes.ts`; inline `{...}` attribute serialization stays in `attributes.ts`, and YAML block attributes live in `handlers/mdc.ts`, which only `comark/render` loads. ### `@comark/ansi` (`packages/comark-ansi/`) @@ -166,6 +167,7 @@ import { parseMarkdown, createMarkdownParser, autoCloseMarkdown, defineComarkPlu import { parseMarkdown } from 'comark/core' // no default plugins; autoClose takes a function, not a boolean import { autoCloseMarkdown } from 'comark/auto-close' import { renderMarkdown } from 'comark/render' +import { renderMarkdown } from 'comark/render/markdown' // no YAML: components as HTML, no frontmatter import type { ComarkContext, ComarkDocument, ComarkPatch } from 'comark/context' import type { MarkdownDocument, Node, ElementNode, TextNode, CommentNode, NodeTransform } from 'comark' import { diff --git a/docs/content/5.reference/0.render.md b/docs/content/5.reference/0.render.md index 4425dfaf1..dc0f0ba88 100644 --- a/docs/content/5.reference/0.render.md +++ b/docs/content/5.reference/0.render.md @@ -65,6 +65,38 @@ This is an alert For the complete parsed document and node types, see the [Document model](/getting-started/document-model#node-model). :: +### Plain Markdown without YAML + +`renderMarkdown` from `comark/render/markdown` writes CommonMark and GFM the same way, but does not load the YAML serializer, which keeps it small in a browser or edge bundle. It writes nodes that have no Markdown syntax, such as components, as HTML, and leaves frontmatter out. It takes the same `components`, `data`, `transformNode` and `headingIds` options. + +::code-group +```typescript [render.ts] +import { parseMarkdown } from 'comark' +import { renderMarkdown } from 'comark/render/markdown' + +const document = await parseMarkdown(`--- +title: Hello +--- + +# Hello **World** + +::alert{type="info"} +This is an alert +:: +`) + +const markdown = await renderMarkdown(document) +``` + +```markdown [Output] +# Hello **World** + + +This is an alert + +``` +:: + --- ## Options diff --git a/packages/comark/package.json b/packages/comark/package.json index 1c2ad0b40..880e8b989 100644 --- a/packages/comark/package.json +++ b/packages/comark/package.json @@ -56,7 +56,8 @@ "./auto-close": "./dist/auto-close.js", "./context": "./dist/context.js", "./render": "./dist/render/index.js", - "./render/html": "./dist/render/html.js" + "./render/html": "./dist/render/html.js", + "./render/markdown": "./dist/render/markdown.js" }, "publishConfig": { "access": "public" diff --git a/packages/comark/src/internal/stringify/attributes.ts b/packages/comark/src/internal/stringify/attributes.ts index 67091df0a..c8587a804 100644 --- a/packages/comark/src/internal/stringify/attributes.ts +++ b/packages/comark/src/internal/stringify/attributes.ts @@ -1,6 +1,3 @@ -import { stringifyYaml } from '../yaml.ts' -import { pickFence } from './fence.ts' - export { resolveAttributes, resolveAttribute } from './html-attributes.ts' export type { ResolveAttributesOptions } from './html-attributes.ts' @@ -108,51 +105,3 @@ export function comarkAttributes(attributes: Record) { return attrs.length > 0 ? `{${attrs}}` : '' } - -// Coerce string `'true'`/`'false'` (how inline `{attr}` parsing stores -// boolean-like attrs) to native booleans so js-yaml v5 emits them unquoted. -function normalizeValue(value: unknown): unknown { - if (value === 'true') return true - if (value === 'false') return false - return value -} - -/** Serialize attributes into a Comark YAML block (`codeblock` or `frontmatter`). */ -export function comarkYamlAttributes( - attributes: Record, - style: 'frontmatter' | 'codeblock' = 'codeblock' -) { - // Normalize attribute values for YAML serialization: - // - `:`-prefixed JSON literals (`:count="42"`, `:config={...}`) restore to - // native values and drop the prefix (matching @nuxtjs/mdc stringify). - // - `:`-prefixed path bindings (`:to="$doc.link"`) stay prefixed so they - // round-trip as bindings, not plain strings. - // - Bare string literals `'true'`/`'false'` from inline attrs coerce to bools. - const normalized = Object.fromEntries( - Object.entries(attributes).map(([key, value]) => { - if (key.startsWith(':')) { - if (typeof value === 'string') { - try { - // JSON number/boolean/null/object/array -> typed YAML key without `:` - return [key.slice(1), JSON.parse(value)] - } catch { - // Path binding / non-JSON string: keep the `:` key - return [key, value] - } - } - // Already-decoded object/array (processAttributes) or native value - return [key.slice(1), value] - } - return [key, normalizeValue(value)] - }) - ) - - const yamlContent = stringifyYaml(normalized).trim() - - if (style === 'frontmatter') { - return `---\n${yamlContent}\n---` - } - - const fence = pickFence(yamlContent) - return `${fence}yaml [props]\n${yamlContent}\n${fence}` -} diff --git a/packages/comark/src/internal/stringify/handlers/index.ts b/packages/comark/src/internal/stringify/handlers/index.ts index 8d86da76e..474d702bf 100644 --- a/packages/comark/src/internal/stringify/handlers/index.ts +++ b/packages/comark/src/internal/stringify/handlers/index.ts @@ -13,7 +13,6 @@ import { emphesis } from './emphesis.ts' import { blockquote } from './blockquote.ts' import { img } from './img.ts' import { del } from './del.ts' -import { mdc } from './mdc.ts' import { br } from './br.ts' import { template } from './template.ts' import { table, thead, tbody, tr, th, td } from './table.ts' @@ -22,6 +21,8 @@ import { math } from './math.ts' import { mermaid } from './mermaid.ts' import type { NodeHandler } from 'comark/render' +// `mdc` (component syntax, YAML attributes) is left out so `comark/render/markdown` +// stays free of YAML; `comark/render` adds it back. export const handlers: Record = { code, pre, @@ -44,7 +45,6 @@ export const handlers: Record = { blockquote, img, del, - mdc, template, table, thead, diff --git a/packages/comark/src/internal/stringify/handlers/mdc.ts b/packages/comark/src/internal/stringify/handlers/mdc.ts index 87db5af7b..9315389ee 100644 --- a/packages/comark/src/internal/stringify/handlers/mdc.ts +++ b/packages/comark/src/internal/stringify/handlers/mdc.ts @@ -1,7 +1,9 @@ import type { State } from 'comark/render' import type { ElementNode, Node } from 'comark' import { indent } from '../../../utils/index.ts' -import { comarkAttributes, comarkYamlAttributes } from '../attributes.ts' +import { stringifyYaml } from '../../yaml.ts' +import { comarkAttributes } from '../attributes.ts' +import { pickFence } from '../fence.ts' // HTML elements that always create an inline context for their children const INLINE_HTML_ELEMENTS = new Set(['a', 'strong', 'em', 'span']) @@ -78,3 +80,48 @@ export async function mdc(node: ElementNode, state: State, parent?: ElementNode) return inline ? result : indent(result, { level: parent && !afterList ? 1 : 0 }) } + +// Coerce string `'true'`/`'false'` (how inline `{attr}` parsing stores +// boolean-like attrs) to native booleans so js-yaml v5 emits them unquoted. +function normalizeValue(value: unknown): unknown { + if (value === 'true') return true + if (value === 'false') return false + return value +} + +/** Serialize attributes into a Comark YAML block (`codeblock` or `frontmatter`). */ +function comarkYamlAttributes(attributes: Record, style: 'frontmatter' | 'codeblock' = 'codeblock') { + // Normalize attribute values for YAML serialization: + // - `:`-prefixed JSON literals (`:count="42"`, `:config={...}`) restore to + // native values and drop the prefix (matching @nuxtjs/mdc stringify). + // - `:`-prefixed path bindings (`:to="$doc.link"`) stay prefixed so they + // round-trip as bindings, not plain strings. + // - Bare string literals `'true'`/`'false'` from inline attrs coerce to bools. + const normalized = Object.fromEntries( + Object.entries(attributes).map(([key, value]) => { + if (key.startsWith(':')) { + if (typeof value === 'string') { + try { + // JSON number/boolean/null/object/array -> typed YAML key without `:` + return [key.slice(1), JSON.parse(value)] + } catch { + // Path binding / non-JSON string: keep the `:` key + return [key, value] + } + } + // Already-decoded object/array (processAttributes) or native value + return [key.slice(1), value] + } + return [key, normalizeValue(value)] + }) + ) + + const yamlContent = stringifyYaml(normalized).trim() + + if (style === 'frontmatter') { + return `---\n${yamlContent}\n---` + } + + const fence = pickFence(yamlContent) + return `${fence}yaml [props]\n${yamlContent}\n${fence}` +} diff --git a/packages/comark/src/render/index.ts b/packages/comark/src/render/index.ts index 0ab015db1..23f76da92 100644 --- a/packages/comark/src/render/index.ts +++ b/packages/comark/src/render/index.ts @@ -2,7 +2,8 @@ import type { MarkdownDocument, RendererOptions, RenderMarkdownOptions } from 'c import { renderFrontmatter } from '../internal/frontmatter.ts' import { createState, one } from '../internal/stringify/state.ts' -import { handlers } from '../internal/stringify/handlers/index.ts' +import { handlers as markdownHandlers } from '../internal/stringify/handlers/index.ts' +import { mdc } from '../internal/stringify/handlers/mdc.ts' export type { NodeHandler, @@ -19,6 +20,8 @@ export type { export { renderFrontmatter } from '../internal/frontmatter.ts' +const handlers = { ...markdownHandlers, mdc } + // Re-export attribute resolvers for custom handlers that want to honor `:prefix` bindings export { resolveAttributes, resolveAttribute } from '../internal/stringify/attributes.ts' diff --git a/packages/comark/src/render/markdown.ts b/packages/comark/src/render/markdown.ts new file mode 100644 index 000000000..8389faf3b --- /dev/null +++ b/packages/comark/src/render/markdown.ts @@ -0,0 +1,40 @@ +import type { HeadingIdsOption, MarkdownDocument, RendererOptions } from '../types.ts' +import { createState, one } from '../internal/stringify/state.ts' +import { handlers } from '../internal/stringify/handlers/index.ts' + +export interface MarkdownRendererOptions extends RendererOptions { + /** The `headingIds` mode the document was parsed with. See `renderMarkdown` in `comark/render`. */ + headingIds?: HeadingIdsOption + /** Always `markdown/html`. Use `render` from `comark/render` for other formats. */ + format?: never +} + +/** + * Render a document's nodes to CommonMark and GFM without loading YAML support. + * Nodes with no Markdown syntax, such as components, are written as HTML, and + * frontmatter is left out. Otherwise the output matches `renderMarkdown` from + * `comark/render`, which keeps component syntax and frontmatter. + * + * @example + * ```typescript + * import { parseMarkdown } from 'comark' + * import { renderMarkdown } from 'comark/render/markdown' + * + * const document = await parseMarkdown('# Hello **World**') + * const markdown = await renderMarkdown(document) + * ``` + */ +export async function renderMarkdown( + document: MarkdownDocument | { nodes: MarkdownDocument['nodes'] }, + options: MarkdownRendererOptions = {} +): Promise { + const state = createState(handlers, { + ...options, + format: 'markdown/html', + tree: document as MarkdownDocument, + handlers: options.components, + }) + let result = '' + for (const node of document.nodes) result += await one(node, state) + return result.trim() +} diff --git a/packages/comark/test/render-markdown.test.ts b/packages/comark/test/render-markdown.test.ts new file mode 100644 index 000000000..5b55acbe4 --- /dev/null +++ b/packages/comark/test/render-markdown.test.ts @@ -0,0 +1,97 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { gzipSync } from 'node:zlib' +import { describe, expect, it } from 'vitest' +import { build } from 'vite' +import type { NodeHandler } from 'comark' +import { parseMarkdown } from '../src/index' +import { renderMarkdown as renderComarkMarkdown } from '../src/render/index' +import { renderMarkdown } from '../src/render/markdown' + +const markdown = [ + '# Title\n\nSome *emphasis*, **strong**, ~~deleted~~ and `code`.', + '- one\n- two\n - nested\n\n3. three\n4. four', + '> quote\n>\n> - item', + '> [!NOTE]\n> An alert', + '```ts\nconst a = 1\n```\n\n indented', + '| a | b |\n| :- | -: |\n| 1 | `2` |', + '[link](https://example.com "title"), and ![alt](/img.png)', + '- [ ] todo\n- [x] done', + 'line \nbreak\n\n---\n\nafter', + '\\*not emphasis\\*, 1\\. not a list and snake_case', + '## Heading {#custom}\n\nText with inline html', +] + +describe('comark/render/markdown', () => { + it.each(markdown)('writes CommonMark and GFM as comark/render does: %j', async (source) => { + const document = await parseMarkdown(source) + expect(await renderMarkdown(document)).toBe(await renderComarkMarkdown(document)) + }) + + it('writes components as HTML and leaves frontmatter out', async () => { + const document = await parseMarkdown('---\ntitle: Hi\n---\n\n::alert{type="info"}\nCareful :badge[new]\n::') + const html = await renderComarkMarkdown({ nodes: document.nodes }, { format: 'markdown/html' }) + expect(await renderMarkdown(document)).toBe(html) + expect(html).toBe('\n\nCareful new\n\n') + }) + + it('writes a break that has no trailing-space form as
', async () => { + expect(await renderMarkdown({ nodes: [['p', {}, 'a ', ['br', {}], 'b']] })).toBe('a
b') + }) + + it('renders with custom components', async () => { + const strong: NodeHandler = async (node, state) => `*${await state.flow(node, state)}*` + const document = await parseMarkdown('Hello **world**') + expect(await renderMarkdown(document, { components: { strong } })).toBe('Hello *world*') + }) +}) + +it('bundles without YAML or the component serializer', async () => { + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + lib: { entry: fileURLToPath(new URL('../src/render/markdown.ts', import.meta.url)), formats: ['es'] }, + minify: true, + write: false, + }, + }) + const bundles = Array.isArray(result) ? result : [result] + const chunks = bundles.flatMap((bundle) => + 'output' in bundle ? bundle.output.filter((output) => output.type === 'chunk') : [] + ) + expect(chunks).toHaveLength(1) + const chunk = chunks[0]! + expect(gzipSync(chunk.code).length).toBeLessThan(12 * 1024) + const retained = Object.entries(chunk.modules) + .filter(([, module]) => module.renderedLength > 0) + .map(([id]) => id) + expect(retained.filter((id) => /js-yaml|\/yaml\.ts|frontmatter|handlers\/mdc\./.test(id))).toEqual([]) + const { renderMarkdown } = await import(`data:text/javascript;base64,${Buffer.from(chunk.code).toString('base64')}`) + expect(await renderMarkdown({ nodes: [['p', {}, 'Hello ', ['strong', {}, 'world']]] })).toBe('Hello **world**') +}) + +it('imports comark/render/markdown without loading YAML or the component serializer in Node', () => { + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { registerHooks } from 'node:module' + import assert from 'node:assert/strict' + registerHooks({ + load(url, context, next) { + if (/js-yaml|\\/yaml\\.(js|ts)$|frontmatter|handlers\\/mdc\\./.test(url)) { + throw new Error('Unexpected renderer dependency: ' + url) + } + return next(url, context) + } + }) + const { renderMarkdown } = await import('comark/render/markdown') + assert.equal(await renderMarkdown({ nodes: [['p', {}, 'Hello']] }), 'Hello') + `, + ], + { cwd: process.cwd(), encoding: 'utf8' } + ) +}) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 557655dc4..6105547fd 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -77,7 +77,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "43.3k (87 files)", "@comark/svelte": "51.0k (95 files)", "@comark/vue": "62.7k (93 files)", - "comark": "451k (175 files)", + "comark": "452k (177 files)", } `) })