# How to Import and Convert Mermaid Diagrams to the cathrynlavery/diagram-design Format

> Easily import and convert Mermaid diagrams to the cathrynlavery/diagram-design format. Use import-mermaid command and mermaid_extract.py for seamless conversion to HTML SVG or PNG.

- Repository: [Cathryn Lavery/diagram-design](https://github.com/cathrynlavery/diagram-design)
- Tags: how-to-guide
- Published: 2026-08-18

---

**Use the `import-mermaid` command to parse Mermaid source files through [`mermaid_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/mermaid_extract.py), which produces a normalized JSON intermediate representation that the diagram-design rendering pipeline converts to HTML, SVG, or PNG.**

The `cathrynlavery/diagram-design` repository provides a dedicated skill for converting Mermaid diagrams into its internal **intermediate representation (IR)**. This conversion pipeline handles multiple input formats, enforces strict safety boundaries, and outputs publication-ready diagrams through a configurable rendering stage.

## Understanding the Conversion Pipeline

The import process follows three tightly-controlled stages defined in [`skills/diagram-design/SKILL.md`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/SKILL.md):

1. **Locate and invoke the skill** via the `import-mermaid` command
2. **Extract normalized IR** using [`skills/diagram-design/scripts/mermaid_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/scripts/mermaid_extract.py)
3. **Render to final format** through the output-spec pipeline

The extractor never evaluates JavaScript, fetches URLs, or follows click handlers—creating a clean trust boundary for untrusted Mermaid sources.

## Supported Input Formats

The [`mermaid_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/mermaid_extract.py) parser accepts multiple file types through its `load_blocks()` function:

| Extension | Handling |
|-----------|----------|
| `.mmd` | Direct Mermaid source |
| `.mermaid` | Direct Mermaid source |
| `.md` / `.markdown` | Extracts fenced ` ```mermaid ` blocks |

For Markdown files containing multiple diagrams, use the `--diagram` flag to select specific blocks by index.

## Core Extraction Process

### Grammar Detection and Normalization

The `_kind_and_direction()` function in `mermaid_extract.py` identifies diagram types:

- `flowchart`
- `sequenceDiagram`
- `stateDiagram-v2`
- `erDiagram`

Unsupported kinds trigger exit code 2 with a descriptive error message.

### Node and Edge Parsing

| Component | Function | Purpose |
|-----------|----------|---------|
| Nodes | `_parse_node_expression()` | Normalizes labels, strips class suffixes, maps shape delimiters to canonical families (`rect`, `circle`, `rhombus`, etc.) |
| Shapes | `classify_shape()` | Converts Mermaid syntax to internal shape vocabulary |
| Edges | `_edge_operators()`, `_operator_style()` | Collapses variations (`--`, `-.`, `==`, `x`, `o`) into standardized styles (`solid`, `dashed`, `thick`) and arrowheads (`arrow`, `cross`, `circle`, `async`) |

### Safety Sanitization

The `_discard_nonsemantic()` function enforces content security:

- Escapes HTML-like markup in labels via `html.unescape`
- Counts and discards click handlers (`click ...`)
- Removes style directives (`style ...`)
- Strips YAML front-matter via `_frontmatter_end()`

## Available CLI Flags

All flags are documented in `commands/import-mermaid.md` and `prompts/import-mermaid.md`:

| Flag | Values | Effect |
|------|--------|--------|
| `--format` | `html`, `svg`, `png`, `html+png` | Final output container |
| `--size` | `doc-inline`, `slide-16x9`, `social-og`, etc. | SVG viewBox and scaling from `output-spec.md` |
| `--detail` | `faithful`, `balanced`, `simplified` | Node/edge retention with budget limits (≤9 nodes, ≤12 edges) |
| `--audience` | `engineer`, `mixed`, `executive` | Caption wording adjustment |
| `--type` | 27 diagram-type tokens | Force type instead of grammar inference |
| `--diagram` | `0`, `1`, ... or `all` | Select specific Mermaid block from multi-block files |
| `--variant` | `light`, `dark`, `full` | Editorial skin template selection |
| `--output` | path | Base path for generated files |

## Command Examples

### Basic HTML Conversion

```bash
diagram-design import-mermaid path/to/diagram.mmd --format=html --size=doc-inline

```

This reads `diagram.mmd`, runs `mermaid_extract.py`, and produces `diagram.html` with the default light theme.

### Multi-Block Markdown Selection

```bash

# Render only the second Mermaid block from a README

diagram-design import-mermaid docs/README.md --diagram=1 --format=svg

```

The `--diagram=1` flag (0-indexed) isolates the specific block, outputting `README.svg`.

### JSON IR Export for Custom Pipelines

```bash
diagram-design import-mermaid flowchart.mmd --json > flowchart.json

```

The resulting JSON structure:

```json
{
  "source": "flowchart.mmd",
  "diagrams_total": 1,
  "diagrams": [
    {
      "index": 0,
      "kind": "flowchart",
      "source_line": 1,
      "direction": "LR",
      "analysis": {},
      "discarded": {
        "style_directives": 0,
        "click_handlers": 0
      },
      "nodes": [],
      "edges": []
    }
  ]
}

```

Downstream tools can modify this IR before feeding it to alternative renderers.

## Programmatic Python Usage

Import `mermaid_extract.py` directly for custom workflows:

```python
from pathlib import Path
from skills.diagram_design.scripts.mermaid_extract import load_blocks, parse_block, digest

source_path = Path("examples/flowchart.mmd")

# Extract all Mermaid blocks from file

blocks = load_blocks(source_path)  # → list[SourceBlock]

# Parse first block into Diagram dataclass

diagram = parse_block(blocks[0])   # → Diagram object

# Generate human-readable summary

markdown = digest(
    source_path,
    [diagram],
    [diagram],
    max_rows=20
)
print(markdown)

```

This reproduces the CLI's internal logic while exposing the full `Diagram` dataclass for custom analysis.

## Verification and Testing

The `scripts/verify-mermaid-import.py` harness validates:

- Shape classification accuracy
- Edge vocabulary completeness
- Front-matter handling
- Multi-block selection
- Adversarial input resistance
- Resource limit enforcement

Run this to ensure your Mermaid files conform to supported patterns before production import.

## Key Source Files

| File | Purpose |
|------|---------|
| `skills/diagram-design/scripts/mermaid_extract.py` | Core parser producing normalized IR |
| `commands/import-mermaid.md` | CLI specification and flag defaults |
| `prompts/import-mermaid.md` | Assistant-facing documentation |
| `skills/diagram-design/SKILL.md` | High-level skill description |
| `skills/diagram-design/references/output-spec.md` | Size presets and format pipelines |
| `scripts/verify-mermaid-import.py` | Test harness for extractor validation |
| `scripts/fixtures/*.mmd` | Example files for testing |

## Summary

- **Use `import-mermaid`** as the primary entry point for Mermaid-to-diagram-design conversion
- **Trust the extractor**: `mermaid_extract.py` sanitizes inputs, never executing JavaScript or external resources
- **Control output** through `--format`, `--size`, `--detail`, and `--variant` flags defined in `output-spec.md`
- **Select specific diagrams** from multi-block files with `--diagram` indexing
- **Access raw IR** via `--json` for custom processing pipelines
- **Validate inputs** using `verify-mermaid-import.py` before production use

## Frequently Asked Questions

### What Mermaid diagram types are supported for import?

The `mermaid_extract.py` parser supports `flowchart`, `sequenceDiagram`, `stateDiagram-v2`, and `erDiagram` through its `_kind_and_direction()` function. Unsupported types trigger a clear exit-2 error. The 27 internal diagram-type tokens in `--type` provide additional classification for the rendering stage but do not extend grammar parsing.

### How does the converter handle unsafe Mermaid features?

The `_discard_nonsemantic()` function in `mermaid_extract.py` explicitly removes click handlers, style directives, and HTML markup. The extractor never evaluates JavaScript, fetches remote URLs, or processes external resources—creating a hardened boundary suitable for untrusted diagram sources.

### Can I extract multiple diagrams from a single Markdown file?

Yes. The `load_blocks()` function detects all fenced ` ```mermaid ` blocks. Use `--diagram=0` for the first block, `--diagram=1` for the second, or process them sequentially in a script. The `--diagram=all` flag renders every discovered block to separate output files.

### What are the node and edge limits for diagram conversion?

The `--detail` parameter enforces budget constraints: simplified mode targets ≤9 drawable nodes and ≤12 edges. Diagrams exceeding these limits are automatically split into overview-plus-detail files. These defaults balance readability with information density across `doc-inline`, `slide-16x9`, and `social-og` size presets.