-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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
Improve markdown rendering performance #8532
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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,5 @@ | ||
--- | ||
'astro': patch | ||
--- | ||
|
||
Improve markdown rendering performance by sharing processor instance |
This file contains 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,5 @@ | ||
--- | ||
'@astrojs/markdown-remark': minor | ||
--- | ||
|
||
Export `createMarkdownProcessor` and deprecate `renderMarkdown` API |
This file contains 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 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 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 |
---|---|---|
@@ -1,11 +1,16 @@ | ||
import type { | ||
AstroMarkdownOptions, | ||
MarkdownProcessor, | ||
MarkdownRenderingOptions, | ||
MarkdownRenderingResult, | ||
MarkdownVFile, | ||
} from './types.js'; | ||
|
||
import { toRemarkInitializeAstroData } from './frontmatter-injection.js'; | ||
import { | ||
InvalidAstroDataError, | ||
safelyGetAstroData, | ||
setAstroData, | ||
} from './frontmatter-injection.js'; | ||
import { loadPlugins } from './load-plugins.js'; | ||
import { rehypeHeadingIds } from './rehype-collect-headings.js'; | ||
import { remarkCollectImages } from './remark-collect-images.js'; | ||
|
@@ -15,13 +20,14 @@ import { remarkShiki } from './remark-shiki.js'; | |
import rehypeRaw from 'rehype-raw'; | ||
import rehypeStringify from 'rehype-stringify'; | ||
import remarkGfm from 'remark-gfm'; | ||
import markdown from 'remark-parse'; | ||
import markdownToHtml from 'remark-rehype'; | ||
import remarkParse from 'remark-parse'; | ||
import remarkRehype from 'remark-rehype'; | ||
import remarkSmartypants from 'remark-smartypants'; | ||
import { unified } from 'unified'; | ||
import { VFile } from 'vfile'; | ||
import { rehypeImages } from './rehype-images.js'; | ||
|
||
export { InvalidAstroDataError } from './frontmatter-injection.js'; | ||
export { rehypeHeadingIds } from './rehype-collect-headings.js'; | ||
export { remarkCollectImages } from './remark-collect-images.js'; | ||
export { remarkPrism } from './remark-prism.js'; | ||
|
@@ -45,30 +51,29 @@ export const markdownConfigDefaults: Omit<Required<AstroMarkdownOptions>, 'draft | |
// Skip nonessential plugins during performance benchmark runs | ||
const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK); | ||
|
||
/** Shared utility for rendering markdown */ | ||
export async function renderMarkdown( | ||
content: string, | ||
opts: MarkdownRenderingOptions | ||
): Promise<MarkdownRenderingResult> { | ||
let { | ||
fileURL, | ||
/** | ||
* Create a markdown preprocessor to render multiple markdown files | ||
*/ | ||
export async function createMarkdownProcessor( | ||
opts?: AstroMarkdownOptions | ||
): Promise<MarkdownProcessor> { | ||
const { | ||
syntaxHighlight = markdownConfigDefaults.syntaxHighlight, | ||
shikiConfig = markdownConfigDefaults.shikiConfig, | ||
remarkPlugins = markdownConfigDefaults.remarkPlugins, | ||
rehypePlugins = markdownConfigDefaults.rehypePlugins, | ||
remarkRehype = markdownConfigDefaults.remarkRehype, | ||
remarkRehype: remarkRehypeOptions = markdownConfigDefaults.remarkRehype, | ||
gfm = markdownConfigDefaults.gfm, | ||
smartypants = markdownConfigDefaults.smartypants, | ||
frontmatter: userFrontmatter = {}, | ||
} = opts; | ||
const input = new VFile({ value: content, path: fileURL }); | ||
} = opts ?? {}; | ||
|
||
const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins)); | ||
const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins)); | ||
|
||
let parser = unified() | ||
.use(markdown) | ||
.use(toRemarkInitializeAstroData({ userFrontmatter })) | ||
.use([]); | ||
const parser = unified().use(remarkParse); | ||
|
||
if (!isPerformanceBenchmark && gfm) { | ||
// gfm and smartypants | ||
if (!isPerformanceBenchmark) { | ||
if (gfm) { | ||
parser.use(remarkGfm); | ||
} | ||
|
@@ -77,14 +82,13 @@ export async function renderMarkdown( | |
} | ||
} | ||
|
||
const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins)); | ||
const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins)); | ||
|
||
loadedRemarkPlugins.forEach(([plugin, pluginOpts]) => { | ||
parser.use([[plugin, pluginOpts]]); | ||
}); | ||
// User remark plugins | ||
for (const [plugin, pluginOpts] of loadedRemarkPlugins) { | ||
parser.use(plugin, pluginOpts); | ||
} | ||
|
||
if (!isPerformanceBenchmark) { | ||
// Syntax highlighting | ||
if (syntaxHighlight === 'shiki') { | ||
parser.use(remarkShiki, shikiConfig); | ||
} else if (syntaxHighlight === 'prism') { | ||
|
@@ -95,45 +99,88 @@ export async function renderMarkdown( | |
parser.use(remarkCollectImages); | ||
} | ||
|
||
parser.use([ | ||
[ | ||
markdownToHtml as any, | ||
{ | ||
allowDangerousHtml: true, | ||
passThrough: [], | ||
...remarkRehype, | ||
}, | ||
], | ||
]); | ||
|
||
loadedRehypePlugins.forEach(([plugin, pluginOpts]) => { | ||
parser.use([[plugin, pluginOpts]]); | ||
// Remark -> Rehype | ||
parser.use(remarkRehype as any, { | ||
allowDangerousHtml: true, | ||
passThrough: [], | ||
...remarkRehypeOptions, | ||
}); | ||
|
||
// User rehype plugins | ||
for (const [plugin, pluginOpts] of loadedRehypePlugins) { | ||
parser.use(plugin, pluginOpts); | ||
} | ||
|
||
// Images / Assets support | ||
parser.use(rehypeImages()); | ||
|
||
// Headings | ||
if (!isPerformanceBenchmark) { | ||
parser.use([rehypeHeadingIds]); | ||
parser.use(rehypeHeadingIds); | ||
} | ||
|
||
parser.use([rehypeRaw]).use(rehypeStringify, { allowDangerousHtml: true }); | ||
// Stringify to HTML | ||
parser.use(rehypeRaw).use(rehypeStringify, { allowDangerousHtml: true }); | ||
|
||
let vfile: MarkdownVFile; | ||
try { | ||
vfile = await parser.process(input); | ||
} catch (err) { | ||
// Ensure that the error message contains the input filename | ||
// to make it easier for the user to fix the issue | ||
err = prefixError(err, `Failed to parse Markdown file "${input.path}"`); | ||
// eslint-disable-next-line no-console | ||
console.error(err); | ||
throw err; | ||
} | ||
return { | ||
async render(content, renderOpts) { | ||
const vfile = new VFile({ value: content, path: renderOpts?.fileURL }); | ||
setAstroData(vfile.data, { frontmatter: renderOpts?.frontmatter ?? {} }); | ||
|
||
const result: MarkdownVFile = await parser.process(vfile).catch((err) => { | ||
// Ensure that the error message contains the input filename | ||
// to make it easier for the user to fix the issue | ||
err = prefixError(err, `Failed to parse Markdown file "${vfile.path}"`); | ||
// eslint-disable-next-line no-console | ||
console.error(err); | ||
throw err; | ||
}); | ||
|
||
const astroData = safelyGetAstroData(result.data); | ||
if (astroData instanceof InvalidAstroDataError) { | ||
throw astroData; | ||
} | ||
Comment on lines
+139
to
+142
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rendering markdown now handles and throws |
||
|
||
return { | ||
code: String(result.value), | ||
metadata: { | ||
headings: result.data.__astroHeadings ?? [], | ||
imagePaths: result.data.imagePaths ?? new Set(), | ||
frontmatter: astroData.frontmatter ?? {}, | ||
}, | ||
// Compat for `renderMarkdown` only. Do not use! | ||
__renderMarkdownCompat: { | ||
result, | ||
}, | ||
}; | ||
}, | ||
}; | ||
} | ||
|
||
/** | ||
* Shared utility for rendering markdown | ||
* | ||
* @deprecated Use `createMarkdownProcessor` instead for better performance | ||
*/ | ||
export async function renderMarkdown( | ||
content: string, | ||
opts: MarkdownRenderingOptions | ||
): Promise<MarkdownRenderingResult> { | ||
const processor = await createMarkdownProcessor(opts); | ||
|
||
const result = await processor.render(content, { | ||
fileURL: opts.fileURL, | ||
frontmatter: opts.frontmatter, | ||
}); | ||
|
||
const headings = vfile?.data.__astroHeadings || []; | ||
return { | ||
metadata: { headings, source: content, html: String(vfile.value) }, | ||
code: String(vfile.value), | ||
vfile, | ||
code: result.code, | ||
metadata: { | ||
headings: result.metadata.headings, | ||
source: content, | ||
html: result.code, | ||
}, | ||
vfile: (result as any).__renderMarkdownCompat.result, | ||
}; | ||
} | ||
|
||
|
This file contains 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 |
---|---|---|
@@ -1,5 +1,6 @@ | ||
export { | ||
InvalidAstroDataError, | ||
safelyGetAstroData, | ||
setAstroData, | ||
toRemarkInitializeAstroData, | ||
} from './frontmatter-injection.js'; |
This file contains 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 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.
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.
astroData
here is used forastroData.frontmatter
only. I movedfrontmatter
to return directly fromprocessor.render()
above instead.