mermaid

package module
v0.0.0-...-6f57ffa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

mermaid-check

A pure Go parser, validator, and linter for Mermaid diagrams.

What it does

Parse, validate, and lint Mermaid diagram syntax from Go code or the command line. Works with pure Mermaid files (.mmd) and markdown files containing Mermaid code blocks.

Features:

  • Multiple diagram types in a single markdown file
  • Customisable validation rules (default and strict modes)
  • Detailed error messages with line numbers
  • Auto-detection of diagram types
  • Parentheses warnings, comment validation, header checks
  • Grouped output format for processing multiple files
  • Configurable error handling for files without diagrams

This is a new project and there are bound to be bugs, PRs welcome!

Installation

go get github.com/sammcj/mermaid-check@HEAD

Usage

Command line
# Validate a Mermaid file
mermaid-check diagram.mmd

# Validate markdown with Mermaid blocks
mermaid-check README.md

# Validate multiple files at once
mermaid-check docs/*.md diagrams/*.mmd

# Validate from stdin
cat diagram.mmd | mermaid-check

# Force markdown mode
cat content.txt | mermaid-check --format markdown

# Use strict validation rules
mermaid-check --strict diagram.mmd

# Treat markdown files with no Mermaid diagrams as errors
mermaid-check --error-on-empty docs/*.md

Flags:

  • --strict - Use strict validation rules (includes style checks)
  • --error-on-empty - Treat markdown files with no Mermaid diagrams as errors (.mmd files always error if empty)
  • --format FORMAT - Force input format: 'mermaid' or 'markdown'
  • --help - Show help message
  • --version - Show version information

Exit codes:

  • 0 - All diagrams are valid (or no diagrams found in markdown unless --error-on-empty is set)
  • 1 - Validation errors found or processing failed
Output Format

The CLI groups results by type for cleaner output when processing multiple files:

Files with no Mermaid diagrams:
  ⚠ docs/readme.md
  ⚠ docs/guide.md
  Hint: Ensure code blocks use proper markdown fences: ```mermaid

Errors:
  ✗ empty.mmd: empty .mmd file
  ✗ invalid.mmd: parse error at line 5

Validating: diagrams/flow.mmd
  flowchart (L1-L10) - ✓ Valid

Validating: docs/architecture.md
  Diagram 1 (L130-L172) flowchart: ✓ Valid
  Diagram 2 (L200-L250) sequence: ✗ 2 validation error(s):
    undefined participant: User
    missing activation close for: Server

Key features:

  • Informational messages (no diagrams in markdown) appear first in orange with ⚠ icon
  • Actual errors grouped separately in red with ✗ icon
  • Validation results shown per file with line ranges
  • Reduced repetition when processing many files
  • Color-coded output for quick visual scanning

Diagram Support

Diagram Semantic Validation
C4 elements, relationships, boundaries
Class classes, relationships, members
ER entities, attributes, relationships
Flowchart nodes, links, direction
Gantt tasks, sections, dependencies
GitGraph commits, branches, merges
Graph nodes, links, direction
Journey tasks, actors, scores
Mindmap nodes, hierarchy, shapes
Pie entries, values, labels
Quadrant points, axes, coordinates
Sankey nodes, links, values
Sequence participants, messages, notes
State states, transitions, references
Timeline periods, events, sections
XYChart series, axes, data
Library
import "github.com/sammcj/mermaid-check"

// Parse any diagram type (auto-detects)
diagram, err := mermaid.Parse(source)
if err != nil {
    // Handle error
}

// Validate with default rules
errors := mermaid.Validate(diagram, false)

// Validate with strict rules
errors := mermaid.Validate(diagram, true)

// Extract diagrams from markdown
diagrams, err := mermaid.ExtractFromMarkdown(markdownContent)

// Type-specific handling (all diagram types have full AST)
switch d := diagram.(type) {
case *ast.Flowchart:
    fmt.Println("Direction:", d.Direction)
    fmt.Println("Statements:", len(d.Statements))
case *ast.SequenceDiagram:
    fmt.Println("Participants:", len(d.Participants))
    fmt.Println("Statements:", len(d.Statements))
case *ast.ClassDiagram:
    fmt.Println("Classes:", len(d.Classes))
    fmt.Println("Relationships:", len(d.Relationships))
case *ast.StateDiagram:
    fmt.Println("States:", len(d.States))
    fmt.Println("Transitions:", len(d.Transitions))
case *ast.ERDiagram:
    fmt.Println("Entities:", len(d.Entities))
    fmt.Println("Relationships:", len(d.Relationships))
case *ast.GanttDiagram:
    fmt.Println("Tasks:", len(d.Tasks))
    fmt.Println("Sections:", len(d.Sections))
case *ast.GenericDiagram:
    // Fallback for future unsupported types
    fmt.Println("Type:", d.DiagramType)
    fmt.Println("Lines:", len(d.Lines))
}

// Parse flowchart specifically (when you need the full AST)
flowchart, err := mermaid.ParseFlowchart(source)

Validation Capabilities

21+ Mermaid diagram types have complete AST parsing with deep semantic validation:

Core Diagrams:

  • Flowchart/Graph: Full AST with nodes, links, subgraphs, direction validation
  • Sequence: Participants, messages, blocks (alt/opt/loop/par), notes, activation
  • Class: Classes, members, relationships, visibility modifiers, multiplicity
  • State: States, transitions, composite states, fork/join/choice nodes (v2 support)

Data Visualisation:

  • ER: Entities, attributes, relationships, cardinality validation
  • Gantt: Tasks, sections, dependencies, date format validation
  • Pie: Entries, values, labels
  • Journey: Tasks, sections, actors, scores
  • Timeline: Periods, events, sections

Specialised:

  • GitGraph: Commits, branches, merges, cherry-picks, tags
  • Mindmap: Hierarchical nodes, shapes, icons, levels
  • Sankey: Links, nodes, flow values
  • Quadrant: Points, axes, coordinates, quadrant positions
  • XYChart: Series, axes (categorical/numeric), data points

C4 Architecture Diagrams:

  • All 5 C4 types (Context, Container, Component, Dynamic, Deployment)
  • Elements, relationships, boundaries, tags

Validation Features:

  • Duplicate identifier detection
  • Reference validation (undefined nodes/participants/states)
  • Type checking (visibility modifiers, relationship types, directions)
  • Syntax validation for diagram-specific elements
  • Strict mode for style enforcement

Error Detection:

  • Detects escaped backticks in markdown (e.g., \``mermaidinstead of ```mermaid`)
  • Provides clear error messages with line numbers
  • Identifies missing diagrams in markdown files with helpful hints

What's Not Supported:

  • Auto-fixing or diagram transformation
  • Layout or rendering validation
  • Mermaid.js-specific rendering hints

Performance

Parsing and validation are highly efficient, suitable for real-time use:

Parser Performance (Apple M2 Max):

  • Flowchart: ~6.3μs per diagram
  • Sequence: ~6.5μs per diagram
  • Class: ~6.5μs per diagram
  • State: ~4.9μs per diagram
  • ER: ~0.4μs per diagram
  • Gantt: ~12μs per diagram
  • Large diagrams (100 nodes): ~110μs

Validator Performance:

  • Flowchart: ~220ns per diagram
  • Sequence: ~545ns per diagram
  • Class: ~189ns per diagram
  • State: ~315ns per diagram

All parsers meet the <100ms target for diagrams up to 1000 lines. Run benchmarks with go test -bench=. ./parser/ ./validator/

Commands
# Run all tests
make test

# Run specific module tests
go test ./parser/test/...
go test ./validator/test/...

# Run benchmarks
go test -bench=. ./parser/test/
go test -bench=. ./validator/test/

# Run linter
make lint

# Build binary
make build

# Generate coverage report
make coverage

Architecture

The library is organised into focused packages with clear responsibilities:

flowchart TB
    User[User / Application]:::inputOutput
    CLI[CLI<br/>cmd/mermaid-check]:::components
    API[Public API<br/>mermaid.go]:::components

    InputUtil[Input Detection<br/>internal/inpututil]:::process
    Extractor[Markdown Extractor<br/>extractor]:::process
    Parser[Parser Registry<br/>parser]:::process

    FlowParser[Flowchart Parser]:::llm
    SeqParser[Sequence Parser]:::llm
    ClassParser[Class Parser]:::llm
    StateParser[State Parser]:::llm
    OtherParsers[15+ Other Parsers]:::llm

    AST[AST Types<br/>ast]:::data

    Validator[Validator<br/>validator]:::storage

    FlowVal[Flowchart Rules]:::decision
    SeqVal[Sequence Rules]:::decision
    ClassVal[Class Rules]:::decision
    StateVal[State Rules]:::decision
    OtherVal[15+ Other Validators]:::decision

    Results[Validation Results]:::inputOutput

    User --> CLI
    User --> API
    CLI --> InputUtil
    API --> InputUtil

    InputUtil -->|.mmd file| Parser
    InputUtil -->|.md file| Extractor
    Extractor -->|Mermaid blocks| Parser

    Parser --> FlowParser
    Parser --> SeqParser
    Parser --> ClassParser
    Parser --> StateParser
    Parser --> OtherParsers

    FlowParser --> AST
    SeqParser --> AST
    ClassParser --> AST
    StateParser --> AST
    OtherParsers --> AST

    AST --> Validator

    Validator --> FlowVal
    Validator --> SeqVal
    Validator --> ClassVal
    Validator --> StateVal
    Validator --> OtherVal

    FlowVal --> Results
    SeqVal --> Results
    ClassVal --> Results
    StateVal --> Results
    OtherVal --> Results

    Results --> User

    classDef inputOutput fill:#F5F5F5,stroke:#9E9E9E,color:#616161
    classDef llm fill:#E8EAF6,stroke:#7986CB,color:#3F51B5
    classDef components fill:#F3E5F5,stroke:#BA68C8,color:#8E24AA
    classDef process fill:#E0F2F1,stroke:#4DB6AC,color:#00897B
    classDef stop fill:#FFEBEE,stroke:#E57373,color:#D32F2F
    classDef data fill:#E3F2FD,stroke:#64B5F6,color:#1976D2
    classDef decision fill:#FFF3E0,stroke:#FFB74D,color:#F57C00
    classDef storage fill:#F1F8E9,stroke:#9CCC65,color:#689F38
    classDef api fill:#FFF9C4,stroke:#FDD835,color:#F9A825
    classDef error fill:#FFCDD2,stroke:#EF5350,color:#C62828

Key Components:

  • CLI / Public API: Entry points for command-line and library usage
  • Input Detection: Auto-detects file types (.mmd, .md, .markdown, .mdx)
  • Markdown Extractor: Extracts Mermaid code blocks from markdown files
  • Parser Registry: Dispatches to appropriate parser based on diagram type
  • Type-Specific Parsers: 21+ parsers, each producing a complete AST
  • AST Types: Strongly-typed diagram representations implementing ast.Diagram interface
  • Validator: Routes to appropriate validator based on diagram type
  • Type-Specific Validators: Semantic validation rules for each diagram type

Development

Test Structure

Tests are organised in per-module test directories using black-box testing:

parser/test/          # Parser tests (17 files)
validator/test/       # Validator tests (18 files)
extractor/test/       # Markdown extraction tests
internal/inpututil/test/  # Input detection tests
testdata/             # Test fixtures organised by diagram type
  flowchart/         # Flowchart test diagrams
  diagrams/          # General diagram test files
  sequence/          # Sequence diagram test files

All tests use black-box testing (package X_test) to test only the public API.

Licence

  • Apache 2.0 Licensed. See LICENSE for details.

Contributing

Contributions welcome. Please ensure:

  • Linter passes with zero warnings (make lint)
  • All tests pass (make test)
  • Code coverage remains above 75%
  • British English spelling in all code and documentation
  • Tests are placed in per-module test directories using black-box testing

Documentation

Overview

Package mermaid provides parsing, validation, and linting for Mermaid diagram syntax.

This package allows you to parse Mermaid diagrams from raw text or extract them from markdown files, then validate the syntax and apply custom linting rules.

Basic Usage

Parse a raw Mermaid diagram:

diagram, err := mermaid.Parse(source)
if err != nil {
    // Handle parse error
}

Extract diagrams from markdown:

diagrams, err := mermaid.ExtractFromMarkdown(markdownContent)
for _, diagram := range diagrams {
    // Process each diagram
}

Validate with custom rules:

errors := mermaid.Validate(diagram, mermaid.NoParenthesesInLabels)

Supported Diagram Types

Currently supports flowchart and graph diagrams. Additional diagram types (sequence, ER, class, state, gantt, pie, etc.) will be added in future releases.

Index

Constants

This section is empty.

Variables

View Source
var (
	// NoParenthesesInLabels is a validation rule that checks node labels don't contain parentheses.
	NoParenthesesInLabels = &validator.NoParenthesesInLabels{}
	// ValidDirection checks if the flowchart direction is valid.
	ValidDirection = &validator.ValidDirection{}
	// NoUndefinedNodes checks that all referenced nodes are defined.
	NoUndefinedNodes = &validator.NoUndefinedNodes{}
	// NoDuplicateNodeIDs checks that node IDs are unique.
	NoDuplicateNodeIDs = &validator.NoDuplicateNodeIDs{}
)

Exported validation rules for convenience

Functions

func DefaultRules

func DefaultRules() []validator.Rule

DefaultRules returns the default set of validation rules.

func ExtractFromMarkdown

func ExtractFromMarkdown(markdown string) ([]extractor.DiagramBlock, error)

ExtractFromMarkdown extracts all Mermaid diagram blocks from markdown content.

func Parse

func Parse(source string) (ast.Diagram, error)

Parse parses a raw Mermaid diagram from a string. Returns a Diagram interface that can be a Flowchart or GenericDiagram depending on type.

func ParseFile

func ParseFile(path string) ([]ast.Diagram, error)

ParseFile parses a file containing Mermaid diagram(s). It auto-detects the file type based on extension and content: - .mmd files are parsed as raw Mermaid (unless they contain markdown code fences) - .md, .markdown, .mdx files are parsed as markdown and all Mermaid blocks are extracted - If a .mmd file contains markdown code fences, it's treated as markdown

Returns a slice of diagrams (potentially multiple for markdown files).

func ParseFlowchart

func ParseFlowchart(source string) (*ast.Flowchart, error)

ParseFlowchart parses a flowchart/graph diagram specifically. Use this if you need the full Flowchart AST.

func ParseReader

func ParseReader(r io.Reader) (ast.Diagram, error)

ParseReader parses a raw Mermaid diagram from an io.Reader. Returns a Diagram interface that can be a Flowchart or GenericDiagram depending on type.

func StrictRules

func StrictRules() []validator.Rule

StrictRules returns a strict set of validation rules including style checks.

func Validate

func Validate(diagram ast.Diagram, strict bool) []validator.ValidationError

Validate validates any diagram using the appropriate validator. Automatically detects diagram type and applies corresponding rules.

func ValidateFlowchart

func ValidateFlowchart(diagram *ast.Flowchart, rules ...validator.Rule) []validator.ValidationError

ValidateFlowchart validates a flowchart diagram using the provided rules. If no rules are provided, uses default rules.

Types

This section is empty.

Directories

Path Synopsis
Package ast defines the Abstract Syntax Tree types for all Mermaid diagram types.
Package ast defines the Abstract Syntax Tree types for all Mermaid diagram types.
cmd
mermaid-check command
Command mermaid-check provides a CLI tool for parsing, validating, and linting Mermaid diagrams.
Command mermaid-check provides a CLI tool for parsing, validating, and linting Mermaid diagrams.
Package extractor provides utilities for extracting Mermaid diagrams from various file formats.
Package extractor provides utilities for extracting Mermaid diagrams from various file formats.
internal
inpututil
Package inpututil provides utilities for detecting and processing input file types.
Package inpututil provides utilities for detecting and processing input file types.
Package parser provides parsing functionality for Mermaid diagrams.
Package parser provides parsing functionality for Mermaid diagrams.
Package validator provides validation and linting for Mermaid diagrams.
Package validator provides validation and linting for Mermaid diagrams.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL