From 6de2f96ceb7adcc5534e5032eb15003c5fd7a12b Mon Sep 17 00:00:00 2001 From: Alois Klink Date: Sat, 1 Jun 2024 18:46:40 +0900 Subject: [PATCH] perf: skip launching puppeteer when not needed Skip launching puppeteer until it's actually needed. Running mermaid-cli on a markdown file without any mermaid code blocks shouldn't launch puppeteer, if it's unnecessary. Fix: https://github.com/mermaid-js/mermaid-cli/issues/694 --- src/index.js | 12 ++++++++++-- test-positive/mermaidless-markdown-file.md | 3 +++ 2 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 test-positive/mermaidless-markdown-file.md diff --git a/src/index.js b/src/index.js index d26d906e..534ac822 100644 --- a/src/index.js +++ b/src/index.js @@ -413,7 +413,11 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output // TODO: should we use a Markdown parser like remark instead of rolling our own parser? const mermaidChartsInMarkdown = /^[^\S\n]*[`:]{3}(?:mermaid)([^\S\n]*\r?\n([\s\S]*?))[`:]{3}[^\S\n]*$/ const mermaidChartsInMarkdownRegexGlobal = new RegExp(mermaidChartsInMarkdown, 'gm') - const browser = await puppeteer.launch(puppeteerConfig) + /** + * @type {puppeteer.Browser | undefined} + * Lazy-loaded browser instance, only created when needed. + */ + let browser try { if (!outputFormat) { const outputFormatFromFilename = @@ -435,6 +439,9 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output if (input && /\.(md|markdown)$/.test(input)) { const imagePromises = [] for (const mermaidCodeblockMatch of definition.matchAll(mermaidChartsInMarkdownRegexGlobal)) { + if (browser === undefined) { + browser = await puppeteer.launch(puppeteerConfig) + } const mermaidDefinition = mermaidCodeblockMatch[2] /** Output can be either a template image file, or a `.md` output file. @@ -488,11 +495,12 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output } } else { info('Generating single mermaid chart') + browser = await puppeteer.launch(puppeteerConfig) const data = await parseMMD(browser, definition, outputFormat, parseMMDOptions) await fs.promises.writeFile(output, data) } } finally { - await browser.close() + await browser?.close?.() } } diff --git a/test-positive/mermaidless-markdown-file.md b/test-positive/mermaidless-markdown-file.md new file mode 100644 index 00000000..02cbd1d5 --- /dev/null +++ b/test-positive/mermaidless-markdown-file.md @@ -0,0 +1,3 @@ +# This markdown file has no mermaid code blocks in it + +This markdown file purposely has no mermaid code blocks in it.