MCPcopy Create free account
hub / github.com/FSoft-AI4Code/CodeWiki / validate_single_diagram

Function validate_single_diagram

codewiki/src/be/utils.py:228–273  ·  view source on GitHub ↗

Validate a single mermaid diagram. Args: diagram_content: The mermaid diagram content diagram_num: Diagram number for error reporting line_start: Starting line number in the file Returns: Error message if invalid, empty string if valid

(diagram_content: str, diagram_num: int, line_start: int)

Source from the content-addressed store, hash-verified

226 return match.group(0).strip()
227 # Unknown error from the JS parser — fall back rather than surface it.
228 return None
229 finally:
230 sys.stderr.close()
231 sys.stderr = old_stderr
232
233
234def _remote_result(status_code: int, body: str) -> DiagramResult:
235 if 200 <= status_code < 300:
236 return DiagramResult("valid")
237 if status_code in (400, 422) and is_parse_error(body):
238 # Newer mermaid-py truncates str(MermaidError), losing the final
239 # lexer token. Use the response body for actionable diagnostics.
240 return DiagramResult("invalid", body)
241 return DiagramResult("unavailable", f"HTTP {status_code}: {body[:500]}")
242
243
244def _parse_via_mermaid_py(diagram_content: str) -> DiagramResult:
245 """Validate HTTP responses explicitly, including mermaid-py 0.8.0.
246
247 0.8.0 returns error responses without raising. Later versions raise
248 MermaidError; both must distinguish service failures from parse errors.
249 """
250 import mermaid as md
251
252 try:
253 diagram = md.Mermaid(diagram_content)
254 except Exception as e:
255 if isinstance(e, getattr(md, "MermaidError", ())):
256 status_code = getattr(e, "status_code", None)
257 if isinstance(status_code, int):
258 return _remote_result(status_code, getattr(e, "response_text", str(e)))
259 return DiagramResult("unavailable", str(e))
260 for name in ("svg_response", "img_response"):
261 response = getattr(diagram, name, None)
262 status_code = getattr(response, "status_code", None)
263 if not isinstance(status_code, int):
264 return DiagramResult("unavailable", "renderer returned no HTTP response")
265 result = _remote_result(status_code, response.text)
266 if result.status != "valid":
267 return result
268 return DiagramResult("valid")
269
270
271def _run_in_daemon_thread(fn, *args) -> "asyncio.Future":
272 """Run fn in a daemon thread and return an awaitable for its result.
273
274 Unlike asyncio.to_thread, a thread left hanging after wait_for times out
275 (mermaid-py&#x27;s requests.get has no timeout) does not block interpreter exit.
276 """

Callers 1

Calls 3

_try_pythonmonkey_parseFunction · 0.85
debugMethod · 0.80
warningMethod · 0.80

Tested by

no test coverage detected