@zyro-sec/merman 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.test.ts +203 -0
  4. package/src/core/canvas.ts +228 -0
  5. package/src/core/color/style.test.ts +24 -0
  6. package/src/core/color/style.ts +56 -0
  7. package/src/core/drawing.test.ts +116 -0
  8. package/src/core/drawing.ts +301 -0
  9. package/src/core/geometry.test.ts +112 -0
  10. package/src/core/geometry.ts +347 -0
  11. package/src/core/mermaid.ts +38 -0
  12. package/src/core/render-grid.ts +51 -0
  13. package/src/core/spatial.test.ts +87 -0
  14. package/src/core/spatial.ts +243 -0
  15. package/src/core/text-lines.ts +32 -0
  16. package/src/core/text.test.ts +33 -0
  17. package/src/core/text.ts +44 -0
  18. package/src/detect.ts +17 -0
  19. package/src/diagnostics.ts +16 -0
  20. package/src/flowchart/drawing.ts +340 -0
  21. package/src/flowchart/flowchart.test.ts +2800 -0
  22. package/src/flowchart/labels.test.ts +127 -0
  23. package/src/flowchart/labels.ts +144 -0
  24. package/src/flowchart/layout.ts +1427 -0
  25. package/src/flowchart/options.ts +12 -0
  26. package/src/flowchart/parser.ts +467 -0
  27. package/src/flowchart/render.ts +10 -0
  28. package/src/flowchart/routing.test.ts +368 -0
  29. package/src/flowchart/routing.ts +1542 -0
  30. package/src/flowchart/style.ts +79 -0
  31. package/src/flowchart/types.ts +65 -0
  32. package/src/gantt/diagram.test.ts +124 -0
  33. package/src/gantt/diagram.ts +8 -0
  34. package/src/gantt/drawing.ts +191 -0
  35. package/src/gantt/parser.ts +161 -0
  36. package/src/gantt/render-grid.ts +17 -0
  37. package/src/gantt/style.ts +36 -0
  38. package/src/gantt/types.ts +44 -0
  39. package/src/gitgraph/diagram.test.ts +183 -0
  40. package/src/gitgraph/diagram.ts +8 -0
  41. package/src/gitgraph/drawing.ts +234 -0
  42. package/src/gitgraph/parser.ts +219 -0
  43. package/src/gitgraph/render-grid.ts +17 -0
  44. package/src/gitgraph/style.ts +37 -0
  45. package/src/gitgraph/types.ts +36 -0
  46. package/src/layout-audit.test.ts +92 -0
  47. package/src/markdown.ts +336 -0
  48. package/src/palette.test.ts +103 -0
  49. package/src/palette.ts +75 -0
  50. package/src/plugin.ts +15 -0
  51. package/src/sequence/diagram.test.ts +757 -0
  52. package/src/sequence/diagram.ts +8 -0
  53. package/src/sequence/drawing.ts +287 -0
  54. package/src/sequence/options.ts +8 -0
  55. package/src/sequence/parser.ts +282 -0
  56. package/src/sequence/placement.test.ts +219 -0
  57. package/src/sequence/placement.ts +684 -0
  58. package/src/sequence/render-grid.ts +22 -0
  59. package/src/sequence/style.ts +81 -0
  60. package/src/sequence/types.ts +74 -0
  61. package/src/state/diagram.test.ts +1386 -0
  62. package/src/state/diagram.ts +8 -0
  63. package/src/state/drawing.ts +360 -0
  64. package/src/state/endpoint.ts +15 -0
  65. package/src/state/layout.test.ts +314 -0
  66. package/src/state/layout.ts +1134 -0
  67. package/src/state/note.ts +59 -0
  68. package/src/state/options.ts +11 -0
  69. package/src/state/parser.ts +224 -0
  70. package/src/state/render-grid.ts +22 -0
  71. package/src/state/routing.test.ts +693 -0
  72. package/src/state/routing.ts +1522 -0
  73. package/src/state/search.ts +103 -0
  74. package/src/state/style.test.ts +113 -0
  75. package/src/state/style.ts +52 -0
  76. package/src/state/types.ts +63 -0
  77. package/src/state/visible-model.test.ts +84 -0
  78. package/src/state/visible-model.ts +77 -0
  79. package/src/test/diagnostics.test.ts +129 -0
  80. package/src/test/diagram.ts +32 -0
  81. package/src/test/layout-audit/fixtures.ts +538 -0
  82. package/src/test/layout-audit/harness.ts +522 -0
  83. package/src/test/markdown.test.ts +474 -0
  84. package/src/timeline/diagram.test.ts +188 -0
  85. package/src/timeline/diagram.ts +8 -0
  86. package/src/timeline/drawing.ts +109 -0
  87. package/src/timeline/parser.ts +119 -0
  88. package/src/timeline/render-grid.ts +17 -0
  89. package/src/timeline/style.ts +36 -0
  90. package/src/timeline/types.ts +31 -0
  91. package/tsconfig.json +10 -0
  92. package/README.md +0 -3
@@ -0,0 +1,103 @@
1
+ import type { DiagramPoint } from "../core/geometry.js"
2
+ import type { SpatialIndex, SpatialRole } from "../core/spatial.js"
3
+
4
+ const MAX_RENDER_SEARCH_VISITS = 250_000
5
+
6
+ export interface StateSearchBudget {
7
+ remaining: number
8
+ }
9
+
10
+ export interface StateSearchSpace {
11
+ blocked: ReadonlySet<string>
12
+ minX: number
13
+ minY: number
14
+ maxX: number
15
+ maxY: number
16
+ }
17
+
18
+ export function createStateSearchBudget(): StateSearchBudget {
19
+ return { remaining: MAX_RENDER_SEARCH_VISITS }
20
+ }
21
+
22
+ export function createStateSearchSpace(
23
+ space: SpatialIndex,
24
+ clearance: (role: SpatialRole) => number = () => 0,
25
+ ): StateSearchSpace {
26
+ const blocked = new Set<string>()
27
+ let minX = 0
28
+ let minY = 0
29
+ let maxX = 0
30
+ let maxY = 0
31
+
32
+ for (const claim of space.claims) {
33
+ const padding = clearance(claim.role)
34
+ for (const span of claim.spans) {
35
+ for (let y = span.y - padding; y <= span.y + padding; y++) {
36
+ for (let x = span.fromX - padding; x <= span.toX + padding; x++) {
37
+ blocked.add(`${x}:${y}`)
38
+ minX = Math.min(minX, x)
39
+ minY = Math.min(minY, y)
40
+ maxX = Math.max(maxX, x)
41
+ maxY = Math.max(maxY, y)
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ return { blocked, minX, minY, maxX, maxY }
48
+ }
49
+
50
+ export function findStateManhattanPath(
51
+ starts: readonly DiagramPoint[],
52
+ goal: DiagramPoint,
53
+ space: Pick<StateSearchSpace, "blocked">,
54
+ bounds: Pick<StateSearchSpace, "minX" | "minY" | "maxX" | "maxY">,
55
+ budget: StateSearchBudget,
56
+ isFree: (point: DiagramPoint) => boolean = (point) => !space.blocked.has(pointKey(point)),
57
+ ): DiagramPoint[] | undefined {
58
+ const queue = [...new Map(starts.filter(isFree).map((point) => [pointKey(point), point])).values()]
59
+ const parents = new Map(queue.map((point) => [pointKey(point), undefined as string | undefined]))
60
+ const points = new Map(queue.map((point) => [pointKey(point), point]))
61
+
62
+ for (let cursor = 0; cursor < queue.length && budget.remaining > 0; cursor++, budget.remaining--) {
63
+ const current = queue[cursor]!
64
+ if (current.x === goal.x && current.y === goal.y) break
65
+ const dx = Math.sign(goal.x - current.x)
66
+ const dy = Math.sign(goal.y - current.y)
67
+ const candidates = [
68
+ ...(dx === 0 ? [] : [{ x: current.x + dx, y: current.y }]),
69
+ ...(dy === 0 ? [] : [{ x: current.x, y: current.y + dy }]),
70
+ { x: current.x + 1, y: current.y },
71
+ { x: current.x, y: current.y + 1 },
72
+ { x: current.x - 1, y: current.y },
73
+ { x: current.x, y: current.y - 1 },
74
+ ]
75
+ for (const candidate of candidates) {
76
+ if (
77
+ candidate.x < bounds.minX ||
78
+ candidate.x > bounds.maxX ||
79
+ candidate.y < bounds.minY ||
80
+ candidate.y > bounds.maxY
81
+ )
82
+ continue
83
+ const key = pointKey(candidate)
84
+ if (parents.has(key) || !isFree(candidate)) continue
85
+ parents.set(key, pointKey(current))
86
+ points.set(key, candidate)
87
+ queue.push(candidate)
88
+ }
89
+ }
90
+
91
+ if (!parents.has(pointKey(goal))) return undefined
92
+ const path: DiagramPoint[] = []
93
+ let cursor: string | undefined = pointKey(goal)
94
+ while (cursor) {
95
+ path.push(points.get(cursor)!)
96
+ cursor = parents.get(cursor)
97
+ }
98
+ return path.reverse()
99
+ }
100
+
101
+ function pointKey(point: DiagramPoint): string {
102
+ return `${point.x}:${point.y}`
103
+ }
@@ -0,0 +1,113 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { RGBA } from "@opentui/core"
3
+ import { drawStateDiagramGrid } from "./drawing.js"
4
+ import { parseMermaidStateDiagram } from "./parser.js"
5
+ import { renderStateGridStyledText } from "./render-grid.js"
6
+ import { resolveStateStyleColors } from "./style.js"
7
+
8
+ describe("state note connector styles", () => {
9
+ test("ramps the final connector cells into the note border", () => {
10
+ const grid = drawStateDiagramGrid(
11
+ parseMermaidStateDiagram(`stateDiagram-v2
12
+ direction LR
13
+ A --> B
14
+ note right of A : note`),
15
+ )
16
+ const connectorStyles = grid.rows.flatMap((row) =>
17
+ row.map((cell) => cell.style).filter((style) => style?.startsWith("noteConnectorRamp")),
18
+ )
19
+
20
+ expect(new Set(connectorStyles)).toEqual(
21
+ new Set(["noteConnectorRamp1", "noteConnectorRamp2", "noteConnectorRamp3"]),
22
+ )
23
+ })
24
+
25
+ test("resolves the ramp from connector color toward border color", () => {
26
+ const colors = resolveStateStyleColors({
27
+ noteConnector: RGBA.fromInts(0, 0, 0, 255),
28
+ noteBorder: RGBA.fromInts(200, 200, 200, 255),
29
+ })
30
+ const reds = [
31
+ colors.noteConnector.toInts()[0],
32
+ colors.noteConnectorRamp1.toInts()[0],
33
+ colors.noteConnectorRamp2.toInts()[0],
34
+ colors.noteConnectorRamp3.toInts()[0],
35
+ colors.noteBorder.toInts()[0],
36
+ ]
37
+
38
+ expect(reds).toEqual([...reds].sort((left, right) => left - right))
39
+ expect(new Set(reds).size).toBe(5)
40
+ })
41
+ })
42
+
43
+ describe("state transition departure styles", () => {
44
+ test("ramps once from an ordinary state without restarting at a choice fork", () => {
45
+ const grid = drawStateDiagramGrid(
46
+ parseMermaidStateDiagram(`stateDiagram-v2
47
+ Check --> Decision
48
+ state Decision <<choice>>
49
+ Decision --> Ready: yes
50
+ Decision --> Failed: no`),
51
+ )
52
+ const rampStyles = grid.rows
53
+ .flatMap((row) => row.map((cell) => cell.style))
54
+ .filter((style) => style?.startsWith("stateDepartureRamp"))
55
+
56
+ expect(rampStyles).toHaveLength(3)
57
+ expect(new Set(rampStyles)).toEqual(new Set(["stateDepartureRamp1", "stateDepartureRamp2", "stateDepartureRamp3"]))
58
+ })
59
+ })
60
+
61
+ describe("state component styles", () => {
62
+ test("separates box and group text from their borders", () => {
63
+ const grid = drawStateDiagramGrid(
64
+ parseMermaidStateDiagram(`stateDiagram-v2
65
+ state Group {
66
+ A --> [*]
67
+ }`),
68
+ )
69
+ const styles = grid.rows.flatMap((row) => row.map((cell) => cell.style))
70
+
71
+ expect(styles).toContain("state")
72
+ expect(styles).toContain("stateBorder")
73
+ expect(styles).toContain("composite")
74
+ expect(styles).toContain("compositeLabel")
75
+ })
76
+
77
+ test("resolves independent box and group text colors", () => {
78
+ const state = RGBA.fromInts(10, 0, 0, 255)
79
+ const stateBorder = RGBA.fromInts(20, 0, 0, 255)
80
+ const composite = RGBA.fromInts(30, 0, 0, 255)
81
+ const compositeLabel = RGBA.fromInts(40, 0, 0, 255)
82
+ const colors = resolveStateStyleColors({ state, stateBorder, composite, compositeLabel })
83
+
84
+ expect(colors.state).toBe(state)
85
+ expect(colors.stateBorder).toBe(stateBorder)
86
+ expect(colors.composite).toBe(composite)
87
+ expect(colors.compositeLabel).toBe(compositeLabel)
88
+ })
89
+
90
+ test("renders transition labels with an independent background", () => {
91
+ const background = RGBA.fromInts(30, 40, 50, 255)
92
+ const grid = drawStateDiagramGrid(
93
+ parseMermaidStateDiagram(`stateDiagram-v2
94
+ A --> B: transition label`),
95
+ )
96
+ const styled = renderStateGridStyledText(grid, resolveStateStyleColors(), { label: background })
97
+ const row = grid.rows.find((cells) =>
98
+ cells
99
+ .map((cell) => cell.char)
100
+ .join("")
101
+ .includes("transition label"),
102
+ )!
103
+ const start = row
104
+ .map((cell) => cell.char)
105
+ .join("")
106
+ .indexOf("transition label")
107
+
108
+ expect(styled.chunks.some((chunk) => chunk.text === " transition label " && chunk.bg === background)).toBe(true)
109
+ expect(styled.chunks.some((chunk) => chunk.text.includes("A") && chunk.bg !== undefined)).toBe(false)
110
+ expect(row[start - 1]?.style).toBe("label")
111
+ expect(row[start + "transition label".length]?.style).toBe("label")
112
+ })
113
+ })
@@ -0,0 +1,52 @@
1
+ import { RGBA } from "@opentui/core"
2
+ import { createColorRampTheme, numberedStyleKeys, rgba, type DiagramRgb } from "../core/color/style.js"
3
+ import type { BaseStateCellStyle, NoteConnectorRampStyle, StateCellStyle, StateDepartureRampStyle } from "./types.js"
4
+
5
+ const DEFAULT_THEME_RGB = {
6
+ state: [228, 239, 232],
7
+ stateBorder: [228, 239, 232],
8
+ composite: [111, 138, 126],
9
+ compositeLabel: [111, 138, 126],
10
+ transition: [134, 225, 200],
11
+ label: [134, 225, 200],
12
+ noteBorder: [141, 169, 155],
13
+ noteText: [215, 229, 221],
14
+ noteConnector: [141, 169, 155],
15
+ start: [134, 225, 200],
16
+ end: [230, 177, 126],
17
+ choice: [134, 225, 200],
18
+ } as const satisfies Record<BaseStateCellStyle, DiagramRgb>
19
+ const STATE_RAMP_STEPS = [1, 2, 3] as const
20
+ export const NOTE_CONNECTOR_RAMP_STYLES = numberedStyleKeys(
21
+ "noteConnectorRamp",
22
+ STATE_RAMP_STEPS,
23
+ ) satisfies readonly NoteConnectorRampStyle[]
24
+ export const STATE_DEPARTURE_RAMP_STYLES = numberedStyleKeys(
25
+ "stateDepartureRamp",
26
+ STATE_RAMP_STEPS,
27
+ ) satisfies readonly StateDepartureRampStyle[]
28
+ export type StateStyleColors = Required<Record<StateCellStyle, RGBA>>
29
+
30
+ export function resolveStateStyleColors(
31
+ colors: Partial<Record<BaseStateCellStyle, RGBA | undefined>> = {},
32
+ ): StateStyleColors {
33
+ const resolved = {
34
+ state: colors.state ?? rgba(DEFAULT_THEME_RGB.state),
35
+ stateBorder: colors.stateBorder ?? colors.state ?? rgba(DEFAULT_THEME_RGB.stateBorder),
36
+ composite: colors.composite ?? rgba(DEFAULT_THEME_RGB.composite),
37
+ compositeLabel: colors.compositeLabel ?? colors.composite ?? rgba(DEFAULT_THEME_RGB.compositeLabel),
38
+ transition: colors.transition ?? rgba(DEFAULT_THEME_RGB.transition),
39
+ label: colors.label ?? rgba(DEFAULT_THEME_RGB.label),
40
+ noteBorder: colors.noteBorder ?? rgba(DEFAULT_THEME_RGB.noteBorder),
41
+ noteText: colors.noteText ?? rgba(DEFAULT_THEME_RGB.noteText),
42
+ noteConnector: colors.noteConnector ?? rgba(DEFAULT_THEME_RGB.noteConnector),
43
+ start: colors.start ?? rgba(DEFAULT_THEME_RGB.start),
44
+ end: colors.end ?? rgba(DEFAULT_THEME_RGB.end),
45
+ choice: colors.choice ?? rgba(DEFAULT_THEME_RGB.choice),
46
+ }
47
+ return {
48
+ ...resolved,
49
+ ...createColorRampTheme(NOTE_CONNECTOR_RAMP_STYLES, resolved.noteConnector, resolved.noteBorder),
50
+ ...createColorRampTheme(STATE_DEPARTURE_RAMP_STYLES, resolved.stateBorder, resolved.transition),
51
+ }
52
+ }
@@ -0,0 +1,63 @@
1
+ import type { BorderStyle } from "@opentui/core"
2
+
3
+ export type StateDiagramDirection = "TB" | "TD" | "BT" | "LR" | "RL"
4
+ export type StateDiagramArrowHeadStyle = "filled" | "line"
5
+
6
+ export interface StateDiagramState {
7
+ id: string
8
+ label: string
9
+ kind: "state" | "start" | "end" | "choice"
10
+ parentId?: string
11
+ }
12
+
13
+ export interface StateDiagramTransition {
14
+ from: string
15
+ to: string
16
+ label: string
17
+ }
18
+
19
+ export interface StateDiagramCompositeState {
20
+ id: string
21
+ label: string
22
+ parentId?: string
23
+ }
24
+
25
+ export interface StateDiagramNote {
26
+ target: string
27
+ position: "left" | "right"
28
+ lines: string[]
29
+ }
30
+
31
+ export interface StateDiagram {
32
+ direction: StateDiagramDirection
33
+ states: StateDiagramState[]
34
+ transitions: StateDiagramTransition[]
35
+ composites: StateDiagramCompositeState[]
36
+ notes: StateDiagramNote[]
37
+ }
38
+
39
+ export interface StateDiagramRenderOptions {
40
+ direction?: StateDiagramDirection
41
+ borderStyle?: BorderStyle
42
+ arrowHeadStyle?: StateDiagramArrowHeadStyle
43
+ minStateGap?: number
44
+ /** Target rendered width. Oversized horizontal layouts fold vertically. */
45
+ layoutMaxWidth?: number
46
+ }
47
+
48
+ export type NoteConnectorRampStyle = `noteConnectorRamp${1 | 2 | 3}`
49
+ export type StateDepartureRampStyle = `stateDepartureRamp${1 | 2 | 3}`
50
+ export type BaseStateCellStyle =
51
+ | "state"
52
+ | "stateBorder"
53
+ | "composite"
54
+ | "compositeLabel"
55
+ | "transition"
56
+ | "label"
57
+ | "noteBorder"
58
+ | "noteText"
59
+ | "noteConnector"
60
+ | "start"
61
+ | "end"
62
+ | "choice"
63
+ export type StateCellStyle = BaseStateCellStyle | NoteConnectorRampStyle | StateDepartureRampStyle
@@ -0,0 +1,84 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { parseMermaidStateDiagram } from "./parser.js"
3
+ import { prepareVisibleStateDiagram } from "./visible-model.js"
4
+
5
+ describe("prepareVisibleStateDiagram", () => {
6
+ test("collapses composite marker transitions", () => {
7
+ const parsed = parseMermaidStateDiagram(`stateDiagram-v2
8
+ [*] --> Authenticated: login
9
+ state Authenticated {
10
+ [*] --> Idle
11
+ Idle --> Editing: open
12
+ Editing --> [*]: save
13
+ }
14
+ Authenticated --> [*]: logout`)
15
+
16
+ const visible = prepareVisibleStateDiagram(parsed)
17
+ const entry = visible.transitions.find((transition) => transition.from === "__start")
18
+ const exit = visible.transitions.find((transition) => transition.to === "__end")
19
+
20
+ expect(visible.states.some((state) => state.id === "Authenticated.__start")).toBe(false)
21
+ expect(visible.states.some((state) => state.id === "Authenticated.__end")).toBe(false)
22
+ expect(entry).toMatchObject({ from: "__start", to: "Idle", label: "login" })
23
+ expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save<br/>logout" })
24
+ })
25
+
26
+ test("collapses nested composite entry chains without retaining scoped markers", () => {
27
+ const visible = prepareVisibleStateDiagram(
28
+ parseMermaidStateDiagram(`stateDiagram-v2
29
+ state Session {
30
+ [*] --> Open
31
+ state Open {
32
+ [*] --> Clean
33
+ Clean --> Dirty: edit
34
+ Dirty --> Clean: save
35
+ }
36
+ Open --> [*]: close
37
+ }
38
+ [*] --> Session
39
+ Session --> [*]`),
40
+ )
41
+
42
+ expect(visible.states.map((state) => state.id)).toEqual(["Clean", "Dirty", "__start", "__end"])
43
+ expect(visible.transitions).toContainEqual({ from: "__start", to: "Clean", label: "" })
44
+ expect(visible.transitions.some((transition) => transition.from.includes(".__start"))).toBe(false)
45
+ expect(visible.transitions.some((transition) => transition.to.includes(".__start"))).toBe(false)
46
+ })
47
+
48
+ test("resolves an outgoing composite transition through its concrete exit state", () => {
49
+ const visible = prepareVisibleStateDiagram(
50
+ parseMermaidStateDiagram(`stateDiagram-v2
51
+ state Session {
52
+ [*] --> Open
53
+ state Open {
54
+ [*] --> Clean
55
+ Clean --> Dirty: edit
56
+ Dirty --> Clean: save
57
+ Dirty --> [*]
58
+ }
59
+ Open --> Closing: request close
60
+ Closing --> Open: cancel
61
+ }
62
+ [*] --> Session: hydrate`),
63
+ )
64
+
65
+ expect(visible.transitions).toContainEqual({ from: "Dirty", to: "Closing", label: "request close" })
66
+ expect(visible.transitions).toContainEqual({ from: "Closing", to: "Clean", label: "cancel" })
67
+ expect(visible.transitions.some((transition) => transition.from === "Open")).toBe(false)
68
+ })
69
+
70
+ test("preserves labels on both sides of collapsed composite markers", () => {
71
+ const visible = prepareVisibleStateDiagram(
72
+ parseMermaidStateDiagram(`stateDiagram-v2
73
+ [*] --> Session: open session
74
+ state Session {
75
+ [*] --> Ready: initialize
76
+ Ready --> [*]: finalize
77
+ }
78
+ Session --> [*]: close session`),
79
+ )
80
+
81
+ expect(visible.transitions).toContainEqual({ from: "__start", to: "Ready", label: "open session<br/>initialize" })
82
+ expect(visible.transitions).toContainEqual({ from: "Ready", to: "__end", label: "finalize<br/>close session" })
83
+ })
84
+ })
@@ -0,0 +1,77 @@
1
+ import type { StateDiagram, StateDiagramState, StateDiagramTransition } from "./types.js"
2
+
3
+ export type StateVisibleTransition = StateDiagramTransition
4
+
5
+ export interface StateVisibleDiagram extends Omit<StateDiagram, "transitions"> {
6
+ transitions: StateVisibleTransition[]
7
+ }
8
+
9
+ export function isHiddenCompositeMarker(state: StateDiagramState | undefined): boolean {
10
+ return Boolean(state?.parentId && (state.kind === "start" || state.kind === "end"))
11
+ }
12
+
13
+ function composeTransitionLabel(incoming: StateDiagramTransition, outgoing: StateDiagramTransition): string {
14
+ return [incoming.label, outgoing.label].filter(Boolean).join("<br/>")
15
+ }
16
+
17
+ function collapseHiddenCompositeMarkerTransitionsOnce(
18
+ transitions: readonly StateVisibleTransition[],
19
+ statesById: ReadonlyMap<string, StateDiagramState>,
20
+ ): { transitions: StateVisibleTransition[]; changed: boolean } {
21
+ const hiddenMarkers = new Set(
22
+ [...statesById.values()].filter((state) => isHiddenCompositeMarker(state)).map((state) => state.id),
23
+ )
24
+ if (hiddenMarkers.size === 0) return { transitions: [...transitions], changed: false }
25
+
26
+ for (const markerId of hiddenMarkers) {
27
+ const incoming = transitions.filter((transition) => transition.to === markerId && transition.from !== markerId)
28
+ const outgoing = transitions.filter((transition) => transition.from === markerId && transition.to !== markerId)
29
+ if (incoming.length === 0 || outgoing.length === 0) continue
30
+
31
+ const skipped = new Set([...incoming, ...outgoing])
32
+ return {
33
+ transitions: [
34
+ ...transitions.filter((transition) => !skipped.has(transition)),
35
+ ...incoming.flatMap((incomingTransition) =>
36
+ outgoing.map((outgoingTransition) => ({
37
+ from: incomingTransition.from,
38
+ to: outgoingTransition.to,
39
+ label: composeTransitionLabel(incomingTransition, outgoingTransition),
40
+ })),
41
+ ),
42
+ ],
43
+ changed: true,
44
+ }
45
+ }
46
+
47
+ return { transitions: [...transitions], changed: false }
48
+ }
49
+
50
+ function collapseHiddenCompositeMarkerTransitions(diagram: StateDiagram): StateVisibleTransition[] {
51
+ const statesById = new Map(diagram.states.map((state) => [state.id, state]))
52
+ let transitions: StateVisibleTransition[] = diagram.transitions.map((transition) => ({ ...transition }))
53
+
54
+ while (true) {
55
+ const result = collapseHiddenCompositeMarkerTransitionsOnce(transitions, statesById)
56
+ transitions = result.transitions
57
+ if (!result.changed) return transitions
58
+ }
59
+ }
60
+
61
+ export function prepareVisibleStateDiagram(diagram: StateDiagram): StateVisibleDiagram {
62
+ const transitions = collapseHiddenCompositeMarkerTransitions(diagram)
63
+ const referencedHiddenMarkers = new Set<string>()
64
+ const statesById = new Map(diagram.states.map((state) => [state.id, state]))
65
+ for (const transition of transitions) {
66
+ const from = statesById.get(transition.from)
67
+ const to = statesById.get(transition.to)
68
+ if (from && isHiddenCompositeMarker(from)) referencedHiddenMarkers.add(from.id)
69
+ if (to && isHiddenCompositeMarker(to)) referencedHiddenMarkers.add(to.id)
70
+ }
71
+
72
+ return {
73
+ ...diagram,
74
+ states: diagram.states.filter((state) => !isHiddenCompositeMarker(state) || referencedHiddenMarkers.has(state.id)),
75
+ transitions,
76
+ }
77
+ }
@@ -0,0 +1,129 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { MermaidSyntaxError } from "../diagnostics.js"
3
+ import { renderGitGraphDiagram } from "../gitgraph/diagram.js"
4
+ import { parseMermaidFlowchartDiagram } from "../flowchart/parser.js"
5
+ import { parseMermaidSequenceDiagram } from "../sequence/parser.js"
6
+ import { parseMermaidStateDiagram } from "../state/parser.js"
7
+ import { renderTimelineDiagram } from "../timeline/diagram.js"
8
+ import { renderSequenceDiagram } from "../sequence/diagram.js"
9
+
10
+ describe("parser diagnostics", () => {
11
+ test("ignores flowchart presentation directives that do not change terminal structure", () => {
12
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
13
+ A[Start] --> B[Done]
14
+ classDef highlight fill:#fff
15
+ class A highlight
16
+ style B fill:#000
17
+ linkStyle 0 stroke:#fff`)
18
+
19
+ expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B"])
20
+ expect(diagram.edges).toHaveLength(1)
21
+ })
22
+
23
+ test("reports unsupported structural flowchart statements with source location", () => {
24
+ expect(() =>
25
+ parseMermaidFlowchartDiagram(`flowchart LR
26
+ A[Start] --> B[Done]
27
+ A --o B`),
28
+ ).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
29
+ })
30
+
31
+ test("does not partially parse unsupported flowchart syntax", () => {
32
+ for (const statement of ["A & --> C", "A((Start)) --> B", "A-->B; B-->C"]) {
33
+ expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n ${statement}`)).toThrow(MermaidSyntaxError)
34
+ }
35
+ })
36
+
37
+ test("does not treat arrows inside flowchart node labels as edges", () => {
38
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
39
+ A["send --> receive"] --> B`)
40
+
41
+ expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B"])
42
+ expect(diagram.nodes[0]?.label).toBe("send --> receive")
43
+ expect(diagram.edges).toHaveLength(1)
44
+ })
45
+
46
+ test("rejects pathological flowchart statements before parsing edge operators", () => {
47
+ const statement = "-.a".repeat(4_000)
48
+ expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n${statement}`)).toThrow("Flowchart statement is too long")
49
+ })
50
+
51
+ test("exposes structured syntax errors through top-level rendering", () => {
52
+ try {
53
+ renderSequenceDiagram(`sequenceDiagram
54
+ A->>B: request
55
+ opt retry`)
56
+ throw new Error("expected render to reject unsupported syntax")
57
+ } catch (error) {
58
+ expect(error).toBeInstanceOf(MermaidSyntaxError)
59
+ if (!(error instanceof MermaidSyntaxError)) return
60
+ expect(error.kind).toBe("sequence")
61
+ expect(error.lineNumber).toBe(3)
62
+ expect(error.sourceLine).toBe("opt retry")
63
+ }
64
+ })
65
+
66
+ test("rejects unsupported bidirectional sequence arrows without phantom participants", () => {
67
+ for (const message of ["A<<->>B: hello", "A<<-->>B: hello"]) {
68
+ expect(() => parseMermaidSequenceDiagram(`sequenceDiagram\n ${message}`)).toThrow(MermaidSyntaxError)
69
+ }
70
+ })
71
+
72
+ test("rejects chained sequence and state transitions instead of creating phantom endpoints", () => {
73
+ expect(() => parseMermaidSequenceDiagram("sequenceDiagram\n A->>B->>C: hello")).toThrow(MermaidSyntaxError)
74
+ expect(() => parseMermaidStateDiagram("stateDiagram-v2\n A-->B-->C")).toThrow(MermaidSyntaxError)
75
+ })
76
+
77
+ test("reports unclosed state constructs at their opening line", () => {
78
+ expect(() =>
79
+ parseMermaidStateDiagram(`stateDiagram-v2
80
+ state Running {
81
+ [*] --> Ready`),
82
+ ).toThrow('Unclosed composite state; expected "}" in state diagram at line 2: "state Running {"')
83
+ })
84
+
85
+ test("reports unsupported state statements", () => {
86
+ expect(() => parseMermaidStateDiagram(`stateDiagram-v2\n hide empty description`)).toThrow(
87
+ 'Unsupported syntax in state diagram at line 2: "hide empty description"',
88
+ )
89
+ })
90
+
91
+ test("rejects unsupported composite-local state directions", () => {
92
+ expect(() =>
93
+ parseMermaidStateDiagram(`stateDiagram-v2
94
+ direction LR
95
+ state Parent {
96
+ direction TB
97
+ A --> B
98
+ }`),
99
+ ).toThrow("Composite-local direction is not supported")
100
+ })
101
+
102
+ test("reports malformed sequence block endings", () => {
103
+ expect(() =>
104
+ parseMermaidSequenceDiagram(`sequenceDiagram
105
+ end`),
106
+ ).toThrow('Unexpected "end" without an open block in sequence diagram at line 2: "end"')
107
+ })
108
+
109
+ test("reports malformed timeline continuations with timeline diagnostics", () => {
110
+ expect(() => renderTimelineDiagram("timeline\n : orphan event")).toThrow(
111
+ 'Timeline continuation requires a preceding period in timeline diagram at line 2: ": orphan event"',
112
+ )
113
+ })
114
+
115
+ test("reports unsupported GitGraph operations with source diagnostics", () => {
116
+ expect(() => renderGitGraphDiagram("gitGraph\n cherry-pick id: missing")).toThrow(
117
+ 'Cherry-pick is not supported in gitGraph diagram at line 2: "cherry-pick id: missing"',
118
+ )
119
+ })
120
+
121
+ test("does not attach else through an unclosed nested sequence block", () => {
122
+ expect(() =>
123
+ parseMermaidSequenceDiagram(`sequenceDiagram
124
+ alt available
125
+ loop retry
126
+ else fallback`),
127
+ ).toThrow('Unexpected "else" without an open "alt" block in sequence diagram at line 4: "else fallback"')
128
+ })
129
+ })
@@ -0,0 +1,32 @@
1
+ import { expect } from "bun:test"
2
+
3
+ function normalizeDiagram(value: string): string {
4
+ const lines = value.replace(/\r\n/g, "\n").split("\n")
5
+ while (lines[0]?.trim() === "") lines.shift()
6
+ while (lines[lines.length - 1]?.trim() === "") lines.pop()
7
+ const indentation = lines
8
+ .filter((line) => line.trim().length > 0)
9
+ .reduce((min, line) => Math.min(min, line.match(/^\s*/)?.[0].length ?? 0), Number.POSITIVE_INFINITY)
10
+ const trimBy = Number.isFinite(indentation) ? indentation : 0
11
+ return lines.map((line) => line.slice(trimBy)).join("\n")
12
+ }
13
+
14
+ export function expectDiagram(value: string): {
15
+ toEqualDiagram(expected: string): void
16
+ toContainInOrder(...needles: string[]): void
17
+ } {
18
+ return {
19
+ toEqualDiagram(expected) {
20
+ expect(value).toBe(normalizeDiagram(expected))
21
+ },
22
+ toContainInOrder(...needles) {
23
+ let offset = -1
24
+ for (const needle of needles) {
25
+ const searchSpace = value.slice(offset + 1)
26
+ expect(searchSpace).toContain(needle)
27
+ const nextOffset = value.indexOf(needle, offset + 1)
28
+ offset = nextOffset
29
+ }
30
+ },
31
+ }
32
+ }