Repository navigation
perf(render): add comark/render/markdown, which renders Markdown without YAML
#601
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
onmax
wants to merge
1
commit into
comarkdown:main
Choose a base branch
from
onmax:perf/auto-close-slim
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<string> { | ||
| 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() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"), <https://example.com> and ', | ||
| '- [ ] todo\n- [x] done', | ||
| 'line \nbreak\n\n---\n\nafter', | ||
| '\\*not emphasis\\*, 1\\. not a list and snake_case', | ||
| '## Heading {#custom}\n\nText with <b>inline html</b>', | ||
| ] | ||
|
|
||
| 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('<alert type="info">\n\nCareful <badge>new</badge>\n\n</alert>') | ||
| }) | ||
|
|
||
| it('writes a break that has no trailing-space form as <br>', async () => { | ||
| expect(await renderMarkdown({ nodes: [['p', {}, 'a ', ['br', {}], 'b']] })).toBe('a <br>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' } | ||
| ) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Attributed
ul,pre, andtableblocks emit component wrappers inrenderMarkdownoutput.renderMarkdownuses the shared handler map withformat: 'markdown/html'. Theulhandler ignores the format. When aulnode has user attributes, it writes::ul{...}wrapper syntax. For['ul', { id: 'items' }, ...], the first output line is::ul{#items}. A CommonMark consumer shows this line as plain text. Thepreandtablehandlers have the same path (::pre{...},::table{...}).The
renderMarkdownJSDoc says nodes without Markdown syntax are written as HTML. Attributes on these blocks have no Markdown syntax, so attributedul,pre, andtablenodes must be written as HTML elements. Blocks without user attributes keep their Markdown output.