Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: add Mermaid flowchart support with fallback and safe rendering
myhloli5cddf9698250
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex ee281d9c..3416daee 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -137,18 +137,32 @@ HTML 与 DOCX/Markdown 共用 `RenderMode` 和续段/续表 planner。DEFAULT相邻页面之间输出 `hr.mineru-page-break`。每个顶层 block wrapper 保留来源 page/type/index元数据。行内内容直接消费共享 AST:普通文本始终 HTML escape,未知标签保持可见;公式只在 `mineru-math` carrier 内使用 `\(...\)` 或 `\[...\]`,不扫描普通正文中的美元符号。+HTML 的普通 `InlineText` 默认 linkify `http/https`、`www.`、邮箱和常见裸域名;裸域名统一补+`https://`,邮箱补 `mailto:`。无协议裸域名的 TLD 必须属于工程常用白名单:+`com cn org net edu gov io ai dev app de uk nl ru br fr au in eu jp`、+`ca hk tw sg kr nz info biz xyz site online tech cloud shop store`。显式 HTTP(S)、`www.` 和邮箱+不受该小白名单限制。已有 hyperlink、代码、算法、公式、raw HTML 及 Mermaid 源码不重复+识别,候选 href 仍通过统一 URL sanitizer。完整文档只内联压缩后的 `mineru.min.css`。其可读源码为 `mineru.css`,所有文档规则均限定在 `.mineru-document` 内,standalone 外围布局规则限定在 `.mineru-html-body`,不会修改 fragment 宿主页的全局标签样式。样式使用系统字体,不加载外部字体。有公式时按需加载固定 MathJax 4.1.2 `tex-chtml.js`,启用 `ui/safe`、禁用 `require`,并关闭菜单和 enrichment。有可高亮代码时按需加载固定 Prism 1.30.0 core 和 Autoloader,-语言组件根固定到同版本 jsDelivr。入口脚本携带 SRI;动态 MathJax 扩展、字体和 Prism-语言组件没有逐文件 SRI。renderer 不注入 CSP,HTTP 宿主需要自行允许相应 jsDelivr-script/font/style,并评估 CDN 供应链策略。--fragment 调用方需要加载随包提供的 `mineru.min.css`,并按实际内容加载同版本 MathJax-和 Prism。MathJax 必须在初始化前复用 standalone 的 delimiter、+语言组件根固定到同版本 jsDelivr。合法 flowchart 按需加载固定 Mermaid 11.16.1 UMD;+该约 3.57 MB bundle 只在含流程图的文档下载并可由浏览器缓存。三个入口脚本均携带 SRI;+动态 MathJax 扩展、字体和 Prism 语言组件没有逐文件 SRI。renderer 不注入 CSP,HTTP+宿主需要自行允许相应 jsDelivr script/font/style,并评估 CDN 供应链策略。++`ImageBlock(sub_type="flowchart")` 仅在 body 是完整 `mermaid` fence,且首个有效语句为+`graph|flowchart + TB|TD|BT|RL|LR` 时生成 `.mineru-flowchart`。frontmatter、init directive、+其他 Mermaid 图类型及超过 50,000 字符的源码沿用普通图片/details 路径,不加载 Mermaid。+合法流程图初始显示已有 raster;Mermaid 以 `securityLevel: "strict"`、禁用 HTML label、+`maxTextSize=50000`、`maxEdges=500` 逐图生成 SVG,成功后替换 raster。无 JS、CDN/语法失败+继续显示 raster;无 raster 时自动展开已转义源码。图源码只在浏览器本地参与渲染。++fragment 调用方需要加载随包提供的 `mineru.min.css`,并按实际内容加载同版本+MathJax、Prism 和 Mermaid。MathJax 必须在初始化前复用 standalone 的 delimiter、`ignoreHtmlClass/processHtmlClass`、`ui/safe`、禁用 `require` 及 safeOptions 配置。动态插入后调用`MathJax.typesetPromise([root])` 与 `Prism.highlightAllUnder(root)`;替换已有公式前先调用`MathJax.typesetClear([root])`。fragment 内的相对图片以宿主页 URL 为基准,不能通过@@ -180,6 +194,9 @@ window.MathJax = {standalone 还会通过 `startup.ready` 把 menu/enrichment 选项重新施加到 live MathDocument;fragment 宿主如需完全相同行为,也必须复用该 hook,而不能只复制上面的静态字段。+fragment 中的 flowchart 只包含 canvas、fallback 与源码 DOM;宿主必须复用 standalone 的+Mermaid 11.16.1、SRI、安全配置、顺序 `mermaid.render()` 和失败状态切换,且不得调用+`bindFunctions`。Mermaid 点击指令和 HTML label 在本契约中始终禁用。HTML table/chart/image body 只在识别为 markup 时经过 `nh3` allowlist。活动标签、事件属性、来源 style/class/id/data 属性和危险 URL 会被删除;链接只允许相对地址、fragment、diff --git a/mineru/render/_internal/html/inline.py b/mineru/render/_internal/html/inline.pyindex a262426a..499fe696 100644--- a/mineru/render/_internal/html/inline.py+++ b/mineru/render/_internal/html/inline.py@@ -4,8 +4,10 @@from __future__ import annotationsimport html+import ipaddressimport refrom dataclasses import dataclass+from urllib.parse import urlsplitfrom mineru.render._internal.common.inline import (InlineEquation,@@ -20,6 +22,73 @@ from mineru.render._internal.common.inline import (from mineru.render._internal.html.sanitizer import sanitize_link_url+_AUTOLINK_TLD_PATTERN = r"(?:[A-Za-z]{2,63}|xn--[A-Za-z0-9-]{2,59})"+_AUTOLINK_DOMAIN_PATTERN = (+ rf"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{{0,61}}[A-Za-z0-9])?\.){{1,10}}{_AUTOLINK_TLD_PATTERN}"+)+_AUTOLINK_EMAIL_EDGE_PATTERN = r"[A-Za-z0-9!#$%&'*+/=?^_{|}~-]"+_AUTOLINK_EMAIL_PATTERN = (+ rf"{_AUTOLINK_EMAIL_EDGE_PATTERN}"+ rf"(?:[A-Za-z0-9.!#$%&'*+/=?^_{{|}}~-]{{0,62}}{_AUTOLINK_EMAIL_EDGE_PATTERN})?"+ rf"@{_AUTOLINK_DOMAIN_PATTERN}"+)+_AUTOLINK_EXPLICIT_HOST_PATTERN = (+ rf"(?:{_AUTOLINK_DOMAIN_PATTERN}|localhost|(?:\d{{1,3}}\.){{3}}\d{{1,3}}|\[[0-9A-Fa-f:.]+\])"+)+_AUTOLINK_URL_TAIL_PATTERN = (+ r"(?::\d{1,5})?(?:[/?#](?:(?!https?://)[A-Za-z0-9._~:/?#\[\]@!$&()*+,;=%-])*)?"+)+_AUTOLINK_RE = re.compile(+ rf"(?:(?P<email>(?<![A-Za-z0-9._%+@-]){_AUTOLINK_EMAIL_PATTERN})"+ rf"|(?P<explicit>https?://{_AUTOLINK_EXPLICIT_HOST_PATTERN}{_AUTOLINK_URL_TAIL_PATTERN})"+ rf"|(?P<www>(?<![A-Za-z0-9._%+@-])www\.{_AUTOLINK_DOMAIN_PATTERN}{_AUTOLINK_URL_TAIL_PATTERN})"+ rf"|(?P<domain>(?<![A-Za-z0-9._%+@-]){_AUTOLINK_DOMAIN_PATTERN}{_AUTOLINK_URL_TAIL_PATTERN}))",+ re.IGNORECASE,+)+_AUTOLINK_UNSUPPORTED_SCHEME_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:[^\s]*$")+_AUTOLINK_TRAILING_PUNCTUATION = ".,;:!?,。;:!?、"+_AUTOLINK_CLOSING_PAIRS = {")": "(", "]": "[", "}": "{", ")": "(", "】": "【", "》": "《"}+_AUTOLINK_COMMON_BARE_TLDS = frozenset(+ {+ "ai",+ "app",+ "au",+ "biz",+ "br",+ "ca",+ "cloud",+ "cn",+ "com",+ "de",+ "dev",+ "edu",+ "eu",+ "fr",+ "gov",+ "hk",+ "in",+ "info",+ "io",+ "jp",+ "kr",+ "net",+ "nl",+ "nz",+ "online",+ "org",+ "ru",+ "sg",+ "shop",+ "site",+ "store",+ "tech",+ "tw",+ "uk",+ "xyz",+ }+)++@dataclass(frozen=True, slots=True)class HtmlInlineResult:"""保存一段行内 HTML 及其是否包含需由 MathJax 处理的公式。"""@@ -41,6 +110,7 @@ def render_joined_inline_contents_html(contents: list[str]) -> HtmlInlineResult:def render_inline_nodes_html(nodes: list[InlineNode],*,+ linkify_text: bool = True,separate_adjacent_math: bool = False,preserve_newlines: bool = False,) -> HtmlInlineResult:@@ -49,7 +119,11 @@ def render_inline_nodes_html(has_math = Falseprevious_was_math = Falsefor node in nodes:- rendered = _render_inline_node_html(node, preserve_newlines=preserve_newlines)+ rendered = _render_inline_node_html(+ node,+ linkify_text=linkify_text,+ preserve_newlines=preserve_newlines,+ )if not rendered.html:continuecurrent_is_math = isinstance(node, InlineEquation)@@ -79,22 +153,40 @@ def render_math_html(latex: str, *, display: bool) -> HtmlInlineResult:)-def _render_inline_node_html(node: InlineNode, *, preserve_newlines: bool) -> HtmlInlineResult:+def _render_inline_node_html(+ node: InlineNode,+ *,+ linkify_text: bool,+ preserve_newlines: bool,+) -> HtmlInlineResult:"""把一个共享行内节点映射为 HTML。"""if isinstance(node, InlineText):- escaped = _escape_text(node.content)- return HtmlInlineResult(escaped if preserve_newlines else escaped.replace("\n", "<br>\n"))+ return HtmlInlineResult(+ _render_text_html(+ node.content,+ linkify_text=linkify_text,+ preserve_newlines=preserve_newlines,+ )+ )if isinstance(node, InlineEquation):return render_math_html(node.latex, display=False)if isinstance(node, InlineStyled):- children = render_inline_nodes_html(node.children, preserve_newlines=preserve_newlines)+ children = render_inline_nodes_html(+ node.children,+ linkify_text=linkify_text,+ preserve_newlines=preserve_newlines,+ )rendered = _apply_html_styles(children.html, node.styles)plain_text = inline_plain_text(node.children)if _needs_whitespace_preservation(plain_text):rendered = f'<span class="mineru-preserve-whitespace">{rendered}</span>'return HtmlInlineResult(rendered, children.has_math)if isinstance(node, InlineLink):- children = render_inline_nodes_html(node.children, preserve_newlines=preserve_newlines)+ children = render_inline_nodes_html(+ node.children,+ linkify_text=False,+ preserve_newlines=preserve_newlines,+ )safe_url = sanitize_link_url(node.url)if not safe_url or safe_url == ".":return children@@ -106,6 +198,110 @@ def _render_inline_node_html(node: InlineNode, *, preserve_newlines: bool) -> Htraise TypeError(f"Unsupported inline node: {type(node).__name__}")+def _render_text_html(+ content: str,+ *,+ linkify_text: bool,+ preserve_newlines: bool,+) -> str:+ """转义普通文本,并按需把安全 URL-like 候选转换为链接。"""+ if not linkify_text:+ return _escape_text_with_breaks(content, preserve_newlines=preserve_newlines)++ parts: list[str] = []+ cursor = 0+ for match in _AUTOLINK_RE.finditer(content):+ candidate = match.group(0)+ candidate, trailing = _trim_autolink_candidate(candidate)+ if not candidate or _is_embedded_autolink_candidate(content, match, candidate):+ continue+ href = _autolink_href(match, candidate)+ if href is None:+ continue+ parts.append(_escape_text_with_breaks(content[cursor : match.start()], preserve_newlines=preserve_newlines))+ escaped_href = html.escape(href, quote=True)+ escaped_label = _escape_text_with_breaks(candidate, preserve_newlines=preserve_newlines)+ parts.append(f'<a href="{escaped_href}" rel="noopener noreferrer">{escaped_label}</a>')+ cursor = match.end() - len(trailing)+ parts.append(_escape_text_with_breaks(content[cursor:], preserve_newlines=preserve_newlines))+ return "".join(parts)+++def _trim_autolink_candidate(candidate: str) -> tuple[str, str]:+ """去除 URL 尾部句读和不平衡右括号,并返回应保留的原文后缀。"""+ end = len(candidate)+ while end and candidate[end - 1] in _AUTOLINK_TRAILING_PUNCTUATION:+ end -= 1+ changed = True+ while end and changed:+ changed = False+ closing = candidate[end - 1]+ opening = _AUTOLINK_CLOSING_PAIRS.get(closing)+ if opening is not None and candidate[:end].count(closing) > candidate[:end].count(opening):+ end -= 1+ changed = True+ return candidate[:end], candidate[end:]+++def _is_embedded_autolink_candidate(+ content: str,+ match: re.Match[str],+ candidate: str,+) -> bool:+ """拒绝未知协议、相对路径和裸 IP 内部的模糊候选。"""+ if match.group("explicit") is not None:+ return False+ prefix = content[max(0, match.start() - 32) : match.start()]+ if _AUTOLINK_UNSUPPORTED_SCHEME_RE.search(prefix) is not None:+ return True+ if match.group("email") is not None:+ return False+ if match.start() and content[match.start() - 1] in "/\\":+ return True+ host = candidate.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].split(":", 1)[0]+ try:+ ipaddress.ip_address(host)+ except ValueError:+ return False+ return True+++def _autolink_href(match: re.Match[str], candidate: str) -> str | None:+ """把候选转换为显式安全 href,并验证端口和显式 IP 地址。"""+ if match.group("email") is not None:+ if ".." in candidate.rsplit("@", 1)[0]:+ return None+ href = f"mailto:{candidate}"+ elif match.group("explicit") is not None:+ href = candidate+ else:+ if match.group("domain") is not None and not _is_allowed_bare_domain(candidate):+ return None+ href = f"https://{candidate}"+ try:+ parsed = urlsplit(href)+ _ = parsed.port+ if parsed.hostname and re.fullmatch(r"\d+(?:\.\d+){3}", parsed.hostname):+ ipaddress.ip_address(parsed.hostname)+ except ValueError:+ return None+ return sanitize_link_url(href)+++def _is_allowed_bare_domain(candidate: str) -> bool:+ """仅允许工程常用 TLD 的无协议裸域名,减少文件名和股票代码误判。"""+ authority = re.split(r"[/?#]", candidate, maxsplit=1)[0]+ host = authority.rsplit(":", 1)[0]+ tld = host.rsplit(".", 1)[-1].lower()+ return tld in _AUTOLINK_COMMON_BARE_TLDS+++def _escape_text_with_breaks(content: str, *, preserve_newlines: bool) -> str:+ """转义文本,并按调用方要求把换行转换为 HTML br。"""+ escaped = _escape_text(content)+ return escaped if preserve_newlines else escaped.replace("\n", "<br>\n")++def _apply_html_styles(content: str, styles: tuple[str, ...]) -> str:"""按 Markdown renderer 的稳定顺序应用共享富文本样式。"""if not content:diff --git a/mineru/render/html.py b/mineru/render/html.pyindex fa552674..d906d6a9 100644--- a/mineru/render/html.py+++ b/mineru/render/html.py@@ -66,6 +66,13 @@ _PRISM_CORE_INTEGRITY = "sha384-zLRFO4dwowZvh8kzutOb5AWhH7f39HeJp+N7PtHF1SQtTBni_PRISM_AUTOLOADER_URL = "https://cdn.jsdelivr.net/npm/[email protected]/plugins/autoloader/prism-autoloader.min.js"_PRISM_AUTOLOADER_INTEGRITY = "sha384-Uq05+JLko69eOiPr39ta9bh7kld5PKZoU+fF7g0EXTAriEollhZ+DrN8Q/Oi8J2Q"_PRISM_LANGUAGES_PATH = "https://cdn.jsdelivr.net/npm/[email protected]/components/"+_MERMAID_URL = "https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"+_MERMAID_INTEGRITY = "sha384-aBQXj4hK6Jm05i7aQAsUV3bLdSUrHX1BGYfMB0166TtWt/RRaw+h0Eelme9OCOvy"+_MERMAID_MAX_TEXT_SIZE = 50_000+_MERMAID_FLOWCHART_HEADER_RE = re.compile(+ r"(?:graph|flowchart)\s+(?:TB|TD|BT|RL|LR)\b",+ re.IGNORECASE,+)_SAFE_PRISM_LANGUAGE_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,31}")_BLOCKED_PRISM_LANGUAGE_NAMES = {"constructor", "prototype"}_PRISM_LANGUAGE_ALIASES = {@@ -107,6 +114,7 @@ class _HtmlRenderer:self.emitted_anchors: set[str] = set()self.has_math = Falseself.has_prism = False+ self.has_mermaid = Falsedef render(self) -> str:"""生成 fragment article,并按需包装完整 HTML 文档。"""@@ -126,6 +134,7 @@ class _HtmlRenderer:for code in article_soup.find_all("code")if code.get_text())+ self.has_mermaid = article_soup.select_one(".mineru-flowchart") is not Nonereturn self._render_standalone(article)def _render_default_pages(self, planned_pages: list[list[PlannedBlock]]) -> str:@@ -376,8 +385,12 @@ class _HtmlRenderer:def _render_image_body(self, parent: ImageBlock, block: ImageBodyBlock) -> str:"""渲染图片,并把并存的识别内容放入原生 details。"""+ if parent.sub_type == "flowchart":+ mermaid_source = _extract_mermaid_flowchart_source(block.content)+ if mermaid_source is not None:+ return self._render_flowchart_body(block, mermaid_source)source = self._safe_block_image_source(block)- content = self._render_embedded_content(block.content)+ content = self._render_embedded_content(block.content, linkify_text=parent.sub_type != "flowchart")alt = _plain_content_text(block.content) or parent.sub_type or "image"parts = [self._render_image(source, alt=alt, class_name="mineru-image")] if source else []if content.html:@@ -387,6 +400,23 @@ class _HtmlRenderer:parts.append(content.html)return "".join(parts)+ def _render_flowchart_body(self, block: ImageBodyBlock, mermaid_source: str) -> str:+ """输出 Mermaid canvas,并保留 raster 与源码两级失败回退。"""+ source = self._safe_block_image_source(block)+ escaped_source = html.escape(_replace_html_controls(mermaid_source), quote=False)+ fallback = self._render_image(source, alt="flowchart", class_name="mineru-flowchart-fallback") if source else ""+ fallback_class = " mineru-flowchart--has-raster" if fallback else ""+ details_open = "" if fallback else " open"+ return (+ f'<div class="mineru-flowchart{fallback_class}" data-mermaid-state="pending">'+ '<div class="mineru-flowchart-canvas" role="img" aria-label="flowchart"></div>'+ f"{fallback}</div>"+ f'<details class="mineru-details mineru-flowchart-details"{details_open}>'+ '<summary>flowchart source</summary>'+ f'<pre class="mineru-flowchart-source"><code>{escaped_source}</code></pre>'+ "</details>"+ )+def _render_table_block(self, block: TableBlock) -> str:"""按原始子块顺序渲染表格主体、标题与脚注。"""parts: list[str] = []@@ -490,6 +520,7 @@ class _HtmlRenderer:if parent.sub_type == RAW_ALGORITHM:rendered = render_inline_nodes_html(parse_inline_content(block.content),+ linkify_text=False,separate_adjacent_math=True,preserve_newlines=True,)@@ -511,13 +542,13 @@ class _HtmlRenderer:type_class = html.escape(str(block.type).replace("_", "-"), quote=True)return f'<p class="{role_class} {role_class}--{type_class}">{rendered.html}</p>'- def _render_embedded_content(self, content: str) -> HtmlInlineResult:+ def _render_embedded_content(self, content: str, *, linkify_text: bool = True) -> HtmlInlineResult:"""安全处理 body 富 HTML;普通内容走共享 inline AST。"""normalized = content.strip()if not normalized:return HtmlInlineResult("")if not is_supported_html_markup(normalized):- rendered = render_inline_content_html(content)+ rendered = render_inline_nodes_html(parse_inline_content(content), linkify_text=linkify_text)self._observe_inline(rendered)return renderedsanitized = sanitize_html_fragment(normalized, asset_base_url=self.asset_base_url)@@ -579,6 +610,8 @@ class _HtmlRenderer:dependencies.append(_mathjax_head())if self.has_prism:dependencies.append(_prism_head())+ if self.has_mermaid:+ dependencies.append(_mermaid_head())dependency_html = "\n".join(dependencies)return ("<!doctype html>\n"@@ -712,6 +745,34 @@ def _plain_content_text(content: str) -> str:return inline_plain_text(parse_inline_content(content)).strip()+def _extract_mermaid_flowchart_source(content: str) -> str | None:+ """提取受限 Mermaid flowchart fence,拒绝其他图类型和可改写配置的语法。"""+ normalized = _replace_html_controls(content).replace("\r\n", "\n").replace("\r", "\n").strip()+ if not normalized:+ return None+ lines = normalized.split("\n")+ if len(lines) < 3:+ return None+ opening = re.fullmatch(r"(?P<fence>\x60{3,})[ \t]*mermaid[ \t]*", lines[0], re.IGNORECASE)+ if opening is None:+ return None+ fence_length = len(opening.group("fence"))+ if re.fullmatch(rf"\x60{{{fence_length},}}[ \t]*", lines[-1]) is None:+ return None+ source = "\n".join(lines[1:-1]).strip("\n")+ if not source or len(source) > _MERMAID_MAX_TEXT_SIZE:+ return None+ if source.lstrip().startswith("---") or "%%{" in source:+ return None+ first_statement = next(+ (line.strip() for line in source.splitlines() if line.strip() and not line.lstrip().startswith("%%")),+ "",+ )+ if _MERMAID_FLOWCHART_HEADER_RE.match(first_statement) is None:+ return None+ return source++def _contains_usable_table(markup: str) -> bool:"""确认清洗后的 markup 至少保留一个含单元格的 table。"""soup = BeautifulSoup(markup, "html.parser")@@ -817,4 +878,64 @@ document.addEventListener('DOMContentLoaded', function () {{</script>"""+def _mermaid_head() -> str:+ """返回固定 Mermaid 入口和逐图安全渲染、失败回退脚本。"""+ return f"""<script defer src="{_MERMAID_URL}"+ integrity="{_MERMAID_INTEGRITY}" crossorigin="anonymous" referrerpolicy="no-referrer"></script>+<script>+function markMineruMermaidError(host) {{+ host.dataset.mermaidState = 'error';+ if (!host.classList.contains('mineru-flowchart--has-raster')) {{+ var details = host.nextElementSibling;+ if (details && details.classList.contains('mineru-flowchart-details')) details.open = true;+ }}+}}+document.addEventListener('DOMContentLoaded', function () {{+ var root = document.querySelector('.mineru-document');+ var hosts = root ? Array.from(root.querySelectorAll('.mineru-flowchart')) : [];+ if (!hosts.length) return;+ if (!window.mermaid) {{+ hosts.forEach(markMineruMermaidError);+ return;+ }}+ try {{+ window.mermaid.initialize({{+ startOnLoad: false,+ securityLevel: 'strict',+ suppressErrorRendering: true,+ theme: 'neutral',+ maxTextSize: 50000,+ maxEdges: 500,+ flowchart: {{htmlLabels: false, useMaxWidth: true}}+ }});+ }} catch (_error) {{+ hosts.forEach(markMineruMermaidError);+ return;+ }}+ (async function () {{+ for (var index = 0; index < hosts.length; index += 1) {{+ var host = hosts[index];+ var details = host.nextElementSibling;+ var source = details && details.querySelector('.mineru-flowchart-source code');+ var canvas = host.querySelector('.mineru-flowchart-canvas');+ if (!source || !canvas) {{+ markMineruMermaidError(host);+ continue;+ }}+ var renderId = 'mineru-mermaid-' + index;+ while (document.getElementById(renderId)) renderId += '-x';+ host.dataset.mermaidState = 'rendering';+ try {{+ var result = await window.mermaid.render(renderId, source.textContent);+ canvas.innerHTML = result.svg;+ host.dataset.mermaidState = 'rendered';+ }} catch (_error) {{+ markMineruMermaidError(host);+ }}+ }}+ }})();+}});+</script>"""++__all__ = ["render_html"]diff --git a/mineru/resources/html/mineru.css b/mineru/resources/html/mineru.cssindex 095d9c43..2ca7b6a9 100644--- a/mineru/resources/html/mineru.css+++ b/mineru/resources/html/mineru.css@@ -282,6 +282,49 @@margin-inline: auto;}+/* Mermaid 成功后替换 raster;无 JS、加载或语法失败时保留图片/源码回退。 */+.mineru-document .mineru-flowchart {+ margin: 1rem auto;+ max-width: 100%;+ overflow-x: auto;+}++.mineru-document .mineru-flowchart-canvas {+ display: none;+ min-width: 0;+ text-align: center;+}++.mineru-document .mineru-flowchart-canvas svg {+ display: block;+ height: auto;+ margin-inline: auto;+ max-width: 100%;+}++.mineru-document .mineru-flowchart-fallback {+ display: block;+ margin-inline: auto;+}++.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-canvas {+ display: block;+}++.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-fallback {+ display: none;+}++.mineru-document .mineru-flowchart-details {+ max-width: 100%;+}++.mineru-document .mineru-flowchart-source {+ max-height: 24rem;+ text-align: left;+ white-space: pre;+}+.mineru-document .mineru-caption {color: var(--mineru-muted);font-size: 0.9em;diff --git a/mineru/resources/html/mineru.min.css b/mineru/resources/html/mineru.min.cssindex 251a6b51..918d950f 100644--- a/mineru/resources/html/mineru.min.css+++ b/mineru/resources/html/mineru.min.css@@ -1 +1 @@-.mineru-html-body{background:#ffffff;margin:0}.mineru-html-body>.mineru-document{margin:0 auto;max-width:60rem;min-height:100vh;padding:2rem}.mineru-document{--mineru-accent:#0b6fc2;--mineru-accent-hover:#075a9c;--mineru-background:#ffffff;--mineru-border:#d1d5db;--mineru-muted:#6b7280;--mineru-surface:#f8fafc;--mineru-text:#1f2937;background:var(--mineru-background);box-sizing:border-box;color:var(--mineru-text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:16px;line-height:1.65;overflow-wrap:break-word;width:100%}.mineru-document *,.mineru-document *::before,.mineru-document *::after{box-sizing:inherit}.mineru-document :is(h1,h2,h3,h4,h5,h6){color:var(--mineru-text);font-weight:600;line-height:1.3;margin:1.5em 0 0.65em}.mineru-document h1{font-size:2rem}.mineru-document h2{font-size:1.5rem}.mineru-document h3{font-size:1.25rem}.mineru-document h4{font-size:1.125rem}.mineru-document h5{font-size:1rem}.mineru-document h6{color:var(--mineru-muted);font-size:0.875rem}.mineru-document .mineru-block:first-child>:first-child,.mineru-document .mineru-page>.mineru-block:first-child>:first-child{margin-top:0}.mineru-document p{margin:0 0 1rem}.mineru-document :is(strong,b){font-weight:700}.mineru-document :is(s,del){color:var(--mineru-muted)}.mineru-document a{color:var(--mineru-accent);text-decoration:none;text-underline-offset:0.15em}.mineru-document a:hover{color:var(--mineru-accent-hover);text-decoration:underline}.mineru-document a:focus-visible{border-radius:0.15rem;outline:2px solid var(--mineru-accent);outline-offset:2px}.mineru-document blockquote{background:var(--mineru-surface);border-left:0.25rem solid var(--mineru-accent);color:var(--mineru-muted);margin:1rem 0;padding:0.75rem 1rem}.mineru-document blockquote>:first-child{margin-top:0}.mineru-document blockquote>:last-child{margin-bottom:0}.mineru-document :is(ol,ul){margin:0 0 1rem;padding-left:1.75rem}.mineru-document ul{list-style:disc}.mineru-document ul ul{list-style:circle}.mineru-document ul ul ul{list-style:square}.mineru-document ol{list-style:decimal}.mineru-document :is(ol,ul) ol{list-style-type:lower-roman}.mineru-document :is(ol,ul) :is(ol,ul) ol{list-style-type:lower-alpha}.mineru-document li + li{margin-top:0.25rem}.mineru-document li>:is(ol,ul){margin-bottom:0;margin-top:0.25rem}.mineru-document .mineru-list--explicit{list-style:none;padding-left:1.5rem}.mineru-document .mineru-list--unmarked{list-style:none;padding-left:0}.mineru-document .mineru-list-item--explicit{align-items:start;display:grid;gap:0.5em;grid-template-columns:max-content minmax(0,1fr)}.mineru-document .mineru-list-item--orphan{display:grid;grid-template-columns:0 minmax(0,1fr);list-style:none}.mineru-document .mineru-list-item--markerless{list-style:none}.mineru-document .mineru-list-marker{font-variant-numeric:tabular-nums;text-align:right;user-select:none;white-space:pre}.mineru-document .mineru-list-content{min-width:0}.mineru-document .mineru-list-item--orphan>.mineru-list-marker{visibility:hidden}.mineru-document .mineru-list-item--orphan>:is(ol,ul),.mineru-document .mineru-list-item--explicit>:is(ol,ul){grid-column:2;margin-bottom:0}.mineru-document .mineru-index,.mineru-document .mineru-index ul{list-style:none;padding-left:0}.mineru-document .mineru-index ul ul{padding-left:1.5rem}.mineru-document .mineru-index a{overflow-wrap:anywhere}.mineru-document table{border-collapse:collapse;border-spacing:0;display:block;margin:1rem 0;max-width:100%;overflow-x:auto;width:100%}.mineru-document :is(th,td){border:1px solid var(--mineru-border);padding:0.5rem 0.75rem;text-align:left;vertical-align:top}.mineru-document th{background:var(--mineru-surface);font-weight:600}.mineru-document caption{color:var(--mineru-muted);margin-bottom:0.5rem;text-align:left}.mineru-document :is(th,td).mineru-align-left{text-align:left}.mineru-document :is(th,td).mineru-align-center{text-align:center}.mineru-document :is(th,td).mineru-align-right{text-align:right}.mineru-document img{height:auto;max-width:100%}.mineru-document .mineru-figure{margin:1.5rem 0;max-width:100%}.mineru-document :is(.mineru-figure--table,.mineru-figure--chart){margin-inline:auto;width:fit-content}.mineru-document .mineru-figure>img{display:block;margin-inline:auto}.mineru-document .mineru-caption{color:var(--mineru-muted);font-size:0.9em;margin-top:0.5rem;text-align:center}.mineru-document .mineru-footnote{color:var(--mineru-muted);font-size:0.875em;margin-top:0.4rem}.mineru-document .mineru-details{border:1px solid var(--mineru-border);border-radius:0.375rem;margin:1rem 0;padding:0.65rem 0.85rem}.mineru-document .mineru-details>summary{cursor:pointer;font-weight:600}.mineru-document .mineru-page-aux{color:var(--mineru-muted);font-size:0.875rem}.mineru-document code,.mineru-document pre,.mineru-document .mineru-algorithm{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.mineru-document code{background:var(--mineru-surface);border-radius:0.25rem;font-size:0.875em;padding:0.15em 0.35em}.mineru-document pre{background:var(--mineru-surface);border:1px solid var(--mineru-border);border-radius:0.375rem;line-height:1.5;margin:1rem 0;max-width:100%;overflow:auto;padding:1rem;tab-size:4;white-space:pre}.mineru-document pre>code{background:transparent;border-radius:0;display:inline;font-size:inherit;line-height:inherit;padding:0;white-space:inherit}.mineru-document :is(code,pre)[class*="language-"]{color:#374151;text-align:left;text-shadow:none;word-break:normal;word-spacing:normal}.mineru-document .token.comment,.mineru-document .token.prolog,.mineru-document .token.doctype,.mineru-document .token.cdata{color:#6b7280}.mineru-document .token.punctuation{color:#374151}.mineru-document .token.namespace{opacity:0.75}.mineru-document .token.keyword,.mineru-document .token.operator,.mineru-document .token.important,.mineru-document .token.atrule{color:#7c3aed}.mineru-document .token.string,.mineru-document .token.attr-value,.mineru-document .token.regex,.mineru-document .token.url{color:#047857}.mineru-document .token.number,.mineru-document .token.boolean,.mineru-document .token.constant,.mineru-document .token.property,.mineru-document .token.symbol{color:#0369a1}.mineru-document .token.tag,.mineru-document .token.selector,.mineru-document .token.builtin{color:#b45309}.mineru-document .token.function,.mineru-document .token.class-name,.mineru-document .token.attr-name{color:#be123c}.mineru-document .token.important,.mineru-document .token.bold{font-weight:700}.mineru-document .token.italic{font-style:italic}.mineru-document .token.inserted{background:#ecfdf5;color:#047857}.mineru-document .token.deleted{background:#fff1f2;color:#be123c}.mineru-document .token.entity{cursor:help}.mineru-document .mineru-algorithm{max-width:100%;overflow-x:auto;tab-size:4;white-space:pre-wrap;word-break:normal}.mineru-document .mineru-table-text,.mineru-document .mineru-raw-fallback{overflow:auto;tab-size:4;white-space:pre-wrap;word-break:break-word}.mineru-document .mineru-table-text{white-space:pre}.mineru-document .mineru-raw-fallback{border-left:0.2rem solid var(--mineru-border);color:var(--mineru-muted)}.mineru-document .mineru-math{overflow-wrap:anywhere}.mineru-document .mineru-math--block{display:block;margin:1rem 0;max-width:100%;overflow-x:auto;overflow-y:hidden;text-align:center}.mineru-document mjx-container[display="true"]{max-width:100%;overflow-x:auto;overflow-y:hidden}.mineru-document .mineru-preserve-whitespace{white-space:pre-wrap}.mineru-document .mineru-text-emphasis{-webkit-text-emphasis:dot;-webkit-text-emphasis-position:under right;text-emphasis:dot;text-emphasis-position:under right}.mineru-document .mineru-page{min-width:0;position:relative}.mineru-document--full .mineru-page{min-height:1.5rem}.mineru-document .mineru-page-break{background:transparent;border:0;border-top:1px dashed var(--mineru-border);height:0;margin:2rem 0}@media screen and (max-width:40rem){.mineru-html-body>.mineru-document{padding:1rem}.mineru-document h1{font-size:1.75rem}.mineru-document :is(th,td){padding:0.4rem 0.55rem}}@media print{.mineru-html-body{background:#ffffff}.mineru-html-body>.mineru-document{max-width:none;min-height:0;padding:0}.mineru-document .mineru-page-break{display:none}.mineru-document--full .mineru-page{break-after:page;page-break-after:always}.mineru-document--full .mineru-page:last-child{break-after:auto;page-break-after:auto}.mineru-document .mineru-figure{break-inside:avoid;page-break-inside:avoid}.mineru-document table{display:table;overflow:visible}.mineru-document pre{overflow:visible;white-space:pre-wrap;word-break:break-word}}\ No newline at end of file+.mineru-html-body{background:#ffffff;margin:0}.mineru-html-body>.mineru-document{margin:0 auto;max-width:60rem;min-height:100vh;padding:2rem}.mineru-document{--mineru-accent:#0b6fc2;--mineru-accent-hover:#075a9c;--mineru-background:#ffffff;--mineru-border:#d1d5db;--mineru-muted:#6b7280;--mineru-surface:#f8fafc;--mineru-text:#1f2937;background:var(--mineru-background);box-sizing:border-box;color:var(--mineru-text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:16px;line-height:1.65;overflow-wrap:break-word;width:100%}.mineru-document *,.mineru-document *::before,.mineru-document *::after{box-sizing:inherit}.mineru-document :is(h1,h2,h3,h4,h5,h6){color:var(--mineru-text);font-weight:600;line-height:1.3;margin:1.5em 0 0.65em}.mineru-document h1{font-size:2rem}.mineru-document h2{font-size:1.5rem}.mineru-document h3{font-size:1.25rem}.mineru-document h4{font-size:1.125rem}.mineru-document h5{font-size:1rem}.mineru-document h6{color:var(--mineru-muted);font-size:0.875rem}.mineru-document .mineru-block:first-child>:first-child,.mineru-document .mineru-page>.mineru-block:first-child>:first-child{margin-top:0}.mineru-document p{margin:0 0 1rem}.mineru-document :is(strong,b){font-weight:700}.mineru-document :is(s,del){color:var(--mineru-muted)}.mineru-document a{color:var(--mineru-accent);text-decoration:none;text-underline-offset:0.15em}.mineru-document a:hover{color:var(--mineru-accent-hover);text-decoration:underline}.mineru-document a:focus-visible{border-radius:0.15rem;outline:2px solid var(--mineru-accent);outline-offset:2px}.mineru-document blockquote{background:var(--mineru-surface);border-left:0.25rem solid var(--mineru-accent);color:var(--mineru-muted);margin:1rem 0;padding:0.75rem 1rem}.mineru-document blockquote>:first-child{margin-top:0}.mineru-document blockquote>:last-child{margin-bottom:0}.mineru-document :is(ol,ul){margin:0 0 1rem;padding-left:1.75rem}.mineru-document ul{list-style:disc}.mineru-document ul ul{list-style:circle}.mineru-document ul ul ul{list-style:square}.mineru-document ol{list-style:decimal}.mineru-document :is(ol,ul) ol{list-style-type:lower-roman}.mineru-document :is(ol,ul) :is(ol,ul) ol{list-style-type:lower-alpha}.mineru-document li + li{margin-top:0.25rem}.mineru-document li>:is(ol,ul){margin-bottom:0;margin-top:0.25rem}.mineru-document .mineru-list--explicit{list-style:none;padding-left:1.5rem}.mineru-document .mineru-list--unmarked{list-style:none;padding-left:0}.mineru-document .mineru-list-item--explicit{align-items:start;display:grid;gap:0.5em;grid-template-columns:max-content minmax(0,1fr)}.mineru-document .mineru-list-item--orphan{display:grid;grid-template-columns:0 minmax(0,1fr);list-style:none}.mineru-document .mineru-list-item--markerless{list-style:none}.mineru-document .mineru-list-marker{font-variant-numeric:tabular-nums;text-align:right;user-select:none;white-space:pre}.mineru-document .mineru-list-content{min-width:0}.mineru-document .mineru-list-item--orphan>.mineru-list-marker{visibility:hidden}.mineru-document .mineru-list-item--orphan>:is(ol,ul),.mineru-document .mineru-list-item--explicit>:is(ol,ul){grid-column:2;margin-bottom:0}.mineru-document .mineru-index,.mineru-document .mineru-index ul{list-style:none;padding-left:0}.mineru-document .mineru-index ul ul{padding-left:1.5rem}.mineru-document .mineru-index a{overflow-wrap:anywhere}.mineru-document table{border-collapse:collapse;border-spacing:0;display:block;margin:1rem 0;max-width:100%;overflow-x:auto;width:100%}.mineru-document :is(th,td){border:1px solid var(--mineru-border);padding:0.5rem 0.75rem;text-align:left;vertical-align:top}.mineru-document th{background:var(--mineru-surface);font-weight:600}.mineru-document caption{color:var(--mineru-muted);margin-bottom:0.5rem;text-align:left}.mineru-document :is(th,td).mineru-align-left{text-align:left}.mineru-document :is(th,td).mineru-align-center{text-align:center}.mineru-document :is(th,td).mineru-align-right{text-align:right}.mineru-document img{height:auto;max-width:100%}.mineru-document .mineru-figure{margin:1.5rem 0;max-width:100%}.mineru-document :is(.mineru-figure--table,.mineru-figure--chart){margin-inline:auto;width:fit-content}.mineru-document .mineru-figure>img{display:block;margin-inline:auto}.mineru-document .mineru-flowchart{margin:1rem auto;max-width:100%;overflow-x:auto}.mineru-document .mineru-flowchart-canvas{display:none;min-width:0;text-align:center}.mineru-document .mineru-flowchart-canvas svg{display:block;height:auto;margin-inline:auto;max-width:100%}.mineru-document .mineru-flowchart-fallback{display:block;margin-inline:auto}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-canvas{display:block}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-fallback{display:none}.mineru-document .mineru-flowchart-details{max-width:100%}.mineru-document .mineru-flowchart-source{max-height:24rem;text-align:left;white-space:pre}.mineru-document .mineru-caption{color:var(--mineru-muted);font-size:0.9em;margin-top:0.5rem;text-align:center}.mineru-document .mineru-footnote{color:var(--mineru-muted);font-size:0.875em;margin-top:0.4rem}.mineru-document .mineru-details{border:1px solid var(--mineru-border);border-radius:0.375rem;margin:1rem 0;padding:0.65rem 0.85rem}.mineru-document .mineru-details>summary{cursor:pointer;font-weight:600}.mineru-document .mineru-page-aux{color:var(--mineru-muted);font-size:0.875rem}.mineru-document code,.mineru-document pre,.mineru-document .mineru-algorithm{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.mineru-document code{background:var(--mineru-surface);border-radius:0.25rem;font-size:0.875em;padding:0.15em 0.35em}.mineru-document pre{background:var(--mineru-surface);border:1px solid var(--mineru-border);border-radius:0.375rem;line-height:1.5;margin:1rem 0;max-width:100%;overflow:auto;padding:1rem;tab-size:4;white-space:pre}.mineru-document pre>code{background:transparent;border-radius:0;display:inline;font-size:inherit;line-height:inherit;padding:0;white-space:inherit}.mineru-document :is(code,pre)[class*="language-"]{color:#374151;text-align:left;text-shadow:none;word-break:normal;word-spacing:normal}.mineru-document .token.comment,.mineru-document .token.prolog,.mineru-document .token.doctype,.mineru-document .token.cdata{color:#6b7280}.mineru-document .token.punctuation{color:#374151}.mineru-document .token.namespace{opacity:0.75}.mineru-document .token.keyword,.mineru-document .token.operator,.mineru-document .token.important,.mineru-document .token.atrule{color:#7c3aed}.mineru-document .token.string,.mineru-document .token.attr-value,.mineru-document .token.regex,.mineru-document .token.url{color:#047857}.mineru-document .token.number,.mineru-document .token.boolean,.mineru-document .token.constant,.mineru-document .token.property,.mineru-document .token.symbol{color:#0369a1}.mineru-document .token.tag,.mineru-document .token.selector,.mineru-document .token.builtin{color:#b45309}.mineru-document .token.function,.mineru-document .token.class-name,.mineru-document .token.attr-name{color:#be123c}.mineru-document .token.important,.mineru-document .token.bold{font-weight:700}.mineru-document .token.italic{font-style:italic}.mineru-document .token.inserted{background:#ecfdf5;color:#047857}.mineru-document .token.deleted{background:#fff1f2;color:#be123c}.mineru-document .token.entity{cursor:help}.mineru-document .mineru-algorithm{max-width:100%;overflow-x:auto;tab-size:4;white-space:pre-wrap;word-break:normal}.mineru-document .mineru-table-text,.mineru-document .mineru-raw-fallback{overflow:auto;tab-size:4;white-space:pre-wrap;word-break:break-word}.mineru-document .mineru-table-text{white-space:pre}.mineru-document .mineru-raw-fallback{border-left:0.2rem solid var(--mineru-border);color:var(--mineru-muted)}.mineru-document .mineru-math{overflow-wrap:anywhere}.mineru-document .mineru-math--block{display:block;margin:1rem 0;max-width:100%;overflow-x:auto;overflow-y:hidden;text-align:center}.mineru-document mjx-container[display="true"]{max-width:100%;overflow-x:auto;overflow-y:hidden}.mineru-document .mineru-preserve-whitespace{white-space:pre-wrap}.mineru-document .mineru-text-emphasis{-webkit-text-emphasis:dot;-webkit-text-emphasis-position:under right;text-emphasis:dot;text-emphasis-position:under right}.mineru-document .mineru-page{min-width:0;position:relative}.mineru-document--full .mineru-page{min-height:1.5rem}.mineru-document .mineru-page-break{background:transparent;border:0;border-top:1px dashed var(--mineru-border);height:0;margin:2rem 0}@media screen and (max-width:40rem){.mineru-html-body>.mineru-document{padding:1rem}.mineru-document h1{font-size:1.75rem}.mineru-document :is(th,td){padding:0.4rem 0.55rem}}@media print{.mineru-html-body{background:#ffffff}.mineru-html-body>.mineru-document{max-width:none;min-height:0;padding:0}.mineru-document .mineru-page-break{display:none}.mineru-document--full .mineru-page{break-after:page;page-break-after:always}.mineru-document--full .mineru-page:last-child{break-after:auto;page-break-after:auto}.mineru-document .mineru-figure{break-inside:avoid;page-break-inside:avoid}.mineru-document table{display:table;overflow:visible}.mineru-document pre{overflow:visible;white-space:pre-wrap;word-break:break-word}}\ No newline at end of filediff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pyindex ecce91da..162133bb 100644--- a/tests/unittest/test_html_render.py+++ b/tests/unittest/test_html_render.py@@ -60,6 +60,34 @@ def _list(index: int, *items: str, sub_type: str | None = None) -> ListBlock:)+def _mermaid_fence(source: str, *, language: str = "mermaid") -> str:+ """用标准三反引号构造 diagram fence,避免测试字符串散落围栏细节。"""+ fence = chr(96) * 3+ return f"{fence}{language}\n{source}\n{fence}"+++def _flowchart(content: str, *, with_raster: bool = True) -> ImageBlock:+ """构造带可选 raster 回退的 flowchart 图片块。"""+ body: dict[str, object] = {+ "type": "image_body",+ "index": 0,+ "content": content,+ }+ if with_raster:+ body["image_base64"] = _PNG_URI+ return ImageBlock.model_validate(+ {+ "type": "image",+ "index": 0,+ "sub_type": "flowchart",+ "content": [+ body,+ {"type": "image_caption", "index": 1, "content": "Flowchart caption"},+ ],+ }+ )++def test_public_contract_fragment_standalone_title_and_input_immutability() -> None:"""验证严格公共参数、双输出形态、标题回退和输入无副作用。"""middle = _middle(@@ -155,6 +183,183 @@ def test_inline_html_escapes_plain_text_and_renders_styles_links_and_math() -> Nassert "packages: {'[-]': ['require']}" in result+def test_plain_text_autolinks_mpe_style_urls_domains_and_email() -> None:+ """验证显式 URL、www、裸域名、邮箱、括号和 CJK 句读按 MPE 风格转成链接。"""+ content = (+ "See https://example.com/a_(b), www.example.org/path?x=1, "+ "example.net/docs。Email [email protected];"+ "local http://127.0.0.1:8080/a. "+ "pair https://one.example/ahttps://two.example/b"+ )+ soup = BeautifulSoup(+ render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))), standalone=False),+ "html.parser",+ )++ links = soup.select(".mineru-text a")+ assert [link["href"] for link in links] == [+ "https://example.com/a_%28b%29",+ "https://www.example.org/path?x=1",+ "https://example.net/docs",+ "mailto:[email protected]",+ "http://127.0.0.1:8080/a",+ "https://one.example/a",+ "https://two.example/b",+ ]+ assert [link.get_text() for link in links] == [+ "https://example.com/a_(b)",+ "www.example.org/path?x=1",+ "example.net/docs",+ "[email protected]",+ "http://127.0.0.1:8080/a",+ "https://one.example/a",+ "https://two.example/b",+ ]+ assert "docs。Email" in soup.select_one(".mineru-text").get_text()+++ "tld",+ [+ "ai",+ "app",+ "au",+ "biz",+ "br",+ "ca",+ "cloud",+ "cn",+ "com",+ "de",+ "dev",+ "edu",+ "eu",+ "fr",+ "gov",+ "hk",+ "in",+ "info",+ "io",+ "jp",+ "kr",+ "net",+ "nl",+ "nz",+ "online",+ "org",+ "ru",+ "sg",+ "shop",+ "site",+ "store",+ "tech",+ "tw",+ "uk",+ "xyz",+ ],+)+def test_common_engineering_bare_domain_suffixes_linkify(tld: str) -> None:+ """验证 B 工程常用集中的裸域名后缀全部保持可链接。"""+ content = f"Project.Example.{tld}/docs?x=1#intro"+ soup = BeautifulSoup(+ render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))), standalone=False),+ "html.parser",+ )++ link = soup.select_one(".mineru-text a")+ assert link["href"] == f"https://Project.Example.{tld}/docs?x=1#intro"+ assert link.get_text() == content+++ "content",+ [+ "machine.Aborted",+ "HostID.lic",+ "requirements.txt",+ "600104.SH",+ "000868.SZ",+ "libcudart.so",+ "TABLEFORMER.md",+ "cs.CL",+ "TSLA.US",+ "A.Balakrishnan",+ "R.Kohli",+ ],+)+def test_non_common_bare_domain_suffixes_remain_plain_text(content: str) -> None:+ """验证文件名、股票代码、作者姓名和非白名单后缀不再误生成链接。"""+ soup = BeautifulSoup(+ render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))), standalone=False),+ "html.parser",+ )++ assert soup.select_one(".mineru-text a") is None+ assert soup.select_one(".mineru-text").get_text() == content+++def test_strong_link_syntax_bypasses_bare_domain_suffix_allowlist() -> None:+ """验证显式 HTTP、www 和邮箱不受裸域名 B 白名单限制。"""+ content = "https://example.ch www.example.ch [email protected] https://machine.Aborted"+ soup = BeautifulSoup(+ render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))), standalone=False),+ "html.parser",+ )++ assert [link["href"] for link in soup.select(".mineru-text a")] == [+ "https://example.ch",+ "https://www.example.ch",+ "mailto:[email protected]",+ "https://machine.Aborted",+ ]+++def test_autolink_excludes_existing_links_code_math_algorithm_and_raw_html() -> None:+ """验证 linkify 不嵌套显式链接,也不进入危险协议、代码、公式、算法和 raw HTML。"""+ text = TextBlock(+ type="text",+ index=0,+ content=(+ "ftp://bad.example.com /relative.example.com 1.2.3.4 "+ "javascript:evil.example.com data:text/html,data.example.com "+ "[email protected] "+ "<hyperlink>example.com<url>https://target.test</url></hyperlink> "+ "<eq>math.example.com</eq>"+ ),+ )+ code = CodeBlock(+ type="code",+ index=1,+ sub_type="code",+ guess_lang="txt",+ content=[CodeBodyBlock(type="code_body", index=1, content="https://code.example.com")],+ )+ algorithm = CodeBlock(+ type="code",+ index=2,+ sub_type="algorithm",+ content=[CodeBodyBlock(type="code_body", index=2, content="visit algorithm.example.com")],+ )+ raw_html = ChartBlock(+ type="chart",+ index=3,+ content=[ChartBodyBlock(type="chart_body", index=3, content="<p>raw.example.com</p>")],+ )+ soup = BeautifulSoup(+ render_html(_middle(_page(0, text, code, algorithm, raw_html)), standalone=False),+ "html.parser",+ )++ links = soup.select("a")+ assert len(links) == 1+ assert links[0]["href"] == "https://target.test"+ assert links[0].get_text() == "example.com"+ assert soup.select_one(".mineru-math").get_text() == r"\(math.example.com\)"+ assert soup.select_one(".mineru-code").get_text() == "https://code.example.com"+ assert soup.select_one(".mineru-algorithm").get_text() == "visit algorithm.example.com"+ assert soup.select_one(".mineru-figure--chart p").get_text() == "raw.example.com"++def test_formula_body_closing_delimiters_are_neutralized_before_mathjax_scanning() -> None:"""验证公式体内的结束定界符改写为等价 TeX,不会提前闭合 carrier。"""middle = _middle(@@ -340,6 +545,71 @@ def test_visual_child_order_image_details_and_asset_precedence() -> None:assert len(soup.select(".mineru-caption")) == 2+def test_mermaid_flowchart_uses_live_canvas_raster_fallback_and_safe_config() -> None:+ """验证受限 Mermaid 源生成 canvas,并保留 raster、源码和固定安全运行时。"""+ source_text = '%% comment\ngraph LR\n A["<script>alert(1)</script>"] --> B'+ middle = _middle(_page(0, _flowchart(_mermaid_fence(source_text))))+ fragment = render_html(middle, standalone=False)+ standalone = render_html(middle)+ soup = BeautifulSoup(fragment, "html.parser")++ host = soup.select_one(".mineru-flowchart")+ assert host["data-mermaid-state"] == "pending"+ assert "mineru-flowchart--has-raster" in host["class"]+ assert host.select_one('.mineru-flowchart-canvas[role="img"]') is not None+ assert host.select_one(".mineru-flowchart-fallback")["src"].startswith("data:image/png")+ details = host.find_next_sibling("details")+ assert "open" not in details.attrs+ assert details.select_one(".mineru-flowchart-source code").get_text() == source_text+ assert soup.find("script") is None+ assert "mermaid@" not in fragment+ assert "[email protected]/dist/mermaid.min.js" in standalone+ assert "sha384-aBQXj4hK6Jm05i7aQAsUV3bLdSUrHX1BGYfMB0166TtWt/RRaw+h0Eelme9OCOvy" in standalone+ assert "securityLevel: 'strict'" in standalone+ assert "suppressErrorRendering: true" in standalone+ assert "maxTextSize: 50000" in standalone and "maxEdges: 500" in standalone+ assert "flowchart: {htmlLabels: false, useMaxWidth: true}" in standalone+ assert "bindFunctions" not in standalone+++def test_mermaid_flowchart_without_raster_opens_source_fallback() -> None:+ """验证无 raster 的有效 flowchart 默认展开源码,等待或替代浏览器渲染。"""+ soup = BeautifulSoup(+ render_html(+ _middle(_page(0, _flowchart(_mermaid_fence("flowchart TD\n A --> B"), with_raster=False))),+ standalone=False,+ ),+ "html.parser",+ )++ host = soup.select_one(".mineru-flowchart")+ assert "mineru-flowchart--has-raster" not in host.get("class", [])+ assert host.select_one("img") is None+ assert "open" in host.find_next_sibling("details").attrs+++ "content",+ [+ _mermaid_fence("sequenceDiagram\n A->>B: example.com"),+ _mermaid_fence('%%{init: {"securityLevel": "loose"}}%%\ngraph LR\n A --> B'),+ _mermaid_fence("---\ntheme: dark\n---\ngraph LR\n A --> B"),+ _mermaid_fence("graph LR\n A --> B", language="python"),+ _mermaid_fence(f"graph LR\n A[{'x' * 50_001}]"),+ ],+)+def test_invalid_or_out_of_scope_mermaid_keeps_existing_image_path(content: str) -> None:+ """验证非流程图、配置注入、错误 fence 和超限源码不触发 Mermaid 依赖。"""+ rendered = render_html(_middle(_page(0, _flowchart(content))))+ soup = BeautifulSoup(rendered, "html.parser")++ assert soup.select_one(".mineru-flowchart") is None+ assert soup.select_one(".mineru-image") is not None+ assert soup.select_one(".mineru-details") is not None+ assert soup.select_one(".mineru-details a") is None+ assert "mermaid@" not in rendered++def test_table_keeps_safe_html_and_spatial_or_image_fallbacks() -> None:"""验证原生表格、公式、危险属性清理、空间文本和不可用表格图片回退。"""html_table = TableBlock(@@ -599,6 +869,6 @@ def test_empty_document_and_equation_image_do_not_load_external_scripts() -> Nonimage_equation = render_html(_middle(_page(0, EquationBlock(type="equation", index=0, content="", image_base64=_PNG_URI))))assert '<article class="mineru-document mineru-document--default">\n\n</article>' in empty- assert "mathjax@" not in empty and "prismjs@" not in empty- assert "mathjax@" not in image_equation and "prismjs@" not in image_equation+ assert "mathjax@" not in empty and "prismjs@" not in empty and "mermaid@" not in empty+ assert "mathjax@" not in image_equation and "prismjs@" not in image_equation and "mermaid@" not in image_equationassert "data:image/png" in image_equation