merman-core 0.8.0-alpha.3

Mermaid parser + semantic model (headless; parity-focused).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::{
    EditorSemanticFacts, Error, MermaidConfig, ParseMetadata, Result,
    baseline::BaselineRegistryProfile, editor::SourceSpan,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub const BLOCK_WIDTH_WARNING_RULE_ID: &str = "merman.block.width_exceeds_columns";
pub const FLOWCHART_EXPLICIT_DIRECTION_WARNING_RULE_ID: &str =
    "merman.authoring.flowchart.explicit_direction";
pub const FLOWCHART_UNKNOWN_STYLE_TARGET_WARNING_RULE_ID: &str =
    "merman.semantic.flowchart.unknown_style_target";
pub const GIT_GRAPH_DUPLICATE_COMMIT_WARNING_RULE_ID: &str = "merman.git_graph.duplicate_commit_id";

/// Shared warning fact emitted by diagram families for analysis and lint consumers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagramWarningFact {
    pub rule_id: String,
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<SourceSpan>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fix_span: Option<SourceSpan>,
}

impl DiagramWarningFact {
    pub fn new(rule_id: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            rule_id: rule_id.into(),
            message: message.into(),
            span: None,
            fix_span: None,
        }
    }

    pub fn with_span(mut self, span: SourceSpan) -> Self {
        self.span = Some(span);
        self
    }

    pub fn with_fix_span(mut self, span: SourceSpan) -> Self {
        self.fix_span = Some(span);
        self
    }
}

pub(crate) fn legacy_warning_messages(facts: &[DiagramWarningFact]) -> Vec<String> {
    facts.iter().map(|fact| fact.message.clone()).collect()
}

/// Parser used by the semantic JSON path for one Mermaid diagram family.
pub type DiagramSemanticParser = fn(code: &str, meta: &ParseMetadata) -> Result<Value>;

/// Parser used by the typed render-model path for one Mermaid diagram family.
pub type RenderSemanticParser = fn(code: &str, meta: &ParseMetadata) -> Result<RenderSemanticModel>;

/// Registry for semantic JSON parsers keyed by Mermaid diagram type id.
#[derive(Debug, Clone)]
pub struct DiagramRegistry {
    parsers: std::collections::HashMap<&'static str, DiagramSemanticParser>,
    profile: BaselineRegistryProfile,
}

impl Default for DiagramRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl DiagramRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::with_profile(BaselineRegistryProfile::Full)
    }

    fn with_profile(profile: BaselineRegistryProfile) -> Self {
        Self {
            parsers: std::collections::HashMap::new(),
            profile,
        }
    }

    /// Registers or replaces the parser for a Mermaid diagram type id.
    pub fn insert(&mut self, diagram_type: &'static str, parser: DiagramSemanticParser) {
        self.parsers.insert(diagram_type, parser);
    }

    /// Looks up a parser by Mermaid diagram type id.
    pub fn get(&self, diagram_type: &str) -> Option<DiagramSemanticParser> {
        self.parsers.get(diagram_type).copied()
    }

    /// Builds the full semantic parser registry for the repository's pinned Mermaid baseline.
    pub fn pinned_mermaid_baseline_full() -> Self {
        let mut reg = Self::with_profile(BaselineRegistryProfile::Full);
        for fact in crate::family::semantic_parser_facts(BaselineRegistryProfile::Full) {
            reg.insert(fact.id, fact.parser);
        }

        reg
    }

    /// Builds the tiny semantic parser registry for the repository's pinned Mermaid baseline.
    pub fn pinned_mermaid_baseline_tiny() -> Self {
        let mut reg = Self::with_profile(BaselineRegistryProfile::Tiny);
        for fact in crate::family::semantic_parser_facts(BaselineRegistryProfile::Tiny) {
            reg.insert(fact.id, fact.parser);
        }

        reg
    }

    /// Builds the semantic parser registry selected by this crate's feature flags.
    #[cfg(feature = "full")]
    pub fn for_pinned_mermaid_baseline() -> Self {
        Self::pinned_mermaid_baseline_full()
    }

    /// Builds the semantic parser registry selected by this crate's feature flags.
    #[cfg(not(feature = "full"))]
    pub fn for_pinned_mermaid_baseline() -> Self {
        Self::pinned_mermaid_baseline_tiny()
    }

    pub(crate) fn profile(&self) -> BaselineRegistryProfile {
        self.profile
    }

    #[cfg(test)]
    pub(crate) fn parser_ids(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.parsers.keys().copied()
    }
}

/// Parsed diagram metadata plus the Mermaid-compatible semantic JSON model.
#[derive(Debug, Clone)]
pub struct ParsedDiagram {
    /// Diagram type and effective configuration extracted during preprocessing.
    pub meta: ParseMetadata,
    /// Semantic JSON model matching Mermaid's parser/database output shape where possible.
    pub model: Value,
}

/// Parser-backed editor facts produced alongside a successful semantic JSON parse.
#[derive(Debug)]
pub enum ParsedEditorFacts {
    Available(EditorSemanticFacts),
    Unavailable,
    Error(Error),
}

/// Parsed semantic JSON plus editor-facing semantic facts from the same preprocessing pass.
#[derive(Debug)]
pub struct ParsedDiagramWithEditorFacts {
    pub diagram: ParsedDiagram,
    pub editor_facts: ParsedEditorFacts,
}

/// Typed semantic model used by the headless renderer.
///
/// Most public callers should use [`ParsedDiagram`] when they need JSON output. This enum is for
/// render paths that benefit from typed data and avoiding a JSON round trip.
#[derive(Debug, Clone)]
pub enum RenderSemanticModel {
    Json(Value),
    Mindmap(crate::diagrams::mindmap::MindmapDiagramRenderModel),
    State(crate::diagrams::state::StateDiagramRenderModel),
    Sequence(crate::diagrams::sequence::SequenceDiagramRenderModel),
    Flowchart(crate::diagrams::flowchart::FlowchartV2Model),
    Architecture(crate::diagrams::architecture::ArchitectureDiagramRenderModel),
    Class(crate::models::class_diagram::ClassDiagram),
    C4(crate::diagrams::c4::C4DiagramRenderModel),
    Kanban(crate::diagrams::kanban::KanbanDiagramRenderModel),
    Gantt(crate::diagrams::gantt::GanttDiagramRenderModel),
    Pie(crate::diagrams::pie::PieDiagramRenderModel),
    Packet(crate::diagrams::packet::PacketDiagramRenderModel),
    Timeline(crate::diagrams::timeline::TimelineDiagramRenderModel),
    Journey(crate::diagrams::journey::JourneyDiagramRenderModel),
    Requirement(crate::diagrams::requirement::RequirementDiagramRenderModel),
    Sankey(crate::diagrams::sankey::SankeyDiagramRenderModel),
    Radar(crate::diagrams::radar::RadarDiagramRenderModel),
    Info(crate::diagrams::info::InfoDiagramRenderModel),
    Treemap(crate::diagrams::treemap::TreemapDiagramRenderModel),
    Block(crate::diagrams::block::BlockDiagramRenderModel),
    Er(crate::diagrams::er::ErDiagramRenderModel),
    QuadrantChart(crate::diagrams::quadrant_chart::QuadrantChartRenderModel),
    XyChart(crate::diagrams::xychart::XyChartDiagramRenderModel),
    GitGraph(crate::diagrams::git_graph::GitGraphRenderModel),
    TreeView(crate::diagrams::tree_view::TreeViewDiagramRenderModel),
    Ishikawa(crate::diagrams::ishikawa::IshikawaDiagramRenderModel),
    EventModeling(crate::diagrams::eventmodeling::EventModelingDiagramRenderModel),
    Venn(crate::diagrams::venn::VennDiagramRenderModel),
}

impl RenderSemanticModel {
    /// Applies Mermaid common DB sanitization to family-owned typed fields.
    pub(crate) fn sanitize_common_db_fields(&mut self, config: &MermaidConfig) {
        match self {
            Self::Json(v) => crate::common_db::apply_common_db_sanitization(v, config),
            Self::Mindmap(_) => {}
            Self::State(v) => v.sanitize_common_db_fields(config),
            Self::Sequence(v) => v.sanitize_common_db_fields(config),
            Self::Flowchart(v) => v.sanitize_common_db_fields(config),
            Self::Architecture(v) => v.sanitize_common_db_fields(config),
            Self::Class(v) => v.sanitize_common_db_fields(config),
            Self::C4(v) => v.sanitize_common_db_fields(config),
            Self::Kanban(_) => {}
            Self::Gantt(v) => v.sanitize_common_db_fields(config),
            Self::Pie(v) => v.sanitize_common_db_fields(config),
            Self::Packet(v) => v.sanitize_common_db_fields(config),
            Self::Timeline(v) => v.sanitize_common_db_fields(config),
            Self::Journey(v) => v.sanitize_common_db_fields(config),
            Self::Requirement(v) => v.sanitize_common_db_fields(config),
            Self::Sankey(_) => {}
            Self::Radar(v) => v.sanitize_common_db_fields(config),
            Self::Info(_) => {}
            Self::Treemap(v) => v.sanitize_common_db_fields(config),
            Self::Block(_) => {}
            Self::Er(v) => v.sanitize_common_db_fields(config),
            Self::QuadrantChart(v) => v.sanitize_common_db_fields(config),
            Self::XyChart(v) => v.sanitize_common_db_fields(config),
            Self::GitGraph(v) => v.sanitize_common_db_fields(config),
            Self::TreeView(v) => v.sanitize_common_db_fields(config),
            Self::Ishikawa(v) => v.sanitize_common_db_fields(config),
            Self::EventModeling(v) => v.sanitize_common_db_fields(config),
            Self::Venn(v) => v.sanitize_common_db_fields(config),
        }
    }

    pub(crate) fn remap_warning_fact_spans(
        &mut self,
        mut remap: impl FnMut(&mut DiagramWarningFact),
    ) {
        match self {
            Self::Json(v) => Self::remap_json_warning_fact_spans(v, &mut remap),
            Self::Flowchart(v) => Self::remap_warning_fact_slice(&mut v.warning_facts, &mut remap),
            Self::Block(v) => Self::remap_warning_fact_slice(&mut v.warning_facts, &mut remap),
            Self::GitGraph(v) => Self::remap_warning_fact_slice(&mut v.warning_facts, &mut remap),
            _ => {}
        }
    }

    fn remap_warning_fact_slice(
        facts: &mut [DiagramWarningFact],
        remap: &mut impl FnMut(&mut DiagramWarningFact),
    ) {
        for fact in facts {
            remap(fact);
        }
    }

    fn remap_json_warning_fact_spans(
        model: &mut Value,
        remap: &mut impl FnMut(&mut DiagramWarningFact),
    ) {
        let Some(warning_facts_value) = model.get_mut("warningFacts") else {
            return;
        };
        let Ok(mut warning_facts) =
            serde_json::from_value::<Vec<DiagramWarningFact>>(warning_facts_value.clone())
        else {
            return;
        };

        Self::remap_warning_fact_slice(&mut warning_facts, remap);
        *warning_facts_value = serde_json::json!(warning_facts);
    }

    /// Returns a stable family label for diagnostics and timing output.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Json(_) => "json",
            Self::Mindmap(_) => "mindmap",
            Self::State(_) => "state",
            Self::Sequence(_) => "sequence",
            Self::Flowchart(_) => "flowchart",
            Self::Architecture(_) => "architecture",
            Self::Class(_) => "class",
            Self::C4(_) => "c4",
            Self::Kanban(_) => "kanban",
            Self::Gantt(_) => "gantt",
            Self::Pie(_) => "pie",
            Self::Packet(_) => "packet",
            Self::Timeline(_) => "timeline",
            Self::Journey(_) => "journey",
            Self::Requirement(_) => "requirement",
            Self::Sankey(_) => "sankey",
            Self::Radar(_) => "radar",
            Self::Info(_) => "info",
            Self::Treemap(_) => "treemap",
            Self::Block(_) => "block",
            Self::Er(_) => "er",
            Self::QuadrantChart(_) => "quadrantChart",
            Self::XyChart(_) => "xychart",
            Self::GitGraph(_) => "gitGraph",
            Self::TreeView(_) => "treeView",
            Self::Ishikawa(_) => "ishikawa",
            Self::EventModeling(_) => "eventmodeling",
            Self::Venn(_) => "venn",
        }
    }

    /// Returns whether this typed model can represent the given Mermaid diagram type id.
    pub fn supports_diagram_type(&self, diagram_type: &str) -> bool {
        match self {
            Self::Json(_) => true,
            other => {
                crate::family::render_model_kind_supports_diagram_type(other.kind(), diagram_type)
            }
        }
    }
}

/// Registry for typed render-model parsers keyed by Mermaid diagram type id.
#[derive(Debug, Clone)]
pub struct RenderDiagramRegistry {
    parsers: std::collections::HashMap<&'static str, RenderSemanticParser>,
    profile: BaselineRegistryProfile,
}

impl Default for RenderDiagramRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl RenderDiagramRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::with_profile(BaselineRegistryProfile::Full)
    }

    fn with_profile(profile: BaselineRegistryProfile) -> Self {
        Self {
            parsers: std::collections::HashMap::new(),
            profile,
        }
    }

    /// Registers or replaces the typed render parser for a Mermaid diagram type id.
    pub fn insert(&mut self, diagram_type: &'static str, parser: RenderSemanticParser) {
        self.parsers.insert(diagram_type, parser);
    }

    /// Looks up a typed render parser by Mermaid diagram type id.
    pub fn get(&self, diagram_type: &str) -> Option<RenderSemanticParser> {
        self.parsers.get(diagram_type).copied()
    }

    #[cfg(test)]
    pub(crate) fn remove(&mut self, diagram_type: &str) -> Option<RenderSemanticParser> {
        self.parsers.remove(diagram_type)
    }

    /// Builds the full typed render parser registry for the repository's pinned Mermaid baseline.
    pub fn pinned_mermaid_baseline_full() -> Self {
        let mut reg = Self::with_profile(BaselineRegistryProfile::Full);
        for fact in crate::family::render_parser_facts(BaselineRegistryProfile::Full) {
            reg.insert(fact.id, fact.parser);
        }

        reg
    }

    /// Builds the tiny typed render parser registry for the repository's pinned Mermaid baseline.
    pub fn pinned_mermaid_baseline_tiny() -> Self {
        let mut reg = Self::with_profile(BaselineRegistryProfile::Tiny);
        for fact in crate::family::render_parser_facts(BaselineRegistryProfile::Tiny) {
            reg.insert(fact.id, fact.parser);
        }

        reg
    }

    /// Builds the typed render parser registry selected by this crate's feature flags.
    #[cfg(feature = "full")]
    pub fn for_pinned_mermaid_baseline() -> Self {
        Self::pinned_mermaid_baseline_full()
    }

    /// Builds the typed render parser registry selected by this crate's feature flags.
    #[cfg(not(feature = "full"))]
    pub fn for_pinned_mermaid_baseline() -> Self {
        Self::pinned_mermaid_baseline_tiny()
    }

    pub(crate) fn profile(&self) -> BaselineRegistryProfile {
        self.profile
    }

    #[cfg(test)]
    pub(crate) fn parser_ids(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.parsers.keys().copied()
    }
}

/// Parsed diagram metadata plus a typed render model.
#[derive(Debug, Clone)]
pub struct ParsedDiagramRender {
    /// Diagram type and effective configuration extracted during preprocessing.
    pub meta: ParseMetadata,
    /// Typed model consumed by layout and SVG renderers.
    pub model: RenderSemanticModel,
}

/// Parses with a registry entry or reports an unsupported Mermaid diagram type.
pub fn parse_or_unsupported(
    registry: &DiagramRegistry,
    diagram_type: &str,
    code: &str,
    meta: &ParseMetadata,
) -> Result<Value> {
    let Some(parser) = registry.get(diagram_type) else {
        return Err(Error::UnsupportedDiagram {
            diagram_type: diagram_type.to_string(),
        });
    };
    parser(code, meta)
}