Attempt to parse via PythonMonkey/mermaid-parser-py. Returns the extracted parse-error message, "" on success, or None when PythonMonkey itself is unusable (broken JS event loop binding on Python 3.13+) so the caller can fall back to mermaid-py.
(diagram_content: str)
| 159 | def extract_mermaid_blocks(content: str) -> List[Tuple[int, str]]: |
| 160 | """Return opening-fence line numbers and bodies (legacy read-only API).""" |
| 161 | return [ |
| 162 | (block.line, block.content.removesuffix("\n").removesuffix("\r")) |
| 163 | for block in mermaid_blocks(content) |
| 164 | ] |
| 165 | |
| 166 | |
| 167 | # PythonMonkey 1.3.1 only supports Python 3.8–3.11. On 3.12+ it still imports, |
| 168 | # but its SpiderMonkey cleanup runs on the wrong thread during _Py_Finalize and |
| 169 | # segfaults at interpreter shutdown (macOS crash dialog after a successful run). |
| 170 | # Skip it proactively so SpiderMonkey is never loaded into the process. |
| 171 | _PYTHONMONKEY_BROKEN = sys.version_info >= (3, 12) |
| 172 | |
| 173 | # mermaid-py validates diagrams by sending them to a remote rendering service |
| 174 | # (https://mermaid.ink by default, overridable via the MERMAID_INK_SERVER env |
| 175 | # var understood by mermaid-py itself) rather than spawning a local Node.js |
| 176 | # subprocess. Note that this sends diagram content to that third-party service. |
| 177 | # It can still hang or fail when the service is unreachable (no network egress, |
| 178 | # DNS/firewall issues, or an outage). Enabled by default; set MERMAID_VALIDATE=0 |
| 179 | # to disable. |
| 180 | _MERMAID_PY_BROKEN = os.environ.get("MERMAID_VALIDATE", "1") == "0" |
| 181 | _MERMAID_PY_PROBED = True # Skip probing — rely on env var |
| 182 | |
| 183 | |
| 184 | async def _try_pythonmonkey_parse(diagram_content: str) -> str | None: |
| 185 | """Attempt to parse via PythonMonkey/mermaid-parser-py. |
| 186 | |
| 187 | Returns the extracted parse-error message, "" on success, or None when |
| 188 | PythonMonkey itself is unusable (broken JS event loop binding on |
| 189 | Python 3.13+) so the caller can fall back to mermaid-py. |
| 190 | """ |
| 191 | global _PYTHONMONKEY_BROKEN |
| 192 | if _PYTHONMONKEY_BROKEN: |
| 193 | return None |
| 194 | |
| 195 | import os |
| 196 | |
| 197 | try: |
| 198 | from mermaid_parser.parser import parse_mermaid_py |
| 199 | except Exception: |
| 200 | _PYTHONMONKEY_BROKEN = True |
| 201 | return None |
| 202 | |
| 203 | old_stderr = sys.stderr |
| 204 | sys.stderr = open(os.devnull, "w") |
| 205 | try: |
| 206 | if ( |
| 207 | _main_loop is not None |
| 208 | and _main_loop.is_running() |
| 209 | and threading.get_ident() != _main_loop_thread_ident |
| 210 | ): |
| 211 | fut = asyncio.run_coroutine_threadsafe(parse_mermaid_py(diagram_content), _main_loop) |
| 212 | await asyncio.wrap_future(fut) |
| 213 | else: |
no outgoing calls
no test coverage detected