@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,8 @@
1
+ import { drawSequenceDiagramGrid } from "./drawing.js"
2
+ import { parseMermaidSequenceDiagram } from "./parser.js"
3
+ import { renderSequenceGridText } from "./render-grid.js"
4
+ import type { SequenceDiagramRenderOptions } from "./types.js"
5
+
6
+ export function renderSequenceDiagram(content: string, options: SequenceDiagramRenderOptions = {}): string {
7
+ return renderSequenceGridText(drawSequenceDiagramGrid(parseMermaidSequenceDiagram(content), options))
8
+ }
@@ -0,0 +1,287 @@
1
+ import { BorderChars, type BorderStyle } from "@opentui/core"
2
+ import { DiagramCanvas } from "../core/canvas.js"
3
+ import { diagramTextWidth } from "../core/text.js"
4
+ import { DEFAULT_FRAGMENT_BORDER_STYLE } from "./options.js"
5
+ import {
6
+ createSequencePlacementPlan,
7
+ type SequenceGroupPlacement,
8
+ type SequenceHorizontalBounds,
9
+ type SequenceStepPlacement,
10
+ } from "./placement.js"
11
+ import type { SequenceGrid } from "./render-grid.js"
12
+ import { SEQUENCE_FADE_STEPS as FADE_STEPS } from "./style.js"
13
+ import type {
14
+ MessageStyle,
15
+ SequenceArrowHead,
16
+ SequenceCellStyle,
17
+ SequenceDiagram,
18
+ SequenceDiagramRenderOptions,
19
+ } from "./types.js"
20
+
21
+ const SEQUENCE_BORDER = BorderChars.rounded
22
+
23
+ function centeredStart(center: number, text: string): number {
24
+ return center - Math.floor(diagramTextWidth(text) / 2)
25
+ }
26
+
27
+ function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1): string {
28
+ switch (head) {
29
+ case "open":
30
+ return direction === 1 ? ">" : "<"
31
+ case "cross":
32
+ return "✕"
33
+ case "async":
34
+ return direction === 1 ? ")" : "("
35
+ default:
36
+ return direction === 1 ? "►" : "◄"
37
+ }
38
+ }
39
+
40
+ function createGrid(width: number, height: number): SequenceGrid {
41
+ return new DiagramCanvas(width, height)
42
+ }
43
+
44
+ function setCell(grid: SequenceGrid, x: number, y: number, char: string, style?: SequenceCellStyle): void {
45
+ grid.setCell(x, y, char, style)
46
+ }
47
+
48
+ function setText(grid: SequenceGrid, x: number, y: number, text: string, style?: SequenceCellStyle): void {
49
+ grid.setText(Math.max(0, x), y, text, style)
50
+ }
51
+
52
+ function setArrowDepartureFade(
53
+ grid: SequenceGrid,
54
+ x: number,
55
+ y: number,
56
+ direction: 1 | -1,
57
+ style: SequenceCellStyle,
58
+ ): void {
59
+ setCell(
60
+ grid,
61
+ x,
62
+ y,
63
+ direction === 1 ? SEQUENCE_BORDER.leftT : SEQUENCE_BORDER.rightT,
64
+ `${style}Fade1` as SequenceCellStyle,
65
+ )
66
+ for (let step = 2; step <= 5; step++) {
67
+ setCell(grid, x + direction * (step - 1), y, SEQUENCE_BORDER.horizontal, `${style}Fade${step}` as SequenceCellStyle)
68
+ }
69
+ }
70
+
71
+ function groupVerticalChar(existing: string | undefined): string | undefined {
72
+ switch (existing) {
73
+ case undefined:
74
+ case " ":
75
+ return SEQUENCE_BORDER.vertical
76
+ case SEQUENCE_BORDER.vertical:
77
+ return SEQUENCE_BORDER.vertical
78
+ default:
79
+ return undefined
80
+ }
81
+ }
82
+
83
+ function setGroupVerticalCell(grid: SequenceGrid, x: number, y: number): void {
84
+ const existing = grid.getCell(x, y)?.char
85
+ const char = groupVerticalChar(existing)
86
+ if (char) setCell(grid, x, y, char, "group")
87
+ }
88
+
89
+ function renderParticipantGroups(
90
+ grid: SequenceGrid,
91
+ groupBounds: readonly SequenceGroupPlacement[],
92
+ bottomY: number,
93
+ ): void {
94
+ for (const bounds of groupBounds) {
95
+ for (let x = bounds.leftX; x <= bounds.rightX; x++) {
96
+ setCell(grid, x, 0, SEQUENCE_BORDER.horizontal, "group")
97
+ setCell(grid, x, bottomY, SEQUENCE_BORDER.horizontal, "group")
98
+ }
99
+
100
+ setCell(grid, bounds.leftX, 0, SEQUENCE_BORDER.topLeft, "group")
101
+ setCell(grid, bounds.rightX, 0, SEQUENCE_BORDER.topRight, "group")
102
+ setCell(grid, bounds.leftX, bottomY, SEQUENCE_BORDER.bottomLeft, "group")
103
+ setCell(grid, bounds.rightX, bottomY, SEQUENCE_BORDER.bottomRight, "group")
104
+
105
+ for (let y = 1; y < bottomY; y++) {
106
+ setGroupVerticalCell(grid, bounds.leftX, y)
107
+ setGroupVerticalCell(grid, bounds.rightX, y)
108
+ }
109
+
110
+ if (bounds.labelText) {
111
+ setText(grid, bounds.leftX + 2, 0, bounds.labelText, "group")
112
+ }
113
+ }
114
+ }
115
+
116
+ function drawFragmentWalls(
117
+ grid: SequenceGrid,
118
+ bounds: SequenceHorizontalBounds,
119
+ startY: number,
120
+ endY: number,
121
+ borderStyle: BorderStyle,
122
+ ): void {
123
+ if (endY < startY) return
124
+ const border = BorderChars[borderStyle]
125
+
126
+ for (let y = startY; y <= endY; y++) {
127
+ setCell(grid, bounds.leftX, y, border.vertical, "fragment")
128
+ setCell(grid, bounds.rightX, y, border.vertical, "fragment")
129
+ }
130
+ }
131
+
132
+ function renderFragment(
133
+ grid: SequenceGrid,
134
+ placement: Extract<SequenceStepPlacement, { type: "fragment" }>,
135
+ borderStyle: BorderStyle,
136
+ ): void {
137
+ const { bounds, fragment, labelText: label, y } = placement
138
+ const border = BorderChars[borderStyle]
139
+ const { leftX, rightX } = bounds
140
+
141
+ const leftChar =
142
+ fragment.kind === "alt" || fragment.kind === "loop"
143
+ ? border.topLeft
144
+ : fragment.kind === "else"
145
+ ? border.leftT
146
+ : border.bottomLeft
147
+ const rightChar =
148
+ fragment.kind === "alt" || fragment.kind === "loop"
149
+ ? border.topRight
150
+ : fragment.kind === "else"
151
+ ? border.rightT
152
+ : border.bottomRight
153
+
154
+ for (let x = leftX; x <= rightX; x++) {
155
+ setCell(grid, x, y, border.horizontal, "fragment")
156
+ }
157
+
158
+ setCell(grid, leftX, y, leftChar, "fragment")
159
+ setCell(grid, rightX, y, rightChar, "fragment")
160
+ if (label) {
161
+ setText(grid, leftX + 2, y, label, "fragmentLabel")
162
+ }
163
+ }
164
+
165
+ function renderSelfMessage(
166
+ grid: SequenceGrid,
167
+ placement: Extract<SequenceStepPlacement, { type: "selfMessage" }>,
168
+ style: MessageStyle,
169
+ ): void {
170
+ const { centerX, rightX, topY: topRow, bottomY: bottomRow, labelLines, message } = placement
171
+
172
+ setArrowDepartureFade(grid, centerX, topRow, 1, style)
173
+ for (let x = centerX + FADE_STEPS.length; x < rightX; x++) {
174
+ setCell(grid, x, topRow, SEQUENCE_BORDER.horizontal, style)
175
+ }
176
+ setCell(grid, rightX, topRow, SEQUENCE_BORDER.topRight, style)
177
+
178
+ for (let lineIndex = 0; lineIndex < labelLines.length; lineIndex++) {
179
+ const y = topRow + lineIndex + 1
180
+ setCell(grid, centerX, y, SEQUENCE_BORDER.vertical, "lifeline")
181
+ setText(grid, centerX + 2, y, labelLines[lineIndex]!, style)
182
+ setCell(grid, rightX, y, SEQUENCE_BORDER.vertical, style)
183
+ }
184
+
185
+ for (let x = centerX + 1; x < rightX; x++) {
186
+ setCell(grid, x, bottomRow, SEQUENCE_BORDER.horizontal, style)
187
+ }
188
+ const headX = message.head === undefined ? centerX : centerX + 1
189
+ setCell(grid, headX, bottomRow, arrowHeadChar(message.head, -1), style)
190
+ setCell(grid, rightX, bottomRow, SEQUENCE_BORDER.bottomRight, style)
191
+ }
192
+
193
+ function renderNote(grid: SequenceGrid, placement: Extract<SequenceStepPlacement, { type: "note" }>): void {
194
+ placement.textLines.forEach((line, index) =>
195
+ setText(grid, placement.textX, placement.textY + index, line, "noteBadge"),
196
+ )
197
+ }
198
+
199
+ export function drawSequenceDiagramGrid(
200
+ diagram: SequenceDiagram,
201
+ options: SequenceDiagramRenderOptions = {},
202
+ ): SequenceGrid {
203
+ const plan = createSequencePlacementPlan(diagram, options)
204
+ if (plan.width === 0 || plan.height === 0) return createGrid(0, 0)
205
+ const fragmentBorderStyle = options.fragmentBorderStyle ?? DEFAULT_FRAGMENT_BORDER_STYLE
206
+ const grid = createGrid(plan.width, plan.height)
207
+
208
+ if (plan.groups.length > 0) renderParticipantGroups(grid, plan.groups, plan.height - 1)
209
+
210
+ for (const placement of plan.participants) {
211
+ const { centerX: center, headerLeftX, headerRightX, labelLines } = placement
212
+ const { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY } = plan.rows
213
+
214
+ if (options.compact) {
215
+ labelLines.forEach((line, index) =>
216
+ setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
217
+ )
218
+ } else {
219
+ labelLines.forEach((line, index) =>
220
+ setText(grid, centeredStart(center, line), participantHeaderTopY + index, line, "participant"),
221
+ )
222
+ for (let x = headerLeftX; x <= headerRightX; x++) {
223
+ setCell(grid, x, participantRuleY, SEQUENCE_BORDER.horizontal, "participant")
224
+ }
225
+ setCell(grid, center, participantRuleY, SEQUENCE_BORDER.topT, "participant")
226
+ }
227
+
228
+ for (let y = lifelineStartY; y <= lifelineEndY; y++) {
229
+ const distance = y - lifelineStartY
230
+ const style = !options.compact && distance < 3 ? (`lifelineRamp${distance + 1}` as SequenceCellStyle) : "lifeline"
231
+ setCell(grid, center, y, SEQUENCE_BORDER.vertical, style)
232
+ }
233
+ }
234
+
235
+ for (const placement of plan.steps) {
236
+ if (placement.type === "note") {
237
+ renderNote(grid, placement)
238
+ continue
239
+ }
240
+
241
+ if (placement.type === "fragment") {
242
+ if (placement.wallsBefore) {
243
+ drawFragmentWalls(
244
+ grid,
245
+ placement.wallsBefore.bounds,
246
+ placement.wallsBefore.startY,
247
+ placement.wallsBefore.endY,
248
+ fragmentBorderStyle,
249
+ )
250
+ }
251
+ renderFragment(grid, placement, fragmentBorderStyle)
252
+ continue
253
+ }
254
+
255
+ const message = placement.message
256
+ const messageStyle: MessageStyle = message.style === "dashed" ? "response" : "request"
257
+
258
+ if (placement.type === "selfMessage") {
259
+ renderSelfMessage(grid, placement, messageStyle)
260
+ continue
261
+ }
262
+
263
+ if (!placement.inlineLabel) {
264
+ for (let lineIndex = 0; lineIndex < placement.labelLines.length; lineIndex++) {
265
+ setText(grid, placement.labelX, placement.labelY + lineIndex, placement.labelLines[lineIndex]!, messageStyle)
266
+ }
267
+ }
268
+
269
+ for (let x = placement.leftX + 1; x < placement.rightX; x++) {
270
+ setCell(grid, x, placement.arrowY, SEQUENCE_BORDER.horizontal, messageStyle)
271
+ }
272
+
273
+ setArrowDepartureFade(grid, placement.fromX, placement.arrowY, placement.direction, messageStyle)
274
+ setCell(grid, placement.headX, placement.arrowY, arrowHeadChar(message.head, placement.direction), messageStyle)
275
+ if (placement.inlineLabel) setText(grid, placement.labelX, placement.labelY, placement.inlineLabel, messageStyle)
276
+ }
277
+
278
+ for (const activation of plan.activations) {
279
+ for (let y = activation.startY; y <= activation.endY; y++) {
280
+ if (grid.getCell(activation.centerX, y)?.char === SEQUENCE_BORDER.vertical) {
281
+ setCell(grid, activation.centerX, y, "┃", "lifeline")
282
+ }
283
+ }
284
+ }
285
+
286
+ return grid
287
+ }
@@ -0,0 +1,8 @@
1
+ import type { BorderStyle } from "@opentui/core"
2
+
3
+ export const DEFAULT_MIN_PARTICIPANT_GAP = 18
4
+ export const DEFAULT_FRAGMENT_BORDER_STYLE = "rounded" satisfies BorderStyle
5
+
6
+ export function normalizeSequenceMinParticipantGap(value: number | undefined): number {
7
+ return value === undefined || !Number.isFinite(value) ? DEFAULT_MIN_PARTICIPANT_GAP : Math.max(1, Math.floor(value))
8
+ }
@@ -0,0 +1,282 @@
1
+ import {
2
+ firstMeaningfulMermaidLine,
3
+ meaningfulNumberedMermaidLines,
4
+ stripMermaidQuotes as stripQuotes,
5
+ } from "../core/mermaid.js"
6
+ import { MermaidSyntaxError } from "../diagnostics.js"
7
+ import type {
8
+ SequenceArrowHead,
9
+ SequenceDiagram,
10
+ SequenceMessage,
11
+ SequenceParticipant,
12
+ SequenceParticipantGroup,
13
+ SequenceStep,
14
+ } from "./types.js"
15
+
16
+ const MESSAGE_RE = /^(.+?)\s*(-->>|->>|--x|-x|--\)|-\)|-->|->)([+-]?)\s*(.+?)\s*:\s*(.*)$/
17
+ const NOTE_RE = /^note\s+(over|left\s+of|right\s+of)\s+(.+?)\s*:\s*(.*)$/i
18
+ const PARTICIPANT_RE = /^(?:participant|actor)\s+(\S+)(?:\s+as\s+(.+))?$/i
19
+ const ACTIVATION_RE = /^(activate|deactivate)\s+(.+)$/i
20
+ const BOX_RE = /^box(?:\s+(.+))?$/i
21
+ const ALT_RE = /^alt\s+(.+)$/i
22
+ const ELSE_RE = /^else(?:\s+(.+))?$/i
23
+ const LOOP_RE = /^loop\s+(.+)$/i
24
+ const AUTONUMBER_RE = /^autonumber(?:\s+(\d+)(?:\s+(\d+))?)?$/i
25
+ const UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE = /<<-{1,2}>>/
26
+ const MESSAGE_OPERATOR_RE = /-->>|->>|--x|-x|--\)|-\)|-->|->/
27
+ const CSS_COLOR_NAMES = new Set([
28
+ "black",
29
+ "white",
30
+ "red",
31
+ "green",
32
+ "blue",
33
+ "yellow",
34
+ "cyan",
35
+ "magenta",
36
+ "silver",
37
+ "gray",
38
+ "grey",
39
+ "maroon",
40
+ "olive",
41
+ "lime",
42
+ "aqua",
43
+ "teal",
44
+ "navy",
45
+ "fuchsia",
46
+ "purple",
47
+ "orange",
48
+ "brightblack",
49
+ "brightred",
50
+ "brightgreen",
51
+ "brightblue",
52
+ "brightyellow",
53
+ "brightcyan",
54
+ "brightmagenta",
55
+ "brightwhite",
56
+ ])
57
+
58
+ function arrowHeadForSyntax(arrow: string): SequenceArrowHead | undefined {
59
+ if (arrow.endsWith("x")) return "cross"
60
+ if (arrow.endsWith(")")) return "async"
61
+ if (arrow.endsWith(">") && !arrow.endsWith(">>")) return "open"
62
+ return undefined
63
+ }
64
+
65
+ function isBoxColorToken(value: string): boolean {
66
+ const lowerValue = value.toLowerCase()
67
+ return (
68
+ lowerValue === "transparent" ||
69
+ CSS_COLOR_NAMES.has(lowerValue) ||
70
+ /^#[0-9a-f]{3,8}$/i.test(value) ||
71
+ /^rgba?\(.+\)$/i.test(value)
72
+ )
73
+ }
74
+
75
+ function splitLeadingBoxToken(value: string): { token: string; rest: string } {
76
+ if (/^rgba?\(/i.test(value)) {
77
+ const closeIndex = value.indexOf(")")
78
+ if (closeIndex >= 0) {
79
+ return { token: value.slice(0, closeIndex + 1), rest: value.slice(closeIndex + 1).trim() }
80
+ }
81
+ }
82
+
83
+ const firstSpace = value.search(/\s/)
84
+ return firstSpace < 0
85
+ ? { token: value, rest: "" }
86
+ : { token: value.slice(0, firstSpace), rest: value.slice(firstSpace + 1).trim() }
87
+ }
88
+
89
+ function boxLabelText(value: string | undefined): string {
90
+ const rawLabel = (value ?? "").trim()
91
+ if ((rawLabel.startsWith('"') && rawLabel.endsWith('"')) || (rawLabel.startsWith("'") && rawLabel.endsWith("'"))) {
92
+ return stripQuotes(rawLabel)
93
+ }
94
+
95
+ const label = stripQuotes(rawLabel)
96
+ if (!label) return ""
97
+ const { token, rest } = splitLeadingBoxToken(label)
98
+ return isBoxColorToken(token) ? stripQuotes(rest) : label
99
+ }
100
+
101
+ function addParticipantToGroup(group: SequenceParticipantGroup | undefined, participantId: string): void {
102
+ if (!group || group.participantIds.includes(participantId)) return
103
+ group.participantIds.push(participantId)
104
+ }
105
+
106
+ function ensureParticipant(
107
+ participants: SequenceParticipant[],
108
+ id: string,
109
+ label: string = id,
110
+ replaceExistingLabel: boolean = false,
111
+ ): void {
112
+ const existing = participants.find((participant) => participant.id === id)
113
+ if (existing) {
114
+ if (replaceExistingLabel) existing.label = label
115
+ return
116
+ }
117
+ participants.push({ id, label })
118
+ }
119
+
120
+ export function isMermaidSequenceDiagram(content: string): boolean {
121
+ return firstMeaningfulMermaidLine(content)?.toLowerCase() === "sequencediagram"
122
+ }
123
+
124
+ export function parseMermaidSequenceDiagram(content: string): SequenceDiagram {
125
+ const participants: SequenceParticipant[] = []
126
+ const messages: SequenceMessage[] = []
127
+ const steps: SequenceStep[] = []
128
+ const groups: SequenceParticipantGroup[] = []
129
+ const blockStack: Array<{ kind: "box" | "alt" | "loop"; lineNumber: number; sourceLine: string }> = []
130
+ const groupStack: SequenceParticipantGroup[] = []
131
+ let nextMessageNumber: number | undefined
132
+ let messageNumberIncrement = 1
133
+
134
+ for (const source of meaningfulNumberedMermaidLines(content)) {
135
+ const line = source.text
136
+ if (line.toLowerCase() === "sequencediagram") continue
137
+ if (UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE.test(line)) {
138
+ throw new MermaidSyntaxError("sequence", source.lineNumber, line)
139
+ }
140
+
141
+ const autonumberMatch = line.match(AUTONUMBER_RE)
142
+ if (autonumberMatch) {
143
+ nextMessageNumber = Number.parseInt(autonumberMatch[1] ?? "1", 10)
144
+ messageNumberIncrement = Number.parseInt(autonumberMatch[2] ?? "1", 10)
145
+ continue
146
+ }
147
+
148
+ const boxMatch = line.match(BOX_RE)
149
+ if (boxMatch) {
150
+ const group: SequenceParticipantGroup = { label: boxLabelText(boxMatch[1]), participantIds: [] }
151
+ groups.push(group)
152
+ groupStack.push(group)
153
+ blockStack.push({ kind: "box", lineNumber: source.lineNumber, sourceLine: line })
154
+ continue
155
+ }
156
+
157
+ const participantMatch = line.match(PARTICIPANT_RE)
158
+ if (participantMatch) {
159
+ const id = stripQuotes(participantMatch[1]!)
160
+ ensureParticipant(participants, id, stripQuotes(participantMatch[2] ?? id), true)
161
+ addParticipantToGroup(groupStack[groupStack.length - 1], id)
162
+ continue
163
+ }
164
+
165
+ const noteMatch = line.match(NOTE_RE)
166
+ if (noteMatch) {
167
+ const position = noteMatch[1]!.toLowerCase().replace(/\s+of$/, "") as "over" | "left" | "right"
168
+ const over = noteMatch[2]!
169
+ .split(",")
170
+ .map((participant) => stripQuotes(participant))
171
+ .filter((participant) => participant.length > 0)
172
+ for (const participant of over) ensureParticipant(participants, participant)
173
+ steps.push({
174
+ type: "note",
175
+ note: {
176
+ over,
177
+ label: stripQuotes(noteMatch[3]!),
178
+ ...(position === "over" ? {} : { position }),
179
+ },
180
+ })
181
+ continue
182
+ }
183
+
184
+ const activationMatch = line.match(ACTIVATION_RE)
185
+ if (activationMatch) {
186
+ const participant = stripQuotes(activationMatch[2]!)
187
+ ensureParticipant(participants, participant)
188
+ steps.push({
189
+ type: "activation",
190
+ activation: { participant, active: activationMatch[1]!.toLowerCase() === "activate" },
191
+ })
192
+ continue
193
+ }
194
+
195
+ const altMatch = line.match(ALT_RE)
196
+ if (altMatch) {
197
+ blockStack.push({ kind: "alt", lineNumber: source.lineNumber, sourceLine: line })
198
+ steps.push({ type: "fragment", fragment: { kind: "alt", label: stripQuotes(altMatch[1]!) } })
199
+ continue
200
+ }
201
+
202
+ const loopMatch = line.match(LOOP_RE)
203
+ if (loopMatch) {
204
+ blockStack.push({ kind: "loop", lineNumber: source.lineNumber, sourceLine: line })
205
+ steps.push({ type: "fragment", fragment: { kind: "loop", label: stripQuotes(loopMatch[1]!) } })
206
+ continue
207
+ }
208
+
209
+ const elseMatch = line.match(ELSE_RE)
210
+ if (elseMatch) {
211
+ if (blockStack[blockStack.length - 1]?.kind !== "alt") {
212
+ throw new MermaidSyntaxError(
213
+ "sequence",
214
+ source.lineNumber,
215
+ line,
216
+ 'Unexpected "else" without an open "alt" block',
217
+ )
218
+ }
219
+ steps.push({ type: "fragment", fragment: { kind: "else", label: stripQuotes(elseMatch[1] ?? "") } })
220
+ continue
221
+ }
222
+
223
+ if (line.toLowerCase() === "end") {
224
+ const block = blockStack.pop()
225
+ if (!block)
226
+ throw new MermaidSyntaxError("sequence", source.lineNumber, line, 'Unexpected "end" without an open block')
227
+ if (block.kind === "box") {
228
+ groupStack.pop()
229
+ continue
230
+ }
231
+ steps.push({ type: "fragment", fragment: { kind: "end", label: block.kind } })
232
+ continue
233
+ }
234
+
235
+ const messageMatch = line.match(MESSAGE_RE)
236
+ if (messageMatch) {
237
+ const from = stripQuotes(messageMatch[1]!)
238
+ const arrow = messageMatch[2]!
239
+ const activationMarker = messageMatch[3]!
240
+ const to = stripQuotes(messageMatch[4]!)
241
+ if (MESSAGE_OPERATOR_RE.test(from) || MESSAGE_OPERATOR_RE.test(to)) {
242
+ throw new MermaidSyntaxError("sequence", source.lineNumber, line)
243
+ }
244
+ const message: SequenceMessage = {
245
+ from,
246
+ to,
247
+ label: stripQuotes(messageMatch[5]!),
248
+ style: arrow.startsWith("--") ? "dashed" : "solid",
249
+ }
250
+ const activeGroup = groupStack[groupStack.length - 1]
251
+ ensureParticipant(participants, from)
252
+ ensureParticipant(participants, to)
253
+ addParticipantToGroup(activeGroup, from)
254
+ addParticipantToGroup(activeGroup, to)
255
+ const head = arrowHeadForSyntax(arrow)
256
+ if (head) message.head = head
257
+ if (nextMessageNumber !== undefined) {
258
+ message.number = nextMessageNumber
259
+ nextMessageNumber += messageNumberIncrement
260
+ }
261
+ if (activationMarker === "+") message.activate = to
262
+ else if (activationMarker === "-") message.deactivate = from
263
+ messages.push(message)
264
+ steps.push({ type: "message", message })
265
+ continue
266
+ }
267
+
268
+ throw new MermaidSyntaxError("sequence", source.lineNumber, line)
269
+ }
270
+
271
+ const unclosedBlock = blockStack[blockStack.length - 1]
272
+ if (unclosedBlock) {
273
+ throw new MermaidSyntaxError(
274
+ "sequence",
275
+ unclosedBlock.lineNumber,
276
+ unclosedBlock.sourceLine,
277
+ `Unclosed ${unclosedBlock.kind} block; expected "end"`,
278
+ )
279
+ }
280
+
281
+ return { participants, messages, steps, groups }
282
+ }