mrk-cli 0.9.0

Render Markdown beautifully in the terminal: syntax highlighting, tables, themes, and Mermaid diagrams as images.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use mermaid_rs_renderer::{DiagramKind, Edge, Graph};

use super::DiagramError;
use super::catch::caught;
use super::{kind, text};

/// Mermaid blocks above this size are shown as source.
pub const MAX_SOURCE_BYTES: usize = 64 * 1024;
/// mermaid-text recurses once per level, and deeper subgraphs never fit a terminal anyway.
const MAX_SUBGRAPH_DEPTH: usize = 16;
/// The limits below keep the slowest diagram measured within them under the times `specs/02-security.md` rule 4 gives.
const MAX_LINKS: usize = 150;
const MAX_MESSAGES: usize = 400;
const MAX_ELEMENTS: usize = 600;
const MAX_EDGES: usize = 100;
/// mermaid-text lays class diagrams out far slower than any other kind: 40 relations took it 2.8 s.
const MAX_RELATIONS: usize = 32;
/// mermaid-text draws every row across all of a sequence's participants or a git graph's branches, each at least six
/// columns wide: more than this many never fit the widest text, 1,000 columns.
const MAX_LANES: usize = 200;
/// What a document's diagrams may cost together, in milliseconds of layout at the slowest rate measured for what
/// each one counts; a diagram that does not fit what is left shows as source.
pub const MAX_DOCUMENT_COST_MS: usize = 12_000;
/// What any diagram costs at least, its fixed work aside from the layout: at most this many diagrams fit a document.
const MIN_COST_MS: usize = 5;
/// The most diagrams a document lays out.
pub const MAX_DOCUMENT_DIAGRAMS: usize = MAX_DOCUMENT_COST_MS / MIN_COST_MS;
/// What a picture costs on top of its layout: fitting and drawing it.
const PICTURE_COST_MS: usize = 20;

/// What a diagram's layout time grows with, counted before an engine lays it out.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Load {
    /// Nodes, edges, edge labels, subgraphs, state notes, and every edge doubling another between the same two nodes,
    /// once per earlier one: what the layered layout routes around.
    Links,
    /// Participants, messages, notes and frame parts of a sequence diagram.
    Messages,
    /// Nodes, edges, subgraphs, commits, C4 shapes and relations, and chart marks, for the diagrams laid out in rows or
    /// rings.
    Elements,
    /// Edges, nodes on none and subgraphs, as the text engine is given them: `a & b --> c & d` is four.
    Edges,
    /// Relations of a class diagram, whose members cost mermaid-text little.
    Relations,
    /// Participants of a sequence diagram or branches of a git graph, the columns mermaid-text draws every row across.
    Lanes,
}

impl Load {
    pub fn limit(self) -> usize {
        match self {
            Self::Links => MAX_LINKS,
            Self::Messages => MAX_MESSAGES,
            Self::Elements => MAX_ELEMENTS,
            Self::Edges => MAX_EDGES,
            Self::Relations => MAX_RELATIONS,
            Self::Lanes => MAX_LANES,
        }
    }

    pub fn unit(self) -> &'static str {
        match self {
            Self::Links => "links",
            Self::Messages => "messages",
            Self::Elements => "elements",
            Self::Edges => "edges",
            Self::Relations => "relations",
            Self::Lanes => "participants or branches",
        }
    }

    /// The slowest layout measured for that many, in milliseconds: the layered engines slow down per unit as the
    /// diagram grows (145 links between random nodes took 3.1 s, 51 took 0.27 s), the row-by-row ones do not.
    fn cost_ms(self, count: usize) -> usize {
        match self {
            Self::Links => count * count / 7,
            Self::Edges => count * count / 8,
            Self::Relations => count * count * 7 / 4,
            Self::Messages | Self::Elements | Self::Lanes => count,
        }
    }

    fn within(self, count: usize) -> Result<usize, DiagramError> {
        if count > self.limit() { Err(DiagramError::OverBudget(self)) } else { Ok(self.cost_ms(count)) }
    }
}

/// A diagram parsed once, with what each engine's count says of it: layout time grows much faster than the source,
/// which its 64 KiB cap alone does not bound.
pub struct Diagram {
    /// mermaid-rs-renderer's graph and what it costs as a picture, or why the picture is refused.
    picture: Result<(Arc<Graph>, usize), DiagramError>,
    /// What it costs as mermaid-text's text, or why the text is refused.
    text: Result<usize, DiagramError>,
}

impl Diagram {
    /// Refuses, for both engines and before parsing, a block too large to read or whose subgraphs would overflow
    /// mermaid-text's stack.
    pub fn new(source: &str) -> Result<Self, DiagramError> {
        readable(source)?;
        let graph = parsed(source);
        let text = text_cost(source, graph.as_ref().ok());
        let picture = graph.and_then(|graph| picture_cost(&graph).map(|cost| (Arc::new(graph), cost)));
        Ok(Self { picture, text })
    }

    /// The graph to lay out as a picture, unless its count refuses one.
    pub fn picture_graph(&self) -> Result<Arc<Graph>, DiagramError> {
        self.picture.as_ref().map(|(graph, _)| Arc::clone(graph)).map_err(Clone::clone)
    }

    /// Refuses what mermaid-text would take too long to lay out: counted on mermaid-rs-renderer's graph when it parses
    /// the diagram, else on a scan of the source, since mermaid-text reads syntax mermaid-rs-renderer refuses.
    pub fn admit_text(&self) -> Result<(), DiagramError> {
        self.text.as_ref().map(|_| ()).map_err(Clone::clone)
    }

    /// What drawing it costs its document: as a picture when pictures are drawn and its count allows one, else as
    /// text; at least `MIN_COST_MS`, even when both counts refuse it, since parsing it took time.
    pub fn cost(&self, pictures: bool) -> usize {
        let picture = self.picture.as_ref().ok().filter(|_| pictures).map(|(_, cost)| cost + PICTURE_COST_MS);
        picture.or_else(|| self.text.as_ref().ok().copied()).map_or(MIN_COST_MS, |cost| cost.max(MIN_COST_MS))
    }
}

/// The diagrams of one document its budget lets through, in reading order, each distinct source counted once since
/// the cache keeps what a repeated one costs: each that fits what is left of the budget, none read once nothing can
/// fit. A block refused before parsing costs nothing and keeps its refusal.
pub struct Allowance(HashMap<String, Result<Diagram, DiagramError>>);

impl Allowance {
    pub fn new(sources: impl IntoIterator<Item = String>, pictures: bool) -> Self {
        let mut diagrams = HashMap::new();
        let mut left = MAX_DOCUMENT_COST_MS;
        let mut sources = sources.into_iter();
        while left >= MIN_COST_MS
            && let Some(source) = sources.next()
        {
            if diagrams.contains_key(&source) {
                continue;
            }
            let diagram = Diagram::new(&source);
            let cost = diagram.as_ref().map_or(0, |diagram| diagram.cost(pictures));
            let admitted = if cost <= left {
                left -= cost;
                diagram
            } else {
                Err(DiagramError::OverDocumentBudget)
            };
            diagrams.insert(source, admitted);
        }
        Self(diagrams)
    }

    pub fn admit(&self, source: &str) -> Result<&Diagram, DiagramError> {
        self.0.get(source).ok_or(DiagramError::OverDocumentBudget)?.as_ref().map_err(Clone::clone)
    }
}

fn parsed(source: &str) -> Result<Graph, DiagramError> {
    let parsed = caught(|| mermaid_rs_renderer::parse_mermaid_strict(source))?
        .map_err(|error| DiagramError::Invalid(first_line(&error.to_string())))?;
    Ok(parsed.graph)
}

fn readable(source: &str) -> Result<(), DiagramError> {
    if source.len() > MAX_SOURCE_BYTES {
        return Err(DiagramError::Oversized);
    }
    if !has_safe_subgraphs(source) {
        return Err(DiagramError::UnsafeSubgraphs);
    }
    Load::Lanes.within(scanned_lanes(source)).map(|_| ())
}

fn picture_cost(graph: &Graph) -> Result<usize, DiagramError> {
    let (load, count) = picture_load(graph);
    load.within(count)
}

/// The kinds mermaid-text draws in one pass, row after row, cost it their lanes, else only their fixed work: 64 KiB of
/// any kind without lanes took it under 30 ms.
fn text_cost(source: &str, graph: Option<&Graph>) -> Result<usize, DiagramError> {
    let load = match (text::lanes(source), graph) {
        (Some(lanes), _) => Some((Load::Lanes, lanes)),
        (None, Some(graph)) => graph_text_load(graph),
        (None, None) => scanned_text_load(source),
    };
    load.map_or(Ok(MIN_COST_MS), |(load, count)| load.within(count))
}

fn picture_load(graph: &Graph) -> (Load, usize) {
    let shapes = graph.nodes.len() + graph.edges.len() + graph.subgraphs.len();
    match graph.kind {
        DiagramKind::Flowchart
        | DiagramKind::Class
        | DiagramKind::State
        | DiagramKind::Er
        | DiagramKind::Requirement
        | DiagramKind::Architecture => (Load::Links, shapes + labels(&graph.edges) + doublings(&graph.edges) + graph.state_notes.len()),
        DiagramKind::Sequence | DiagramKind::ZenUML => {
            (Load::Messages, graph.nodes.len() + graph.edges.len() + graph.sequence_notes.len() + frame_parts(graph))
        }
        _ => (Load::Elements, shapes + graph.gitgraph.commits.len() + graph.c4.shapes.len() + graph.c4.rels.len() + chart_marks(graph)),
    }
}

/// Each part of a sequence frame: an `alt` with one `else` is two.
fn frame_parts(graph: &Graph) -> usize {
    graph.sequence_frames.iter().map(|frame| frame.sections.len()).sum()
}

/// What the chart parsers keep outside the nodes: pie slices, timeline periods and their events, and xy chart
/// categories, series and their values.
fn chart_marks(graph: &Graph) -> usize {
    let timeline: usize = graph.timeline.events.iter().map(|period| 1 + period.events.len()).sum();
    let series: usize = graph.xychart.series.iter().map(|series| 1 + series.values.len()).sum();
    graph.pie_slices.len() + timeline + graph.xychart.x_axis_categories.len() + series
}

fn graph_text_load(graph: &Graph) -> Option<(Load, usize)> {
    match graph.kind {
        DiagramKind::Sequence
        | DiagramKind::Pie
        | DiagramKind::Gantt
        | DiagramKind::Timeline
        | DiagramKind::Journey
        | DiagramKind::GitGraph
        | DiagramKind::Mindmap
        | DiagramKind::Kanban => None,
        DiagramKind::Class => Some((Load::Relations, graph.edges.len())),
        _ => {
            let joined: HashSet<&str> = graph.edges.iter().flat_map(|edge| [edge.from.as_str(), edge.to.as_str()]).collect();
            let alone = graph.nodes.keys().filter(|node| !joined.contains(node.as_str())).count();
            Some((Load::Edges, graph.edges.len() + alone + graph.subgraphs.len()))
        }
    }
}

fn scanned_text_load(source: &str) -> Option<(Load, usize)> {
    let header = statements(source).next()?;
    if LINEAR_KINDS.iter().any(|kind| header.starts_with(kind)) {
        None
    } else if header.starts_with("classDiagram") {
        Some((Load::Relations, statements(source).map(|statement| edges_in(&statement, &CLASS_ARROWS)).sum()))
    } else {
        Some((Load::Edges, statements(source).skip(1).map(|statement| edges_in(&statement, &ARROWS).max(1)).sum()))
    }
}

/// Both parsers look each participant or branch up among those already met, so their time grows with the square of
/// the lanes: a scan counts the names first, those a message or a declaration gives, `participant A as Alice` being `A`
/// and a git graph starting on `main`.
fn scanned_lanes(source: &str) -> usize {
    let keyword = kind::header(source).and_then(|header| header.split_whitespace().next()).unwrap_or_default().to_ascii_lowercase();
    let names: HashSet<String> = if keyword.starts_with("sequencediagram") {
        statements(source).skip(1).flat_map(|statement| participants(&statement)).collect()
    } else if keyword.starts_with("gitgraph") {
        statements(source).filter_map(|statement| declared(&statement, &["branch"])).chain(["main".to_owned()]).collect()
    } else {
        HashSet::new()
    };
    names.len()
}

/// The participants a sequence statement names: the one it declares, or those either side of a message's arrows.
fn participants(statement: &str) -> Vec<String> {
    if let Some(name) = declared(statement.trim_start_matches("create "), &["participant", "actor"]) {
        return vec![name];
    }
    let before_text = statement.split_once(':').map_or(statement, |(before, _)| before);
    let sides = sides(before_text, &SEQUENCE_ARROWS);
    if sides.len() < 2 {
        return Vec::new();
    }
    sides.iter().map(|side| side.trim().trim_start_matches(['+', '-']).to_owned()).filter(|name| !name.is_empty()).collect()
}

/// The word after the keyword a statement opens on, when it is one of `keywords`.
fn declared(statement: &str, keywords: &[&str]) -> Option<String> {
    let mut words = statement.split_whitespace();
    let keyword = words.next()?;
    if keywords.iter().any(|candidate| candidate.eq_ignore_ascii_case(keyword)) { words.next().map(str::to_owned) } else { None }
}

/// Longest first, so a shorter arrow never splits a longer one.
const SEQUENCE_ARROWS: [&str; 10] = ["<<-->>", "<<->>", "-->>", "->>", "-->", "->", "--x", "-x", "--)", "-)"];
const LINEAR_KINDS: [&str; 8] = ["sequenceDiagram", "pie", "gantt", "timeline", "journey", "gitGraph", "mindmap", "kanban"];
const ARROWS: [&str; 3] = ["--", "==", "-."];
const CLASS_ARROWS: [&str; 2] = ["--", ".."];
const ARROW_MARK: char = '\u{0}';

/// One edge per pair of nodes either side of each arrow: `a & b --> c & d --> e` is four then two.
fn edges_in(statement: &str, arrows: &[&str]) -> usize {
    let nodes: Vec<usize> = sides(statement, arrows).iter().map(|side| side.split('&').count()).collect();
    nodes.windows(2).map(|pair| pair[0] * pair[1]).sum()
}

/// The text between the arrows of a statement, `arrows` matched in their order.
fn sides(statement: &str, arrows: &[&str]) -> Vec<String> {
    let marked = arrows.iter().fold(statement.to_owned(), |marked, arrow| marked.replace(arrow, &ARROW_MARK.to_string()));
    marked.split(ARROW_MARK).map(str::to_owned).collect()
}

/// The statements as mermaid-text reads them: split on newlines and semicolons, with every carriage return deleted.
fn statements(source: &str) -> impl Iterator<Item = String> {
    let statements: Vec<String> = source
        .replace('\r', "")
        .split(['\n', ';'])
        .map(str::trim)
        .filter(|statement| !statement.is_empty() && !statement.starts_with("%%"))
        .map(str::to_owned)
        .collect();
    statements.into_iter()
}

fn first_line(message: &str) -> String {
    message.lines().next().unwrap_or("invalid diagram").to_owned()
}

fn labels(edges: &[Edge]) -> usize {
    edges.iter().flat_map(|edge| [&edge.label, &edge.start_label, &edge.end_label]).filter(|label| label.is_some()).count()
}

/// Edges between the same two nodes route and label around each other, so each costs one more per edge before it.
fn doublings(edges: &[Edge]) -> usize {
    let mut seen: HashMap<(&str, &str), usize> = HashMap::new();
    edges
        .iter()
        .map(|edge| {
            let pair = if edge.from <= edge.to { (edge.from.as_str(), edge.to.as_str()) } else { (edge.to.as_str(), edge.from.as_str()) };
            let earlier = seen.entry(pair).or_default();
            *earlier += 1;
            *earlier - 1
        })
        .sum()
}

/// mermaid-text recurses without end on a subgraph that reuses an id, and a stack overflow aborts past `catch_unwind`.
fn has_safe_subgraphs(source: &str) -> bool {
    let mut ids = HashSet::new();
    let mut depth = 0_usize;
    for statement in statements(source) {
        match statement.split_whitespace().next() {
            Some("subgraph") => {
                depth += 1;
                if depth > MAX_SUBGRAPH_DEPTH || !ids.insert(subgraph_id(&statement).to_owned()) {
                    return false;
                }
            }
            Some("end") => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    true
}

/// The id mermaid-text gives a bare `subgraph`.
const BARE_SUBGRAPH_ID: &str = "__sg__";

/// `subgraph id`, `subgraph id [label]`, `subgraph [label]` where the label stands for the id, or a bare `subgraph`.
fn subgraph_id(statement: &str) -> &str {
    let header = statement.trim_start_matches("subgraph").trim();
    if header.is_empty() {
        return BARE_SUBGRAPH_ID;
    }
    match header.split_once('[') {
        Some((id, _)) if !id.trim().is_empty() => id.trim(),
        Some((_, label)) => label.split_once(']').map_or(label, |(inside, _)| inside).trim(),
        None => header,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;

    fn edges(count: usize, edge: impl Fn(usize) -> String) -> String {
        format!("graph TD\n{}", (0..count).map(|index| format!("  {}\n", edge(index))).collect::<String>())
    }

    fn chain(count: usize, name: &str) -> String {
        edges(count, |index| format!("{name}{index} --> {name}{}", index + 1))
    }

    /// A sequence of `count` participants, each named by a message.
    fn messaged(count: usize) -> String {
        format!("sequenceDiagram\n{}", (1..count).map(|index| format!("  p{} ->> p{index}: m\n", index - 1)).collect::<String>())
    }

    fn boxed(count: usize) -> String {
        messaged(count).replace("sequenceDiagram\n", "sequenceDiagram\n  box Front\n    participant p0\n  end\n")
    }

    /// A git graph of `count` branches, `main` included.
    fn branched(count: usize) -> String {
        format!("gitGraph\n{}", (1..count).map(|index| format!("  branch b{index}\n  commit\n")).collect::<String>())
    }

    fn graph(source: &str) -> Graph {
        mermaid_rs_renderer::parse_mermaid(source).unwrap().graph
    }

    fn load_of(source: &str) -> (Load, usize) {
        picture_load(&graph(source))
    }

    fn picture_graph(source: &str) -> Result<Arc<Graph>, DiagramError> {
        Diagram::new(source)?.picture_graph()
    }

    fn admit_text(source: &str) -> Result<(), DiagramError> {
        Diagram::new(source)?.admit_text()
    }

    fn cost(source: &str, pictures: bool) -> usize {
        Diagram::new(source).map_or(0, |diagram| diagram.cost(pictures))
    }

    fn admitted(allowance: &Allowance, sources: &[String]) -> Vec<bool> {
        sources.iter().map(|source| allowance.admit(source).is_ok()).collect()
    }

    #[test]
    fn a_diagram_costs_what_the_engine_that_draws_it_counts() {
        let flowchart = chain(40, "a");

        assert_eq!(cost(&flowchart, true), Load::Links.cost_ms(41 + 40) + PICTURE_COST_MS);
        assert_eq!(cost(&flowchart, false), Load::Edges.cost_ms(40));
        assert_eq!(cost(&chain(3, "a"), false), MIN_COST_MS);
        assert_eq!(cost("pie\n  \"a\" : 1", false), MIN_COST_MS);
    }

    #[test]
    fn a_diagram_both_engines_refuse_or_drawn_row_after_row_costs_little() {
        assert_eq!(cost(&chain(200, "a"), true), MIN_COST_MS);
        assert_eq!(cost(&"%%\n".repeat(MAX_SOURCE_BYTES), true), 0);
        assert_eq!(cost(&format!("sequenceDiagram\n{}", "  a ->> b: hi\n".repeat(1000)), false), MIN_COST_MS);
    }

    #[test]
    fn each_diagram_that_fits_what_is_left_of_the_budget_is_let_through_in_reading_order() {
        let large = |name: &str| chain(MAX_EDGES - 1, name);
        let large_cost = cost(&large("a"), false);
        let fitting = MAX_DOCUMENT_COST_MS / large_cost;
        let sources: Vec<String> = (0..=fitting).map(|index| large(&format!("d{index}_"))).chain([chain(1, "small")]).collect();

        let allowance = Allowance::new(sources.clone(), false);

        let expected: Vec<bool> = (0..=fitting).map(|index| index < fitting).chain([true]).collect();
        assert_eq!(admitted(&allowance, &sources), expected);
        assert_eq!(allowance.admit(&large("z")).err(), Some(DiagramError::OverDocumentBudget));
    }

    #[test]
    fn a_repeated_diagram_costs_its_document_once() {
        let large = chain(MAX_EDGES, "a");
        let repeats = MAX_DOCUMENT_COST_MS / cost(&large, false) + 1;
        let last = chain(MAX_EDGES, "b");

        let allowance = Allowance::new(std::iter::repeat_n(large.clone(), repeats).chain([last.clone()]), false);

        assert_eq!(admitted(&allowance, &[large, last]), [true, true]);
    }

    #[test]
    fn a_document_lets_through_at_most_its_diagram_count() {
        let allowance = Allowance::new((0..2 * MAX_DOCUMENT_DIAGRAMS).map(|index| format!("pie\n  \"n{index}\" : 1")), false);

        assert_eq!(allowance.0.values().filter(|diagram| diagram.is_ok()).count(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn a_spent_budget_reads_no_further_diagram() {
        let spending = (0..MAX_DOCUMENT_DIAGRAMS).map(|index| format!("pie\n  \"n{index}\" : 1"));
        let unread = std::iter::from_fn(|| -> Option<String> { panic!("a diagram read after the budget was spent") });

        let allowance = Allowance::new(spending.chain(unread), false);

        assert_eq!(allowance.0.values().filter(|diagram| diagram.is_ok()).count(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn diagrams_parsed_then_refused_by_both_counts_still_spend_the_budget() {
        let refused = (0..MAX_DOCUMENT_DIAGRAMS).map(|index| chain(MAX_EDGES + 1, &format!("d{index}_")));
        let unread = std::iter::from_fn(|| -> Option<String> { panic!("a diagram read after the budget was spent") });

        let allowance = Allowance::new(refused.chain(unread), false);

        assert_eq!(allowance.0.len(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn invalid_source_is_an_error() {
        assert!(matches!(picture_graph("hello"), Err(DiagramError::Invalid(_))));
    }

    #[test]
    fn a_parser_panic_is_a_crash() {
        let panicking = "architecture-beta\n group )g(cloud)[G]";

        assert_eq!(picture_graph(panicking).unwrap_err(), DiagramError::Crashed);
        assert_eq!(cost(panicking, true), MIN_COST_MS);
    }

    #[test]
    fn oversized_source_is_refused_before_parsing() {
        assert_eq!(readable(&"%%\n".repeat(MAX_SOURCE_BYTES)), Err(DiagramError::Oversized));
    }

    #[test]
    fn nodes_edges_labels_subgraphs_and_doubled_edges_are_links() {
        assert_eq!(load_of("graph TD\n  a --> b\n  b --> c"), (Load::Links, 3 + 2));
        assert_eq!(load_of("graph TD\n  a -->|yes| b"), (Load::Links, 2 + 1 + 1));
        assert_eq!(load_of("graph TD\n  subgraph s\n  a --> b\n  end"), (Load::Links, 2 + 1 + 1));
        assert_eq!(load_of("graph TD\n  a --> b\n  b --> a\n  a --> b"), (Load::Links, 2 + 3 + (1 + 2)));
        assert_eq!(load_of("graph TD\n  a & b --> c & d"), (Load::Links, 4 + 4));
        assert_eq!(load_of("classDiagram\n  A --> B").0, Load::Links);
    }

    #[test]
    fn each_kind_counts_what_its_layout_grows_with() {
        assert_eq!(load_of("sequenceDiagram\n  a ->> b: hi\n  b ->> a: ho\n  note over a: x"), (Load::Messages, 2 + 2 + 1));
        assert_eq!(load_of("pie\n  \"a\" : 1").0, Load::Elements);
        assert_eq!(load_of("packet-beta\n  0-15: \"Source\"").0, Load::Elements);
        assert_eq!(load_of("gitGraph\n  commit\n  commit"), (Load::Elements, 2));
    }

    #[test]
    fn what_a_parser_keeps_outside_nodes_and_edges_counts_too() {
        assert_eq!(load_of("pie\n  \"a\" : 1\n  \"b\" : 2"), (Load::Elements, 2));
        assert_eq!(load_of("timeline\n  2001 : a : b\n  2002 : c"), (Load::Elements, 2 + 3));
        assert_eq!(load_of("xychart-beta\n  x-axis [a, b]\n  bar [1, 2]\n  line [3, 4]"), (Load::Elements, 2 + 2 * (1 + 2)));
        assert_eq!(load_of("sequenceDiagram\n  alt x\n  a ->> b: hi\n  else y\n  a ->> b: ho\n  end"), (Load::Messages, 2 + 2 + 2));
        assert_eq!(load_of("stateDiagram-v2\n  a --> b\n  note right of a : n\n  note left of b : m"), (Load::Links, 2 + 1 + 2));
    }

    #[test]
    fn a_chart_over_its_count_is_refused_as_a_picture() {
        let pie = format!("pie\n{}", (0..=MAX_ELEMENTS).map(|index| format!("  \"s{index}\" : 1\n")).collect::<String>());

        assert_eq!(picture_graph(&pie).err(), Some(DiagramError::OverBudget(Load::Elements)));
    }

    #[test]
    fn a_diagram_at_its_limit_passes_and_one_more_is_refused() {
        assert!(picture_graph(&chain(MAX_LINKS / 2 - 1, "n")).is_ok());
        assert_eq!(picture_graph(&chain(MAX_LINKS / 2 + 1, "n")).unwrap_err(), DiagramError::OverBudget(Load::Links));
    }

    #[test]
    fn parallel_labelled_edges_exhaust_the_budget_quickly() {
        let parallel = edges(30, |_| "a -->|again| b".to_owned());

        assert_eq!(load_of(&parallel), (Load::Links, 2 + 30 + 30 + (0..30).sum::<usize>()));
        assert_eq!(picture_graph(&parallel).unwrap_err(), DiagramError::OverBudget(Load::Links));
    }

    #[test]
    fn the_text_engine_counts_the_parsed_edges_and_lone_nodes() {
        assert_eq!(graph_text_load(&graph("graph TD\n  a --> b --> c\n  d; e")), Some((Load::Edges, 2 + 2)));
        assert_eq!(graph_text_load(&graph("graph TD\n  a & b & c --> d & e & f")), Some((Load::Edges, 9)));
        assert_eq!(graph_text_load(&graph("sequenceDiagram\n  a ->> b: hi")), None);
        assert_eq!(admit_text(&chain(MAX_EDGES, "n")), Ok(()));
        assert_eq!(admit_text(&chain(MAX_EDGES + 1, "n")), Err(DiagramError::OverBudget(Load::Edges)));
    }

    #[test]
    fn the_scan_for_syntax_mermaid_rs_renderer_refuses_counts_every_fanned_out_edge() {
        assert_eq!(scanned_text_load("graph TD\n  a --> b --> c\n  %% a comment\n  d; e"), Some((Load::Edges, 2 + 1 + 1)));
        assert_eq!(scanned_text_load("graph TD\n  a & b & c --> d & e --> f"), Some((Load::Edges, 3 * 2 + 2)));
        assert_eq!(scanned_text_load(&format!("sequenceDiagram\n{}", "  a ->> b: hi\n".repeat(1000))), None);
        assert_eq!(
            scanned_text_load("%% why\nclassDiagram\n  class A {\n    +f() int\n  }\n  A & C --> B\n  B ..> C"),
            Some((Load::Relations, 3))
        );
    }

    #[test]
    fn fanned_out_edges_hidden_on_one_line_are_refused_by_both_engines() {
        let fanned = edges(12, |index| format!("a{index} & b{index} & c{index} --> d{index} & e{index} & f{index}"));

        assert_eq!(picture_graph(&fanned).unwrap_err(), DiagramError::OverBudget(Load::Links));
        assert_eq!(admit_text(&fanned), Err(DiagramError::OverBudget(Load::Edges)));
    }

    #[test]
    fn the_text_engine_counts_the_lanes_every_row_crosses() {
        for lanes in [messaged, boxed, branched] {
            assert_eq!(admit_text(&lanes(MAX_LANES)), Ok(()));
            assert_eq!(text_cost(&lanes(MAX_LANES + 1), None), Err(DiagramError::OverBudget(Load::Lanes)));
        }
        assert_eq!(cost(&messaged(MAX_LANES), false), MAX_LANES);
    }

    #[test]
    fn lanes_over_the_limit_are_refused_before_parsing() {
        fn declared(count: usize) -> String {
            format!("sequenceDiagram\n{}", (0..count).map(|index| format!("  actor p{index} as Person {index}\n")).collect::<String>())
        }
        fn fronted(count: usize) -> String {
            format!("---\ntitle: Lanes\n---\n{}", messaged(count))
        }

        for lanes in [messaged, boxed, branched, declared, fronted] {
            assert_eq!(readable(&lanes(MAX_LANES)), Ok(()));
            assert_eq!(readable(&lanes(MAX_LANES + 1)), Err(DiagramError::OverBudget(Load::Lanes)));
        }
    }

    #[test]
    fn the_lane_scan_counts_each_participant_once_whatever_names_it() {
        let source = "sequenceDiagram\n  autonumber\n  create participant A\n  actor U as User\n  U->>+A: hi\n  A-->>-U: ok\n  \
                      A-)B: async\n  B--xU: lost\n  U<<->>A: both\n  note over A,B: n\n  loop every minute\n  A->>A: tick\n  end";

        assert_eq!(scanned_lanes(source), 3);
        assert_eq!(scanned_lanes("gitGraph\n  commit\n  branch dev\n  checkout main\n  branch dev"), 2);
        assert_eq!(scanned_lanes(&chain(MAX_LANES + 1, "n")), 0);
    }

    #[test]
    fn syntax_only_mermaid_text_reads_passes_the_text_gate() {
        assert_eq!(admit_text("classDiagram\n  class Shape {\n    <<interface>>\n    +area() double\n  }"), Ok(()));
    }

    #[test]
    fn a_reused_subgraph_id_is_refused_before_parsing() {
        let sources = [
            "graph TD\n subgraph a\n subgraph a\n end\n end",
            "graph TD; subgraph a; subgraph a; end; end",
            "graph TD\n subgraph a [One]\n end\n subgraph b\n subgraph a[Two]\n end\n end",
            "graph TD\n subgraph [Same]\n subgraph [Same]\n end\n end",
            "graph TD\n subgraph\n subgraph\n end\n end",
            "graph TD\n subgraph\n subgraph __sg__\n end\n end",
            "graph TD\n subgraph\n subgraph __sg__\n A-->B\n end\n end",
            "graph TD\n sub\rgraph a\n sub\rgraph a\n end\n end",
        ];

        for source in sources {
            assert_eq!(readable(source), Err(DiagramError::UnsafeSubgraphs), "{source:?}");
        }
    }

    #[test]
    fn subgraphs_nested_too_deep_are_refused() {
        let nested = |depth: usize| {
            let opening: String = (0..depth).map(|level| format!(" subgraph s{level}\n")).collect();
            format!("graph TD\n{opening} x --> y\n{}", " end\n".repeat(depth))
        };

        assert_eq!(readable(&nested(MAX_SUBGRAPH_DEPTH)), Ok(()));
        assert_eq!(readable(&nested(MAX_SUBGRAPH_DEPTH + 1)), Err(DiagramError::UnsafeSubgraphs));
    }

    #[test]
    fn distinct_subgraphs_are_safe() {
        assert!(has_safe_subgraphs(
            "graph TD\n subgraph outer\n subgraph inner [Inner box]\n a --> b\n end\n end\n subgraph other\n c\n end"
        ));
    }
}