From f184dc816cc2f056f1bd35004a42f465e30e91f1 Mon Sep 17 00:00:00 2001 From: fulequn Date: Thu, 22 Oct 2026 12:39:22 +0800 Subject: [PATCH 1/6] =?UTF-8?q?:arrow=5Fup:=20=E5=8D=87=E7=BA=A7=20mermaid?= =?UTF-8?q?=20=E8=87=B3=2011.16.0=20=E5=B9=B6=E9=80=82=E9=85=8D=20run=20?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mermaid 10 起移除了 mermaid.init(),原调用在新版本下会直接报错。 改为 mermaid.run(),并捕获渲染异常,避免单个图表语法错误中断整页。 默认 CDN 同步升级到 11.16.0,配置项说明指向新版 schema 文档。 Co-Authored-By: Claude Code --- _config.yml | 5 +++-- layout/_partials/plugins/mermaid.ejs | 20 ++++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/_config.yml b/_config.yml index 815b498bc..c9c5529de 100644 --- a/_config.yml +++ b/_config.yml @@ -762,7 +762,8 @@ post: # If true, only set `mermaid: true` in Front-matter will enable mermaid, to load faster when the page does not contain mermaid specific: false - # See: http://mermaid-js.github.io/mermaid/ + # 配置项与 mermaid 版本保持一致,可参考:https://mermaid.js.org/config/schema-docs/config.html + # Options follow the mermaid version schema, see: https://mermaid.js.org/config/schema-docs/config.html options: { theme: 'default' } # 评论插件 @@ -1136,7 +1137,7 @@ static_prefix: clipboard: https://lib.baomitu.com/clipboard.js/2.0.11/ - mermaid: https://lib.baomitu.com/mermaid/8.14.0/ + mermaid: https://cdn.jsdelivr.net/npm/mermaid@11.16.0/dist/ valine: https://lib.baomitu.com/valine/1.5.1/ diff --git a/layout/_partials/plugins/mermaid.ejs b/layout/_partials/plugins/mermaid.ejs index ffd2860e7..c8cdcc66d 100644 --- a/layout/_partials/plugins/mermaid.ejs +++ b/layout/_partials/plugins/mermaid.ejs @@ -2,12 +2,20 @@ Fluid.utils.createScript('<%= url_join(theme.static_prefix.mermaid, 'mermaid.min.js') %>', function() { mermaid.initialize(<%- JSON.stringify(theme.post.mermaid.options || {}) %>); - Fluid.utils.listenDOMLoaded(function() { - Fluid.events.registerRefreshCallback(function() { - if ('mermaid' in window) { - mermaid.init(); - } + var renderMermaid = function() { + if (!('mermaid' in window)) { + return; + } + // mermaid 10+ 移除了 mermaid.init(),改用 mermaid.run() + // mermaid 10+ removed mermaid.init(), use mermaid.run() instead + mermaid.run().catch(function(err) { + // 单个图表语法错误不应中断整页渲染 + // A syntax error in one diagram should not break the whole page + console.error('[Fluid] Mermaid render failed:', err); }); - }); + }; + + Fluid.utils.listenDOMLoaded(renderMermaid); + Fluid.events.registerRefreshCallback(renderMermaid); }); From eb11e4b318c4a10908c3c60ec44342d00df304bf Mon Sep 17 00:00:00 2001 From: fulequn Date: Thu, 22 Oct 2026 14:05:54 +0800 Subject: [PATCH 2/6] =?UTF-8?q?:bug:=20=E4=BF=AE=E5=A4=8D=20mermaid=20?= =?UTF-8?q?=E7=89=B9=E5=AE=9A=E6=A8=A1=E5=BC=8F=E6=BC=8F=E5=8A=A0=E8=BD=BD?= =?UTF-8?q?=E5=B9=B6=E6=98=BE=E5=BC=8F=E6=8E=A7=E5=88=B6=E6=B8=B2=E6=9F=93?= =?UTF-8?q?=E6=97=B6=E6=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - specific 为 true 时自动检测页面内的 mermaid 块,避免忘记写 Front-matter 导致图表退化为纯文本 - 支持通过 `mermaid: false` 显式关闭 - 固定 startOnLoad 为 false,由 mermaid.run 统一渲染,避免自动渲染早于 initialize 生效 - 传入 options 会覆盖 run 的默认 querySelector,需显式指定,否则不会渲染任何图表 - 使用 suppressErrors,单个图表语法错误不再影响同页其他图表 - 构建期在图表存在但不会加载脚本时输出警告 Co-Authored-By: Claude Code --- _config.yml | 6 ++++-- layout/_partials/markdown-plugins.ejs | 13 ++++++++++++- layout/_partials/plugins/mermaid.ejs | 19 +++++++++++++------ scripts/events/index.js | 1 + scripts/events/lib/mermaid.js | 24 ++++++++++++++++++++++++ 5 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 scripts/events/lib/mermaid.js diff --git a/_config.yml b/_config.yml index c9c5529de..0eb8246c5 100644 --- a/_config.yml +++ b/_config.yml @@ -758,8 +758,10 @@ post: # If you want to use mermaid on the custom page, you need to set `mermaid: true` in Front-matter enable: false - # 开启后,只有在文章 Front-matter 里指定 `mermaid: true` 才会在文章页启动公式转换,以便在页面不包含公式时提高加载速度 - # If true, only set `mermaid: true` in Front-matter will enable mermaid, to load faster when the page does not contain mermaid + # 开启后,只有当页面包含 mermaid 图表或 Front-matter 指定 `mermaid: true` 时才加载脚本,以便在页面不包含图表时提高加载速度 + # 指定 `mermaid: false` 可强制关闭 + # If true, the script is only loaded when the page contains mermaid diagrams or `mermaid: true` is set in Front-matter, saving the load on pages without diagrams + # Set `mermaid: false` to opt out explicitly specific: false # 配置项与 mermaid 版本保持一致,可参考:https://mermaid.js.org/config/schema-docs/config.html diff --git a/layout/_partials/markdown-plugins.ejs b/layout/_partials/markdown-plugins.ejs index e7a8272bb..62b035a3a 100644 --- a/layout/_partials/markdown-plugins.ejs +++ b/layout/_partials/markdown-plugins.ejs @@ -19,6 +19,17 @@ <% if (theme.post.math.enable && (!theme.post.math.specific || (theme.post.math.specific && page.math))) { %> <%- partial('_partials/plugins/math.ejs') %> <% } %> -<% if (theme.post.mermaid.enable && (!theme.post.mermaid.specific || (theme.post.mermaid.specific && page.mermaid))) { %> +<% + // mermaid 块可能来自 ```mermaid 代码块,也可能来自 {% mermaid %} 标签。 + // 检测到页面内确实存在图表时才加载脚本,特定模式下无需再手动写 Front-matter。 + // Detect mermaid blocks in the page content, so that `specific: true` does not + // silently skip the script when the Front-matter flag is missing. + // Mermaid blocks may come from a ```mermaid fence or the {% mermaid %} tag. + var hasMermaidBlock = /]*\bmermaid\b[^>]*>/i.test(page.content || ''); + var needMermaid = theme.post.mermaid.enable + && page.mermaid !== false + && (!theme.post.mermaid.specific || page.mermaid || hasMermaidBlock); +%> +<% if (needMermaid) { %> <%- partial('_partials/plugins/mermaid.ejs') %> <% } %> diff --git a/layout/_partials/plugins/mermaid.ejs b/layout/_partials/plugins/mermaid.ejs index c8cdcc66d..0b5345936 100644 --- a/layout/_partials/plugins/mermaid.ejs +++ b/layout/_partials/plugins/mermaid.ejs @@ -1,16 +1,23 @@ diff --git a/scripts/events/lib/highlight.js b/scripts/events/lib/highlight.js index 87d6c1500..4406298f0 100644 --- a/scripts/events/lib/highlight.js +++ b/scripts/events/lib/highlight.js @@ -14,6 +14,7 @@ try { const fs = require('fs'); const objUtil = require('../../utils/object'); const resolveModule = require('../../utils/resolve'); +const { hasMermaidCode, toMermaidClass } = require('../../utils/mermaid'); module.exports = (hexo) => { @@ -94,14 +95,14 @@ module.exports = (hexo) => { hexo.extend.filter.register('after_post_render', (page) => { if (hexo.config.highlight.line_number) { page.content = page.content.replace(/]+?highlight.+?]+?code[^>]+?>.*?().+?<\/figure>/gims, (str, p1) => { - if (/]+?mermaid[^>]+?>/ims.test(p1)) { + if (hasMermaidCode(p1)) { return p1.replace(/(class="[^>]*?)hljs([^>]*?")/gims, '$1$2').replace(/
/gims, '\n'); } return str; }); } else { page.content = page.content.replace(/(?)/gims, (str) => { - if (/]+?mermaid[^>]+?>/ims.test(str)) { + if (hasMermaidCode(str)) { return str.replace(/(class=".*?)hljs(.*?")/gims, '$1$2'); } return `
${str}
`; @@ -133,12 +134,11 @@ module.exports = (hexo) => { hexo.extend.filter.register('after_post_render', (page) => { page.content = page.content.replace(/(?)/gims, (str) => { - if (/]+?mermaid[^>]+?>/ims.test(str)) { + if (hasMermaidCode(str)) { if (hexo.config.highlight.line_number) { str = str.replace(/]+?line-numbers-rows[^>]+?>.+?<\/span><\/code>/, ''); } - str = str.replace(/]*?>/gims, '
')
-            .replace(/(class=".*?)language-mermaid(.*?")/gims, '$1mermaid$2')
+          str = toMermaidClass(str.replace(/]*?>/gims, '
'))
             .replace(/]+?>(.+?)<\/span>/gims, '$1');
           return str;
         }
diff --git a/scripts/events/lib/mermaid.js b/scripts/events/lib/mermaid.js
index a9d9425fd..8a6ff85c1 100644
--- a/scripts/events/lib/mermaid.js
+++ b/scripts/events/lib/mermaid.js
@@ -2,7 +2,7 @@
 
 'use strict';
 
-const MERMAID_BLOCK = /]*\bmermaid\b[^>]*>/i;
+const { hasMermaidElement } = require('../../utils/mermaid');
 
 module.exports = (hexo) => {
   // 构建期提示:页面里有 mermaid 块,但配置导致脚本不会被加载时给出警告,
@@ -11,7 +11,7 @@ module.exports = (hexo) => {
   // be loaded, so the diagrams would silently show up as plain text
   hexo.extend.filter.register('after_post_render', (page) => {
     const config = hexo.theme.config.post.mermaid;
-    if (!config || !MERMAID_BLOCK.test(page.content || '')) {
+    if (!config || !hasMermaidElement(page.content || '')) {
       return page;
     }
     if (!config.enable) {
diff --git a/scripts/helpers/mermaid.js b/scripts/helpers/mermaid.js
new file mode 100644
index 000000000..055dc5bdf
--- /dev/null
+++ b/scripts/helpers/mermaid.js
@@ -0,0 +1,9 @@
+/* global hexo */
+
+'use strict';
+
+const { hasMermaidElement } = require('../utils/mermaid');
+
+// EJS 模板里不能 require,检测逻辑通过 helper 暴露给 layout
+// EJS templates cannot require modules, so expose the detector as a helper
+hexo.extend.helper.register('has_mermaid', (content) => hasMermaidElement(content));
diff --git a/scripts/utils/mermaid.js b/scripts/utils/mermaid.js
new file mode 100644
index 000000000..f675e6f5e
--- /dev/null
+++ b/scripts/utils/mermaid.js
@@ -0,0 +1,107 @@
+'use strict';
+
+// 识别页面中真正会被 mermaid.run() 渲染的元素。
+// mermaid.run 默认按 `.mermaid` 选择器查找节点,所以这里必须基于真实的 class token,
+// 不能对整段 HTML 做宽松正则匹配:HTML 注释、', false, 'script body'],
+    ['', false, 'style body'],
+    ['<div class="mermaid">', false, 'escaped html'],
+    ['x', false, 'raw language- class is not rendered'],
+    ['
x
', false, 'not-mermaid class'], + ['
x
', false, 'prefixed class'], + ['just text', false, 'plain text'] + ]; + + for (const [html, expected, why] of elementCases) { + expectEqual(`hasMermaidElement(${why})`, hasMermaidElement(html), expected); } - const Hexo = require(path.join(SITE, 'node_modules', 'hexo')); - const hexo = new Hexo(SITE, { silent: true }); + // 代码块适配器需要识别 prism 转换前的 language-mermaid + // Adapters run before the class is rewritten, so accept language-mermaid there + expectEqual('hasMermaidCode(language-mermaid)', hasMermaidCode('x'), true); + expectEqual('hasMermaidCode(hljs mermaid)', hasMermaidCode('x'), true); + expectEqual('hasMermaidCode(not-mermaid)', hasMermaidCode('x'), false); + + const rewriteCases = [ + ['
x
', + '
x
', 'both wrapper and code'], + ['x', + 'x', 'other tokens preserved'], + ['x', + 'x', 'prefixed language untouched'], + ['x', + 'x', 'single quotes preserved'] + ]; + + for (const [html, expected, why] of rewriteCases) { + expectEqual(`toMermaidClass(${why})`, toMermaidClass(html), expected); + } +} + +function resolveModules() { + if (process.env.FLUID_TEST_MODULES) { + console.log(`[test] reusing node_modules from ${process.env.FLUID_TEST_MODULES}`); + return process.env.FLUID_TEST_MODULES; + } + const deps = path.join(WORK, 'deps'); + fs.mkdirSync(deps, { recursive: true }); + console.log('[test] installing dependencies...'); + // 固定版本:测试应该验证当前这套已知可用的组合,而不是随时漂移的 latest + // Pinned versions keep the test on the combination that was verified + const installed = spawnSync('npm', [ + 'install', '--no-save', '--no-audit', '--no-fund', '--loglevel=error', + 'hexo@8.1.2', 'hexo-renderer-ejs@2.0.0', 'hexo-renderer-marked@7.0.1', + 'hexo-renderer-stylus@3.0.1', 'hexo-pagination@3.0.0', 'nunjucks@3.2.4', + '@adobe/css-tools@4.3.3', 'hexo-prism-plugin@2.3.0' + ], { cwd: deps, stdio: 'inherit' }); + if (installed.status !== 0) { + fail('npm install failed'); + } + return path.join(deps, 'node_modules'); +} + +async function buildSite(name, fluidConfig, modules) { + const site = path.join(WORK, name); + copyDir(path.join(__dirname, 'fixture'), site); + copyDir(ROOT, path.join(site, 'themes', 'fluid')); + fs.writeFileSync(path.join(site, '_config.fluid.yml'), fluidConfig); + fs.symlinkSync(modules, path.join(site, 'node_modules'), 'dir'); + + const Hexo = require(path.join(site, 'node_modules', 'hexo')); + const hexo = new Hexo(site, { silent: true }); const warnings = []; await hexo.init(); hexo.log.warn = (...args) => warnings.push(args.join(' ')); @@ -72,46 +187,151 @@ async function main() { await hexo.call('generate'); await hexo.exit(); + return { + warnings, + html(page) { + const file = path.join(site, 'public', page, 'index.html'); + if (!fs.existsSync(file)) { + fail(`missing generated page ${page}/index.html in ${name}`); + } + return fs.readFileSync(file, 'utf8'); + } + }; +} + +function mermaidWarnings(warnings) { + return warnings.filter((line) => line.includes('[Fluid] Mermaid block found')); +} + +async function testEnabledBuild(modules) { + const site = await buildSite('enabled', ENABLED_CONFIG, modules); + const cases = [ { page: 'with-flag', loads: true, why: 'Front-matter mermaid: true' }, - { page: 'block-only', loads: true, why: 'mermaid block detected in content' }, - { page: 'tag-only', loads: true, why: '{% mermaid %} tag detected in content' }, + { page: 'block-only', loads: true, why: '```mermaid fence' }, + { page: 'tag-only', loads: true, why: '{% mermaid %} tag' }, + { page: 'div-mermaid', loads: true, why: '
in content' }, { page: 'plain', loads: false, why: 'no mermaid block' }, - { page: 'opt-out', loads: false, why: 'mermaid: false in Front-matter' }, + { page: 'not-mermaid', loads: false, why: '```not-mermaid fence is not a diagram' }, + { page: 'escaped-sample', loads: false, why: 'mermaid example escaped inside an html fence' }, + { page: 'raw-language', loads: false, why: 'raw language-mermaid class is not rendered by run()' }, + { page: 'opt-out', loads: false, why: 'mermaid: false in Front-matter' } ]; for (const item of cases) { - const html = load(item.page); - const loads = html.includes('mermaid.min.js'); - if (loads !== item.loads) { - fail(`${item.page}: expected mermaid.min.js ${item.loads ? 'present' : 'absent'} (${item.why})`); - } + const html = site.html(item.page); + expectEqual(`${item.page}: mermaid.min.js`, html.includes('mermaid.min.js'), item.loads); } - const withFlag = load('with-flag'); - if (!/startOnLoad:\s*false/.test(withFlag)) { - fail('with-flag: startOnLoad is not forced to false'); - } - if (/mermaid\.init\s*\(/.test(withFlag)) { - fail('with-flag: legacy mermaid.init() call is still present'); - } - if (!/suppressErrors:\s*true/.test(withFlag)) { - fail('with-flag: mermaid.run() is not called with suppressErrors'); - } - if (!/querySelector:\s*['"]\.mermaid['"]/.test(withFlag)) { - fail('with-flag: mermaid.run() does not set querySelector explicitly'); - } - if (!/class="[^"]*\bmermaid\b[^"]*"/.test(withFlag)) { - fail('with-flag: mermaid code block was not preserved'); - } + const withFlag = site.html('with-flag'); + expectMatch('with-flag: startOnLoad forced off', withFlag, /Object\.assign\(\{\}, \{[^}]*\}, \{ startOnLoad: false \}\)/); + expectMatch('with-flag: theme options passed through', withFlag, /"theme":"forest"/); + expectNoMatch('with-flag: no legacy init()', withFlag, /mermaid\.init\s*\(/); + expectMatch('with-flag: querySelector explicit', withFlag, /querySelector:\s*['"]\.mermaid['"]/); + // suppressErrors 会吞掉 run() 的 reject,让失败无法观测 + // suppressErrors swallows run()'s rejection, hiding failures + expectMatch('with-flag: run() only passes querySelector', withFlag, /mermaid\.run\(\{\s*querySelector:\s*['"]\.mermaid['"]\s*\}\)/); + expectMatch('with-flag: load failures are reported', withFlag, /Failed to load mermaid/); - if (!warnings.some((line) => /opt-out/.test(line) && /mermaid: false/.test(line))) { - fail(`expected a build warning for opt-out, got:\n${warnings.join('\n')}`); - } - if (warnings.some((line) => /plain/.test(line))) { - fail(`unexpected warning for plain page:\n${warnings.join('\n')}`); + // 代码块类名与高亮不能被误伤 + // Code blocks must keep their classes and highlighting + expectMatch('with-flag: mermaid code block preserved', withFlag, /class="[^"]*\bmermaid\b[^"]*"/); + const notMermaid = site.html('not-mermaid'); + expectMatch('not-mermaid: language class preserved', notMermaid, /class="[^"]*not-mermaid[^"]*"/); + expectMatch('not-mermaid: hljs class preserved', notMermaid, /class="hljs not-mermaid"/); + expectNoMatch('not-mermaid: no mermaid class rewrite', notMermaid, /class="mermaid"/); + + // 正文里的 div.mermaid 不能被代码块适配器包成 code-wrapper + // A raw div.mermaid must not be wrapped like a code block + const divMermaid = site.html('div-mermaid'); + expectMatch('div-mermaid: block preserved', divMermaid, /
/); + expectNoMatch('div-mermaid: not wrapped as code', divMermaid, /
/); + + // 代码围栏里的示例必须保持为高亮文本,不能变成真实图表节点 + // An escaped example must stay highlighted text, not become a diagram node + const escaped = site.html('escaped-sample'); + expectNoMatch('escaped-sample: no real mermaid element', escaped, /
/); + expectMatch('escaped-sample: kept as highlighted html', escaped, /class="hljs-tag"/); + + const found = mermaidWarnings(site.warnings); + expectEqual( + 'enabled: warnings only for the opted-out page', + found.map((line) => (line.includes('opt-out') ? 'opt-out' : line)).join(','), + 'opt-out' + ); +} + +async function testDisabledBuild(modules) { + const site = await buildSite('disabled', DISABLED_CONFIG, modules); + + for (const page of ['with-flag', 'block-only', 'tag-only', 'div-mermaid', 'opt-out', 'plain']) { + expectEqual(`disabled/${page}: mermaid.min.js`, site.html(page).includes('mermaid.min.js'), false); } + const found = mermaidWarnings(site.warnings); + const pagesWithWarning = found.map((line) => { + const match = line.match(/"([^"]+)"/); + return match ? match[1].split('/')[0] : line; + }).sort(); + expectEqual( + 'disabled: warns exactly for pages with renderable diagrams', + pagesWithWarning.join(','), + ['block-only', 'div-mermaid', 'opt-out', 'tag-only', 'with-flag'].join(',') + ); +} + +async function testHighlightLineNumberBuild(modules) { + const site = await buildSite('hljs-lineno', HLJS_LINENO_CONFIG, modules); + + const blockOnly = site.html('block-only'); + expectEqual('hljs+line_number/block-only: mermaid.min.js', blockOnly.includes('mermaid.min.js'), true); + expectMatch('hljs+line_number/block-only: figure unwrapped', blockOnly, /graph TD\n {2}A --> B\n<\/code>/); + expectNoMatch('hljs+line_number/block-only: figure removed', blockOnly, /
/); + expectMatch('hljs+line_number/not-mermaid: hljs class kept', notMermaid, /class="hljs not-mermaid"/); + expectMatch('hljs+line_number/not-mermaid: line numbers kept', notMermaid, /class="gutter"/); +} + +async function testPrismBuild(modules) { + const site = await buildSite('prism', PRISM_CONFIG, modules); + + const blockOnly = site.html('block-only'); + expectEqual('prism/block-only: mermaid.min.js', blockOnly.includes('mermaid.min.js'), true); + expectMatch('prism/block-only: language-mermaid rewritten', blockOnly, //); + expectNoMatch('prism/block-only: no leftover language class', blockOnly, /class="[^"]*language-mermaid[^"]*"/); + expectNoMatch('prism/block-only: line numbers removed', blockOnly, /line-numbers-rows/); + expectNoMatch('prism/block-only: pre attributes removed', blockOnly, /
/);
+
+  const divMermaid = site.html('div-mermaid');
+  expectEqual('prism/div-mermaid: mermaid.min.js', divMermaid.includes('mermaid.min.js'), true);
+
+  expectEqual('prism/plain: mermaid.min.js', site.html('plain').includes('mermaid.min.js'), false);
+}
+
+async function main() {
+  console.log(`[test] work dir: ${WORK}`);
+
+  testDetector();
+
+  const modules = resolveModules();
+  await testEnabledBuild(modules);
+  await testDisabledBuild(modules);
+  await testHighlightLineNumberBuild(modules);
+  await testPrismBuild(modules);
+
   console.log('[test] all mermaid assertions passed');
   fs.rmSync(WORK, { recursive: true, force: true });
 }

From 974480594ae4df402fac9a0ddc5b949e48b2c4f5 Mon Sep 17 00:00:00 2001
From: fulequn 
Date: Fri, 23 Oct 2026 11:59:13 +0800
Subject: [PATCH 5/6] =?UTF-8?q?:bug:=20=E6=96=87=E7=AB=A0=E6=91=98?=
 =?UTF-8?q?=E8=A6=81=E4=B8=8D=E5=86=8D=E8=BE=93=E5=87=BA=20mermaid=20?=
 =?UTF-8?q?=E6=BA=90=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

首页自动摘要直接复用 post.content,代码围栏里的 mermaid 图表会以
"graph TD ..." 的形式出现在文章列表和本地搜索里。

新增 strip_mermaid helper:先按 class token 整体移除 mermaid 节点
(pre/code/div,兼容 language-mermaid),再交给 strip_html 取纯文本。
只匹配独立的 mermaid token,mermaid-wrapper 之类的名字不受影响。

Co-Authored-By: Claude Code 
---
 layout/index.ejs         |  2 +-
 scripts/helpers/utils.js | 12 ++++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/layout/index.ejs b/layout/index.ejs
index a370e9c97..230bb430a 100644
--- a/layout/index.ejs
+++ b/layout/index.ejs
@@ -31,7 +31,7 @@ page.banner_mask_alpha = theme.index.banner_mask_alpha
       <% var excerpt = post.description || post.excerpt || (theme.index.auto_excerpt.enable && !post.encrypt && post.content) %>
       
         
- <%- strip_html(excerpt).substring(0, 200).trim().replace(/\n/g, ' ') %> + <%- strip_html(strip_mermaid(excerpt)).substring(0, 200).trim().replace(/\n/g, ' ') %>
diff --git a/scripts/helpers/utils.js b/scripts/helpers/utils.js index 7581d62e8..8c381dc11 100644 --- a/scripts/helpers/utils.js +++ b/scripts/helpers/utils.js @@ -27,3 +27,15 @@ hexo.extend.helper.register('deduplicate', function(arr) { }); hexo.extend.helper.register('decode_url', decodeURL); + +// 移除正文里的 mermaid 源码,避免图表代码进入摘要和 meta description +// Strip mermaid source so diagram code never leaks into excerpts or meta descriptions +// 只匹配独立的 mermaid 类名,避免误伤 mermaid-wrapper 之类的复合类名;单双引号都支持 +// Match only the exact `mermaid` class token, so names like mermaid-wrapper survive +const MERMAID_BLOCK = /<(pre|div|code)\b[^>]*\bclass=(["'])(?:[^"']*\s)?(?:language-)?mermaid(?:\s[^"']*)?\2[^>]*>[\s\S]*?<\/\1>/gi; + +hexo.extend.helper.register('strip_mermaid', function(html) { + // 第二步清掉只剩空壳的
,fenced 代码块被剥离后会留下它
+  // Second pass removes the empty 
 left behind by a fenced block
+  return String(html || '').replace(MERMAID_BLOCK, ' ').replace(/]*>\s*<\/pre>/gi, ' ');
+});

From f83734fd49b3545621fc678d5d411fdf475182ed Mon Sep 17 00:00:00 2001
From: fulequn 
Date: Fri, 23 Oct 2026 11:59:53 +0800
Subject: [PATCH 6/6] =?UTF-8?q?:mag:=20=E5=AE=8C=E5=96=84=E6=96=87?=
 =?UTF-8?q?=E7=AB=A0=E5=85=83=E4=BF=A1=E6=81=AF=EF=BC=9A=E6=91=98=E8=A6=81?=
 =?UTF-8?q?=E6=B8=85=E6=B4=97=E3=80=81og:image=20=E5=9B=9E=E9=80=80?=
 =?UTF-8?q?=E4=B8=8E=20JSON-LD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

- description 先移除 mermaid 与代码块、解码 HTML 实体,再交给 open_graph,
  避免图表源码和 "&" 这类转义原样进入 meta description
- og:image 增加正文首张绝对地址图片,优先级为
  og_img > index_img > 正文首图 > 站点默认图
- 新增 json_ld helper:文章输出 BlogPosting、首页输出 WebSite,
  并转义 "<" 防止正文提前闭合 script 标签

Co-Authored-By: Claude Code 
---
 layout/_partials/head.ejs | 51 ++++++++++++++++++++++++++++++++++++---
 scripts/helpers/utils.js  | 26 +++++++++++++++++++-
 2 files changed, 72 insertions(+), 5 deletions(-)

diff --git a/layout/_partials/head.ejs b/layout/_partials/head.ejs
index 648e06493..75292e00c 100644
--- a/layout/_partials/head.ejs
+++ b/layout/_partials/head.ejs
@@ -5,12 +5,20 @@ var keywords = page.keywords || config.keywords
 if (keywords instanceof Array) {
   keywords = keywords.join(',')
 }
-var description = page.description || page.excerpt || (is_post() && page.content) || config.description
+var description = page.description || page.excerpt || page.content || config.description
 if (description) {
-  description = strip_html(description).substring(0, 200).trim().replace(/\n/g, ' ')
+  // 先剥标签再去实体,避免 "&" 这类转义原样进入 meta 和 JSON-LD
+  // Strip tags first, then decode entities so escaped text stays readable in metadata
+  // 代码块内容不参与摘要,避免 meta 里出现整段源码
+  // Code blocks never belong in a summary
+  description = unescape_html(strip_html(strip_mermaid(description).replace(//gi, ' '))).substring(0, 200).trim().replace(/\n/g, ' ')
 }
-var ogImage = page.og_img || page.index_img
-var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_graph)
+// 正文首图优先于站点默认图,避免分享卡片千篇一律;只取绝对地址,
+// 相对路径可能指向未提交的图片,分享卡片会从默认图退化成 404
+// Only absolute content images: a broken relative path would replace the default card with a 404
+var contentImage = ((page.content || '').match(/]*\ssrc=["']((?:https?:)?\/\/[^"']+)["']/i) || [])[1]
+var ogImage = page.og_img || page.index_img || contentImage || theme.open_graph.image
+var ogConfig = Object.assign({ description: description }, theme.open_graph, { image: ogImage && url_for(ogImage) })
 %>
 
 
@@ -35,6 +43,41 @@ var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_
   <% } else { %>
     
   <% } %>
+  <%
+    // 结构化数据:文章输出 BlogPosting,首页输出 WebSite
+    // Structured data: BlogPosting for posts, WebSite for the home page
+    var jsonLd = null
+    var pageUrl = url_join(config.url, (page.canonical_path || page.path || '').replace('index.html', ''))
+    if (is_post()) {
+      jsonLd = {
+        '@context': 'https://schema.org',
+        '@type': 'BlogPosting',
+        headline: page.title,
+        description: description,
+        url: pageUrl,
+        mainEntityOfPage: { '@type': 'WebPage', '@id': pageUrl },
+        author: { '@type': 'Person', name: page.author || config.author },
+        publisher: { '@type': 'Organization', name: config.title },
+        inLanguage: config.language
+      }
+      if (page.date) jsonLd.datePublished = page.date.toISOString()
+      if (page.updated || page.date) jsonLd.dateModified = (page.updated || page.date).toISOString()
+      if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image)
+    } else if (is_home() && page.current === 1) {
+      jsonLd = {
+        '@context': 'https://schema.org',
+        '@type': 'WebSite',
+        name: config.title,
+        url: config.url,
+        description: description,
+        inLanguage: config.language
+      }
+      if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image)
+    }
+  %>
+  <% if (jsonLd) { %>
+    <%- json_ld(jsonLd) %>
+  <% } %>
   <% if ((theme.post.meta.views.enable && theme.post.meta.views.source === 'busuanzi')
     || (theme.footer.statistics.enable && theme.footer.statistics.source === 'busuanzi')) { %>
     
diff --git a/scripts/helpers/utils.js b/scripts/helpers/utils.js
index 8c381dc11..ba7327f49 100644
--- a/scripts/helpers/utils.js
+++ b/scripts/helpers/utils.js
@@ -3,7 +3,7 @@
 'use strict';
 
 const md5 = require('../utils/crypto');
-const { decodeURL } = require('hexo-util');
+const { decodeURL, unescapeHTML } = require('hexo-util');
 const compareVersions = require('../../scripts/utils/compare-versions');
 
 hexo.extend.helper.register('md5', function(string) {
@@ -39,3 +39,27 @@ hexo.extend.helper.register('strip_mermaid', function(html) {
   // Second pass removes the empty 
 left behind by a fenced block
   return String(html || '').replace(MERMAID_BLOCK, ' ').replace(/]*>\s*<\/pre>/gi, ' ');
 });
+
+// 解码 HTML 实体,避免 "&" 原样出现在 meta description 和 JSON-LD 里
+// Decode HTML entities so escaped text does not leak into meta tags and JSON-LD
+hexo.extend.helper.register('unescape_html', function(value) {
+  // hexo-util 只覆盖少量实体,这里补上十进制数字实体(如 {)
+  // hexo-util covers only a few entities; decode decimal numerics as well
+  return unescapeHTML(String(value == null ? '' : value)).replace(/&#(\d+);/g, function(match, code) {
+    const n = Number(code);
+    if (!(n > 0 && n <= 0x10ffff) || (n >= 0xd800 && n <= 0xdfff)) {
+      return match;
+    }
+    return String.fromCodePoint(n);
+  });
+});
+
+// 输出 JSON-LD,转义 < 防止正文里的  提前闭合标签
+// Emit JSON-LD with < escaped so content cannot close the script tag early
+hexo.extend.helper.register('json_ld', function(data) {
+  if (!data) {
+    return '';
+  }
+  const json = JSON.stringify(data).replace(/${json}`;
+});