@node-projects/web-component-designer-mermaid 0.1.0

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.
@@ -0,0 +1,2473 @@
1
+ import { DesignItem, IDesignItem, IHtmlParserService, IHtmlWriterOptions, IHtmlWriterService, InstanceServiceContainer, ITextWriter, ServiceContainer } from "@node-projects/web-component-designer";
2
+ import { MermaidEdge } from "../widgets/mermaid-edge.js";
3
+ import { MermaidNode, normalizeLabelLineBreaks } from "../widgets/mermaid-node.js";
4
+ import { MermaidSequenceMessage } from "../widgets/mermaid-sequence-message.js";
5
+ import { MermaidSequenceParticipant } from "../widgets/mermaid-sequence-participant.js";
6
+ import { MermaidMindmapNode } from "../widgets/mermaid-mindmap-node.js";
7
+ import { MermaidRequirementNode } from "../widgets/mermaid-requirement-node.js";
8
+ import { MermaidRequirementRelationship } from "../widgets/mermaid-requirement-relationship.js";
9
+ import { MermaidSubgraph } from "../widgets/mermaid-subgraph.js";
10
+ import { MermaidFlowchartDirective } from "../widgets/mermaid-flowchart-directive.js";
11
+ import { getMermaidDocumentDiagramType, getMermaidDocumentFrontmatter, getMermaidDocumentTitle, mermaidDiagramTypeAttribute, mermaidFlowchartDirectionAttribute, mermaidFrontmatterAttribute, mermaidTitleAttribute, MermaidDocumentDiagramType } from "./MermaidDocumentPropertiesService.js";
12
+ import { encodeWaypoints, FlowchartDirection, routeBetweenBounds } from "./mermaidGeometry.js";
13
+
14
+ type ParsedNode = {
15
+ id: string;
16
+ label: string;
17
+ shape: string;
18
+ parentId?: string;
19
+ classes?: string;
20
+ style?: string;
21
+ sourceRange?: { start: number; length: number };
22
+ }
23
+
24
+ type ParsedEdge = {
25
+ from: string;
26
+ to: string;
27
+ fromNode?: ParsedNode;
28
+ toNode?: ParsedNode;
29
+ label: string;
30
+ edgeType: string;
31
+ connector?: string;
32
+ edgeId?: string;
33
+ animation?: string;
34
+ connectorRange?: { start: number; length: number };
35
+ sourceRange?: { start: number; length: number };
36
+ }
37
+
38
+ type ParsedSubgraph = {
39
+ id: string;
40
+ title: string;
41
+ parentId?: string;
42
+ direction?: FlowchartDirection;
43
+ sourceRange?: { start: number; length: number };
44
+ }
45
+
46
+ type ParsedFlowchartDirective = {
47
+ line: string;
48
+ sourceRange?: { start: number; length: number };
49
+ }
50
+
51
+ type ParsedSequenceParticipant = {
52
+ id: string;
53
+ label: string;
54
+ participantType: string;
55
+ implicit?: boolean;
56
+ sourceRange?: { start: number; length: number };
57
+ }
58
+
59
+ type ParsedSequenceMessage = {
60
+ from: string;
61
+ to: string;
62
+ label: string;
63
+ messageType: string;
64
+ connector: string;
65
+ sourceRange?: { start: number; length: number };
66
+ }
67
+
68
+ type ParsedMindmapNode = {
69
+ id: string;
70
+ parentId: string;
71
+ label: string;
72
+ shape: string;
73
+ indent: number;
74
+ sourceRange?: { start: number; length: number };
75
+ }
76
+
77
+ type ParsedRequirementNode = {
78
+ id: string;
79
+ kind: "requirement" | "element";
80
+ requirementType?: string;
81
+ requirementId?: string;
82
+ text?: string;
83
+ risk?: string;
84
+ verifyMethod?: string;
85
+ elementType?: string;
86
+ docRef?: string;
87
+ sourceRange?: { start: number; length: number };
88
+ }
89
+
90
+ type ParsedRequirementRelationship = {
91
+ from: string;
92
+ to: string;
93
+ relationshipType: string;
94
+ syntaxDirection: "forward" | "reverse";
95
+ sourceRange?: { start: number; length: number };
96
+ }
97
+
98
+ type LineRecord = {
99
+ text: string;
100
+ trimmed: string;
101
+ indent: number;
102
+ start: number;
103
+ }
104
+
105
+ type ParsedMermaidDocument = {
106
+ lines: LineRecord[];
107
+ title: string;
108
+ frontmatter: string;
109
+ }
110
+
111
+ export class MermaidParserService implements IHtmlParserService, IHtmlWriterService {
112
+ options: IHtmlWriterOptions = {};
113
+ supportsRootItemWrite = true;
114
+
115
+ async parse(html: string, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer, parseSnippet: boolean): Promise<IDesignItem[]> {
116
+ const diagramKind = getDiagramKind(readMermaidDocument(html));
117
+ if (diagramKind === "sequence")
118
+ return parseSequenceDiagram(html, serviceContainer, instanceServiceContainer);
119
+ if (diagramKind === "mindmap")
120
+ return parseMindmapDiagram(html, serviceContainer, instanceServiceContainer);
121
+ if (diagramKind === "requirementDiagram")
122
+ return parseRequirementDiagram(html, serviceContainer, instanceServiceContainer);
123
+ return parseFlowchart(html, serviceContainer, instanceServiceContainer);
124
+ }
125
+
126
+ write(textWriter: ITextWriter, designItems: IDesignItem[], rootContainerKeepInline: boolean, updatePositions?: boolean) {
127
+ const rootDesignItem = getRootDesignItem(designItems);
128
+ const mermaidDesignItems = getMermaidDesignItems(designItems);
129
+ const documentType = getWritableDocumentDiagramType(mermaidDesignItems.length ? mermaidDesignItems : designItems);
130
+ if (documentType === "mindmap") {
131
+ writeMindmapDiagram(textWriter, mermaidDesignItems, updatePositions, rootDesignItem);
132
+ return;
133
+ }
134
+ if (documentType === "sequenceDiagram") {
135
+ writeSequenceDiagram(textWriter, mermaidDesignItems, updatePositions, rootDesignItem);
136
+ return;
137
+ }
138
+ if (documentType === "requirementDiagram") {
139
+ writeRequirementDiagram(textWriter, mermaidDesignItems, updatePositions, rootDesignItem);
140
+ return;
141
+ }
142
+
143
+ writeFlowchart(textWriter, mermaidDesignItems, updatePositions, rootDesignItem);
144
+ }
145
+ }
146
+
147
+ function getDiagramKind(document: ParsedMermaidDocument) {
148
+ const firstMeaningfulLine = document.lines.find(line => line.trimmed && !line.trimmed.startsWith("%%"))?.trimmed ?? "";
149
+ if (equalsIgnoreCase(firstMeaningfulLine, "sequenceDiagram"))
150
+ return "sequence";
151
+ if (equalsIgnoreCase(firstMeaningfulLine, "mindmap"))
152
+ return "mindmap";
153
+ if (equalsIgnoreCase(firstMeaningfulLine, "requirementDiagram"))
154
+ return "requirementDiagram";
155
+ return "flowchart";
156
+ }
157
+
158
+ async function parseFlowchart(html: string, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): Promise<IDesignItem[]> {
159
+ const document = readMermaidDocument(html);
160
+ const lines = document.lines;
161
+ const designItems: IDesignItem[] = [];
162
+ const nodes = new Map<string, ParsedNode>();
163
+ const nodeBounds = new Map<string, { x: number; y: number; width: number; height: number }>();
164
+ const edges: ParsedEdge[] = [];
165
+ const subgraphs = new Map<string, ParsedSubgraph>();
166
+ const directives: ParsedFlowchartDirective[] = [];
167
+ const subgraphStack: ParsedSubgraph[] = [];
168
+ let direction: FlowchartDirection = "TD";
169
+ const scannedNodes = new Map<string, ParsedNode>();
170
+ const scannedEdges: ParsedEdge[] = [];
171
+
172
+ for (const line of lines) {
173
+ if (!line.trimmed || line.trimmed.startsWith("%%"))
174
+ continue;
175
+
176
+ const subgraph = parseSubgraphStart(line.trimmed, line.start, subgraphStack[subgraphStack.length - 1]?.id);
177
+ if (subgraph) {
178
+ subgraphs.set(subgraph.id, subgraph);
179
+ subgraphStack.push(subgraph);
180
+ continue;
181
+ }
182
+
183
+ if (equalsIgnoreCase(line.trimmed, "end")) {
184
+ subgraphStack.pop();
185
+ continue;
186
+ }
187
+
188
+ const directive = parseFlowchartDirective(line.trimmed, line.start);
189
+ if (directive) {
190
+ directives.push(directive);
191
+ continue;
192
+ }
193
+
194
+ const parsedDirection = parseFlowchartDirection(line.trimmed);
195
+ if (parsedDirection) {
196
+ if (subgraphStack.length)
197
+ subgraphStack[subgraphStack.length - 1].direction = parsedDirection;
198
+ else
199
+ direction = parsedDirection;
200
+ continue;
201
+ }
202
+ const parsedSubgraphDirection = parseDirectionStatement(line.trimmed);
203
+ if (parsedSubgraphDirection && subgraphStack.length) {
204
+ subgraphStack[subgraphStack.length - 1].direction = parsedSubgraphDirection;
205
+ continue;
206
+ }
207
+
208
+ const edge = parseEdge(line.trimmed, line.start);
209
+ if (edge) {
210
+ scannedEdges.push(edge);
211
+ mergeNode(scannedNodes, edge.fromNode);
212
+ mergeNode(scannedNodes, edge.toNode);
213
+ continue;
214
+ }
215
+
216
+ const node = parseNode(line.trimmed, line.start);
217
+ if (node) {
218
+ node.parentId = subgraphStack[subgraphStack.length - 1]?.id;
219
+ mergeNode(scannedNodes, node);
220
+ }
221
+ }
222
+
223
+ setMermaidDocumentAttributes(instanceServiceContainer, "flowchart", direction, document.title, document.frontmatter);
224
+ const parsed = await getMermaidFlowchartData(html);
225
+ if (parsed) {
226
+ for (const node of parsed.nodes) {
227
+ const scanned = scannedNodes.get(node.id);
228
+ mergeNode(nodes, { ...node, parentId: scanned?.parentId, classes: scanned?.classes, style: scanned?.style, sourceRange: scanned?.sourceRange });
229
+ }
230
+ for (const edge of parsed.edges) {
231
+ const scanned = getScannedEdge(scannedEdges, edge);
232
+ edges.push({ ...edge, ...scanned });
233
+ }
234
+ } else {
235
+ for (const node of scannedNodes.values())
236
+ mergeNode(nodes, node);
237
+ edges.push(...scannedEdges);
238
+ }
239
+
240
+ const mermaidLayout = await getMermaidLayout(html, nodes);
241
+ const designItemsById = new Map<string, IDesignItem>();
242
+ let subgraphIndex = 0;
243
+ for (const subgraph of subgraphs.values()) {
244
+ const layout = mermaidLayout?.subgraphs?.get(subgraph.id);
245
+ const element = new MermaidSubgraph();
246
+ element.style.position = "absolute";
247
+ element.style.left = (layout?.x ?? (30 + subgraphIndex * 40)) + "px";
248
+ element.style.top = (layout?.y ?? (30 + subgraphIndex * 40)) + "px";
249
+ element.style.width = (layout?.width ?? 360) + "px";
250
+ element.style.height = (layout?.height ?? 240) + "px";
251
+ element.setAttribute("subgraph-id", subgraph.id);
252
+ element.setAttribute("title", subgraph.title);
253
+ if (subgraph.direction)
254
+ element.setAttribute("direction", subgraph.direction);
255
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
256
+ designItemsById.set(subgraph.id, designItem);
257
+ const parentItem = designItemsById.get(subgraph.parentId);
258
+ if (parentItem)
259
+ parentItem._insertChildInternal(designItem);
260
+ else
261
+ designItems.push(designItem);
262
+ if (subgraph.sourceRange)
263
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, subgraph.sourceRange);
264
+ subgraphIndex++;
265
+ }
266
+
267
+ let index = 0;
268
+ for (const node of nodes.values()) {
269
+ const layout = mermaidLayout?.nodes.get(node.id);
270
+ const parentLayout = node.parentId ? mermaidLayout?.subgraphs?.get(node.parentId) : null;
271
+ const fallbackPosition = getFallbackFlowchartNodePosition(index, nodes.size, direction);
272
+ const left = layout ? layout.x - (parentLayout?.x ?? 0) : fallbackPosition.left;
273
+ const top = layout ? layout.y - (parentLayout?.y ?? 0) : fallbackPosition.top;
274
+ const width = layout?.width ?? getDefaultNodeSize(node.shape).width;
275
+ const height = layout?.height ?? getDefaultNodeSize(node.shape).height;
276
+ const element = new MermaidNode();
277
+ element.style.position = "absolute";
278
+ element.style.left = left + "px";
279
+ element.style.top = top + "px";
280
+ element.style.width = width + "px";
281
+ element.style.height = height + "px";
282
+ element.setAttribute("node-id", node.id);
283
+ element.setAttribute("label", node.label);
284
+ element.setAttribute("shape", node.shape);
285
+ element.setAttribute("diagram-direction", direction);
286
+ if (node.classes)
287
+ element.setAttribute("classes", node.classes);
288
+ if (node.style)
289
+ element.setAttribute("style-directive", node.style);
290
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
291
+ const parentItem = designItemsById.get(node.parentId);
292
+ if (parentItem)
293
+ parentItem._insertChildInternal(designItem);
294
+ else
295
+ designItems.push(designItem);
296
+ designItemsById.set(node.id, designItem);
297
+ if (node.sourceRange)
298
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, node.sourceRange);
299
+ nodeBounds.set(node.id, { x: layout?.x ?? left, y: layout?.y ?? top, width, height });
300
+ index++;
301
+ }
302
+
303
+ let edgeIndex = 0;
304
+ for (const edge of edges) {
305
+ const element = new MermaidEdge();
306
+ element.style.position = "absolute";
307
+ element.style.left = "40px";
308
+ element.style.top = 60 + index * 110 + edgeIndex * 44 + "px";
309
+ element.style.width = "220px";
310
+ element.style.height = "28px";
311
+ element.setAttribute("from", edge.from);
312
+ element.setAttribute("to", edge.to);
313
+ element.setAttribute("label", edge.label);
314
+ element.setAttribute("edge-type", edge.edgeType);
315
+ if (edge.connector)
316
+ element.setAttribute("connector", edge.connector);
317
+ if (edge.edgeId)
318
+ element.setAttribute("edge-id", edge.edgeId);
319
+ if (edge.animation)
320
+ element.setAttribute("animation", edge.animation);
321
+ element.setAttribute("diagram-direction", direction);
322
+ const sourceBounds = nodeBounds.get(edge.from);
323
+ const targetBounds = nodeBounds.get(edge.to);
324
+ if (sourceBounds && targetBounds)
325
+ element.setAttribute("waypoints", encodeWaypoints(routeBetweenBounds(sourceBounds, targetBounds, direction)));
326
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
327
+ designItems.push(designItem);
328
+ if (edge.sourceRange)
329
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, edge.connectorRange ?? edge.sourceRange);
330
+ edgeIndex++;
331
+ }
332
+
333
+ let directiveIndex = 0;
334
+ for (const directive of directives) {
335
+ const element = new MermaidFlowchartDirective();
336
+ element.style.position = "absolute";
337
+ element.style.left = "40px";
338
+ element.style.top = 60 + index * 110 + edgeIndex * 44 + directiveIndex * 28 + "px";
339
+ element.style.width = "320px";
340
+ element.style.height = "24px";
341
+ element.setAttribute("line", directive.line);
342
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
343
+ designItems.push(designItem);
344
+ if (directive.sourceRange)
345
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, directive.sourceRange);
346
+ directiveIndex++;
347
+ }
348
+
349
+ return designItems;
350
+ }
351
+
352
+ function writeFlowchart(textWriter: ITextWriter, designItems: IDesignItem[], updatePositions?: boolean, rootDesignItem?: IDesignItem) {
353
+ const rootDirection = rootDesignItem?.getAttribute(mermaidFlowchartDirectionAttribute);
354
+ const direction = isFlowchartDirection(rootDirection) ? rootDirection : getDiagramDirection(designItems);
355
+ writeMermaidFrontmatter(textWriter, designItems, rootDesignItem);
356
+ textWriter.writeLine("flowchart " + direction);
357
+ const allFlowchartItems = getAllFlowchartItems(designItems);
358
+ const nodeIdsUsedByEdges = getFlowchartNodeIdsUsedByEdges(allFlowchartItems);
359
+ const nodeItemsById = getFlowchartNodeItemsById(allFlowchartItems);
360
+ const explicitlyWrittenNodeIds = new Set<string>();
361
+
362
+ const writeNodeOrSubgraph = (designItem: IDesignItem, depth: number) => {
363
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
364
+ if (element.nodeName === "MERMAID-SUBGRAPH") {
365
+ const subgraphElement = element as HTMLElement & { createMermaidStart?: () => string };
366
+ writeDesignItemLine(textWriter, designItem, repeatText(" ", depth) + subgraphElement.createMermaidStart(), updatePositions);
367
+ const subgraphDirection = element.getAttribute("direction");
368
+ if (isFlowchartDirection(subgraphDirection))
369
+ textWriter.writeLine(repeatText(" ", depth + 1) + "direction " + subgraphDirection);
370
+ for (const child of designItem.children())
371
+ writeNodeOrSubgraph(child, depth + 1);
372
+ textWriter.writeLine(repeatText(" ", depth) + "end");
373
+ } else if (element.nodeName === "MERMAID-NODE" && element.createMermaid && shouldWriteFlowchartNode(element, nodeIdsUsedByEdges)) {
374
+ writeDesignItemLine(textWriter, designItem, repeatText(" ", depth) + element.createMermaid(), updatePositions);
375
+ explicitlyWrittenNodeIds.add(element.getAttribute("node-id"));
376
+ }
377
+ };
378
+
379
+ for (const designItem of designItems) {
380
+ writeNodeOrSubgraph(designItem, 1);
381
+ }
382
+ for (const designItem of allFlowchartItems) {
383
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
384
+ if (element.nodeName === "MERMAID-EDGE" && element.createMermaid)
385
+ writeFlowchartEdgeLine(textWriter, designItem, element, nodeItemsById, explicitlyWrittenNodeIds, updatePositions);
386
+ }
387
+ for (const designItem of allFlowchartItems) {
388
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
389
+ if (element.nodeName === "MERMAID-FLOWCHART-DIRECTIVE" && element.createMermaid)
390
+ writeDesignItemLine(textWriter, designItem, " " + element.createMermaid(), updatePositions);
391
+ }
392
+ }
393
+
394
+ function writeFlowchartEdgeLine(textWriter: ITextWriter, designItem: IDesignItem, element: HTMLElement & { createMermaid?: () => string }, nodeItemsById: Map<string, IDesignItem>, explicitlyWrittenNodeIds: Set<string>, updatePositions?: boolean) {
395
+ const start = textWriter.position;
396
+ const line = indentEmbeddedNewlines(" " + element.createMermaid());
397
+ textWriter.writeLine(line);
398
+ if (!updatePositions)
399
+ return;
400
+
401
+ const from = element.getAttribute("from");
402
+ const to = element.getAttribute("to");
403
+ const fromIndex = from ? line.indexOf(from) : -1;
404
+ const toIndex = to ? line.lastIndexOf(to) : -1;
405
+
406
+ if (from && fromIndex >= 0 && !explicitlyWrittenNodeIds.has(from))
407
+ nodeItemsById.get(from)?.instanceServiceContainer.designItemDocumentPositionService?.setPosition(nodeItemsById.get(from), { start: start + fromIndex, length: from.length });
408
+ if (to && toIndex >= 0 && !explicitlyWrittenNodeIds.has(to))
409
+ nodeItemsById.get(to)?.instanceServiceContainer.designItemDocumentPositionService?.setPosition(nodeItemsById.get(to), { start: start + toIndex, length: to.length });
410
+
411
+ if (fromIndex >= 0 && toIndex > fromIndex) {
412
+ const connectorStart = fromIndex + from.length;
413
+ designItem.instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, { start: start + connectorStart, length: toIndex - connectorStart });
414
+ } else {
415
+ designItem.instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, { start, length: line.length });
416
+ }
417
+ }
418
+
419
+ function getFlowchartNodeIdsUsedByEdges(designItems: IDesignItem[]) {
420
+ const ids = new Set<string>();
421
+ for (const designItem of designItems) {
422
+ const element = designItem.element as HTMLElement;
423
+ if (element.nodeName === "MERMAID-EDGE") {
424
+ const from = element.getAttribute("from");
425
+ const to = element.getAttribute("to");
426
+ if (from)
427
+ ids.add(from);
428
+ if (to)
429
+ ids.add(to);
430
+ }
431
+ }
432
+ return ids;
433
+ }
434
+
435
+ function getFlowchartNodeItemsById(designItems: IDesignItem[]) {
436
+ const nodeItemsById = new Map<string, IDesignItem>();
437
+ for (const designItem of designItems) {
438
+ const element = designItem.element as HTMLElement;
439
+ if (element.nodeName === "MERMAID-NODE") {
440
+ const id = element.getAttribute("node-id");
441
+ if (id)
442
+ nodeItemsById.set(id, designItem);
443
+ }
444
+ }
445
+ return nodeItemsById;
446
+ }
447
+
448
+ function getAllFlowchartItems(designItems: IDesignItem[]) {
449
+ const result: IDesignItem[] = [];
450
+ const append = (item: IDesignItem) => {
451
+ result.push(item);
452
+ for (const child of item.children())
453
+ append(child);
454
+ };
455
+ for (const designItem of designItems)
456
+ append(designItem);
457
+ return result;
458
+ }
459
+
460
+ function shouldWriteFlowchartNode(element: HTMLElement, nodeIdsUsedByEdges: Set<string>) {
461
+ const id = element.getAttribute("node-id");
462
+ const label = element.getAttribute("label");
463
+ const shape = element.getAttribute("shape") ?? "rectangle";
464
+ if (!nodeIdsUsedByEdges.has(id))
465
+ return true;
466
+ return shape !== "rectangle" || (label && label !== id);
467
+ }
468
+
469
+ async function parseSequenceDiagram(html: string, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): Promise<IDesignItem[]> {
470
+ const document = readMermaidDocument(html);
471
+ setMermaidDocumentAttributes(instanceServiceContainer, "sequenceDiagram", undefined, document.title, document.frontmatter);
472
+ const lines = document.lines;
473
+ const participants = new Map<string, ParsedSequenceParticipant>();
474
+ const messages: ParsedSequenceMessage[] = [];
475
+ const scannedParticipants = new Map<string, ParsedSequenceParticipant>();
476
+ const scannedMessages: ParsedSequenceMessage[] = [];
477
+
478
+ for (const line of lines) {
479
+ if (!line.trimmed || line.trimmed.startsWith("%%") || equalsIgnoreCase(line.trimmed, "sequenceDiagram"))
480
+ continue;
481
+
482
+ const participant = parseSequenceParticipant(line.trimmed, line.start);
483
+ if (participant) {
484
+ scannedParticipants.set(participant.id, participant);
485
+ continue;
486
+ }
487
+
488
+ const message = parseSequenceMessage(line.trimmed, line.start);
489
+ if (message) {
490
+ scannedMessages.push(message);
491
+ }
492
+ }
493
+
494
+ const parsed = await getMermaidSequenceData(html);
495
+ if (parsed) {
496
+ for (const participant of parsed.participants) {
497
+ const scanned = scannedParticipants.get(participant.id);
498
+ participants.set(participant.id, {
499
+ ...participant,
500
+ implicit: !scanned,
501
+ sourceRange: scanned?.sourceRange,
502
+ });
503
+ }
504
+ for (let i = 0; i < parsed.messages.length; i++) {
505
+ messages.push({
506
+ ...parsed.messages[i],
507
+ sourceRange: scannedMessages[i]?.sourceRange,
508
+ });
509
+ }
510
+ } else {
511
+ for (const participant of scannedParticipants.values())
512
+ participants.set(participant.id, participant);
513
+ messages.push(...scannedMessages);
514
+ }
515
+
516
+ for (const message of messages) {
517
+ ensureSequenceParticipant(participants, message.from);
518
+ ensureSequenceParticipant(participants, message.to);
519
+ }
520
+
521
+ const designItems: IDesignItem[] = [];
522
+ const participantBounds = new Map<string, { x: number; y: number; width: number; height: number }>();
523
+ let index = 0;
524
+ for (const participant of participants.values()) {
525
+ const width = 140;
526
+ const height = 44;
527
+ const left = 60 + index * 220;
528
+ const top = 40;
529
+ const element = new MermaidSequenceParticipant();
530
+ element.style.position = "absolute";
531
+ element.style.left = left + "px";
532
+ element.style.top = top + "px";
533
+ element.style.width = width + "px";
534
+ element.style.height = height + "px";
535
+ element.setAttribute("participant-id", participant.id);
536
+ element.setAttribute("label", participant.label);
537
+ element.setAttribute("participant-type", participant.participantType);
538
+ if (participant.implicit)
539
+ element.setAttribute("implicit", "true");
540
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
541
+ designItems.push(designItem);
542
+ if (participant.sourceRange)
543
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, participant.sourceRange);
544
+ participantBounds.set(participant.id, { x: left, y: top, width, height });
545
+ index++;
546
+ }
547
+
548
+ let messageIndex = 0;
549
+ for (const message of messages) {
550
+ const fromBounds = participantBounds.get(message.from);
551
+ const toBounds = participantBounds.get(message.to);
552
+ const y = 130 + messageIndex * 54;
553
+ const startX = fromBounds ? fromBounds.x + fromBounds.width / 2 : 60;
554
+ const endX = toBounds ? toBounds.x + toBounds.width / 2 : startX + 220;
555
+ const left = Math.min(startX, endX);
556
+ const width = Math.max(80, Math.abs(endX - startX));
557
+ const element = new MermaidSequenceMessage();
558
+ element.style.position = "absolute";
559
+ element.style.left = left + "px";
560
+ element.style.top = y + "px";
561
+ element.style.width = width + "px";
562
+ element.style.height = "36px";
563
+ element.setAttribute("from", message.from);
564
+ element.setAttribute("to", message.to);
565
+ element.setAttribute("label", message.label);
566
+ element.setAttribute("message-type", message.messageType);
567
+ element.setAttribute("connector", message.connector);
568
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
569
+ designItems.push(designItem);
570
+ if (message.sourceRange)
571
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, message.sourceRange);
572
+ messageIndex++;
573
+ }
574
+
575
+ return designItems;
576
+ }
577
+
578
+ function writeSequenceDiagram(textWriter: ITextWriter, designItems: IDesignItem[], updatePositions?: boolean, rootDesignItem?: IDesignItem) {
579
+ writeMermaidFrontmatter(textWriter, designItems, rootDesignItem);
580
+ textWriter.writeLine("sequenceDiagram");
581
+ for (const designItem of designItems) {
582
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
583
+ if (element.nodeName === "MERMAID-SEQUENCE-PARTICIPANT" && element.getAttribute("implicit") !== "true" && element.createMermaid)
584
+ writeDesignItemLine(textWriter, designItem, " " + element.createMermaid(), updatePositions);
585
+ }
586
+ for (const designItem of designItems) {
587
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
588
+ if (element.nodeName === "MERMAID-SEQUENCE-MESSAGE" && element.createMermaid)
589
+ writeDesignItemLine(textWriter, designItem, " " + element.createMermaid(), updatePositions);
590
+ }
591
+ }
592
+
593
+ async function parseMindmapDiagram(html: string, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): Promise<IDesignItem[]> {
594
+ const document = readMermaidDocument(html);
595
+ setMermaidDocumentAttributes(instanceServiceContainer, "mindmap", undefined, document.title, document.frontmatter);
596
+
597
+ const parsedNodes: ParsedMindmapNode[] = [];
598
+ const parentStack: ParsedMindmapNode[] = [];
599
+ let index = 0;
600
+
601
+ for (const line of document.lines) {
602
+ if (!line.trimmed || line.trimmed.startsWith("%%") || equalsIgnoreCase(line.trimmed, "mindmap"))
603
+ continue;
604
+
605
+ while (parentStack.length && parentStack[parentStack.length - 1].indent >= line.indent)
606
+ parentStack.pop();
607
+
608
+ const parent = parentStack[parentStack.length - 1];
609
+ const parsed = parseMindmapNode(line.trimmed, index, parent?.id ?? "", line.start, line.text.length, line.indent);
610
+ parsedNodes.push(parsed);
611
+ parentStack.push(parsed);
612
+ index++;
613
+ }
614
+
615
+ const siblingsByParent = new Map<string, number>();
616
+ const designItemsById = new Map<string, IDesignItem>();
617
+ const rootDesignItems: IDesignItem[] = [];
618
+ const mermaidLayout = await getMermaidMindmapLayout(html, parsedNodes);
619
+ for (const node of parsedNodes) {
620
+ const siblingIndex = siblingsByParent.get(node.parentId) ?? 0;
621
+ siblingsByParent.set(node.parentId, siblingIndex + 1);
622
+ const layout = mermaidLayout?.nodes.get(node.id);
623
+ const parentLayout = node.parentId ? mermaidLayout?.nodes.get(node.parentId) : null;
624
+ const left = layout ? layout.x - (parentLayout?.x ?? 0) : (node.parentId ? 220 : 40);
625
+ const top = layout ? layout.y - (parentLayout?.y ?? 0) : (node.parentId ? siblingIndex * 76 : 40 + rootDesignItems.length * 96);
626
+ const element = new MermaidMindmapNode();
627
+ element.style.position = "absolute";
628
+ element.style.left = left + "px";
629
+ element.style.top = top + "px";
630
+ element.style.width = (layout?.width ?? getDefaultMindmapNodeSize(node.shape).width) + "px";
631
+ element.style.height = (layout?.height ?? getDefaultMindmapNodeSize(node.shape).height) + "px";
632
+ element.setAttribute("mindmap-id", node.id);
633
+ element.setAttribute("label", node.label);
634
+ element.setAttribute("shape", node.shape);
635
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
636
+ designItemsById.set(node.id, designItem);
637
+ const parentItem = designItemsById.get(node.parentId);
638
+ if (parentItem) {
639
+ parentItem._insertChildInternal(designItem);
640
+ } else {
641
+ rootDesignItems.push(designItem);
642
+ }
643
+ if (node.sourceRange)
644
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, node.sourceRange);
645
+ }
646
+
647
+ return rootDesignItems;
648
+ }
649
+
650
+ function writeMindmapDiagram(textWriter: ITextWriter, designItems: IDesignItem[], updatePositions?: boolean, rootDesignItem?: IDesignItem) {
651
+ writeMermaidFrontmatter(textWriter, designItems, rootDesignItem);
652
+ textWriter.writeLine("mindmap");
653
+ const writeItems = (items: IDesignItem[], depth: number) => {
654
+ for (const item of sortMindmapItems(items)) {
655
+ const element = item.element as HTMLElement & { createMermaid?: () => string };
656
+ if (!element.createMermaid)
657
+ continue;
658
+ writeDesignItemLine(textWriter, item, repeatText(" ", depth + 1) + element.createMermaid(), updatePositions);
659
+ writeItems(Array.from(item.children()).filter(child => child.element.localName === MermaidMindmapNode.is), depth + 1);
660
+ }
661
+ };
662
+ writeItems(designItems.filter(designItem => designItem.element.localName === MermaidMindmapNode.is), 0);
663
+ }
664
+
665
+ async function parseRequirementDiagram(html: string, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): Promise<IDesignItem[]> {
666
+ const document = readMermaidDocument(html);
667
+ const lines = document.lines;
668
+ const nodes = new Map<string, ParsedRequirementNode>();
669
+ const relationships: ParsedRequirementRelationship[] = [];
670
+ let direction: FlowchartDirection = "TB";
671
+
672
+ for (let i = 0; i < lines.length; i++) {
673
+ const line = lines[i];
674
+ if (!line.trimmed || line.trimmed.startsWith("%%") || equalsIgnoreCase(line.trimmed, "requirementDiagram"))
675
+ continue;
676
+
677
+ const parsedDirection = parseDirectionStatement(line.trimmed);
678
+ if (parsedDirection) {
679
+ direction = parsedDirection;
680
+ continue;
681
+ }
682
+
683
+ const blockStart = parseRequirementBlockStart(line.trimmed);
684
+ if (blockStart) {
685
+ const blockLines: LineRecord[] = [];
686
+ const start = line.start;
687
+ while (++i < lines.length) {
688
+ if (lines[i].trimmed === "}")
689
+ break;
690
+ blockLines.push(lines[i]);
691
+ }
692
+ const endLine = lines[Math.min(i, lines.length - 1)] ?? line;
693
+ const node = parseRequirementBlock(blockStart, blockLines, start, endLine.start + endLine.text.length - start);
694
+ nodes.set(node.id, node);
695
+ continue;
696
+ }
697
+
698
+ const relationship = parseRequirementRelationship(line.trimmed, line.start);
699
+ if (relationship)
700
+ relationships.push(relationship);
701
+ }
702
+
703
+ setMermaidDocumentAttributes(instanceServiceContainer, "requirementDiagram", direction, document.title, document.frontmatter);
704
+
705
+ const designItems: IDesignItem[] = [];
706
+ const nodeBounds = new Map<string, { x: number; y: number; width: number; height: number }>();
707
+ const mermaidLayout = await getMermaidRequirementLayout(html, nodes);
708
+ let index = 0;
709
+ for (const node of nodes.values()) {
710
+ const fallbackPosition = getFallbackRequirementNodePosition(index, nodes.size, direction);
711
+ const layout = mermaidLayout?.nodes.get(node.id);
712
+ const size = getDefaultRequirementNodeSize(node);
713
+ const left = layout?.x ?? fallbackPosition.left;
714
+ const top = layout?.y ?? fallbackPosition.top;
715
+ const width = layout?.width ?? size.width;
716
+ const height = layout?.height ?? size.height;
717
+ const element = new MermaidRequirementNode();
718
+ element.style.position = "absolute";
719
+ element.style.left = left + "px";
720
+ element.style.top = top + "px";
721
+ element.style.width = width + "px";
722
+ element.style.height = height + "px";
723
+ element.setAttribute("node-kind", node.kind);
724
+ element.setAttribute("label", node.id);
725
+ if (node.kind === "requirement") {
726
+ element.setAttribute("requirement-type", node.requirementType ?? "requirement");
727
+ element.setAttribute("requirement-id", node.requirementId ?? "");
728
+ element.setAttribute("text", node.text ?? "");
729
+ element.setAttribute("risk", node.risk ?? "");
730
+ element.setAttribute("verify-method", node.verifyMethod ?? "");
731
+ } else {
732
+ element.setAttribute("element-type", node.elementType ?? "");
733
+ element.setAttribute("doc-ref", node.docRef ?? "");
734
+ }
735
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
736
+ designItems.push(designItem);
737
+ if (node.sourceRange)
738
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, node.sourceRange);
739
+ nodeBounds.set(node.id, { x: left, y: top, width, height });
740
+ index++;
741
+ }
742
+
743
+ let relationshipIndex = 0;
744
+ for (const relationship of relationships) {
745
+ const element = new MermaidRequirementRelationship();
746
+ element.style.position = "absolute";
747
+ element.setAttribute("from", relationship.from);
748
+ element.setAttribute("to", relationship.to);
749
+ element.setAttribute("relationship-type", relationship.relationshipType);
750
+ element.setAttribute("syntax-direction", relationship.syntaxDirection);
751
+ const sourceBounds = nodeBounds.get(relationship.from);
752
+ const targetBounds = nodeBounds.get(relationship.to);
753
+ if (sourceBounds && targetBounds) {
754
+ element.setAttribute("waypoints", encodeWaypoints(routeBetweenBounds(sourceBounds, targetBounds, direction)));
755
+ } else {
756
+ element.style.left = "40px";
757
+ element.style.top = 80 + index * 120 + relationshipIndex * 40 + "px";
758
+ element.style.width = "220px";
759
+ element.style.height = "28px";
760
+ }
761
+ const designItem = DesignItem.createDesignItemFromInstance(element, serviceContainer, instanceServiceContainer);
762
+ designItems.push(designItem);
763
+ if (relationship.sourceRange)
764
+ instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, relationship.sourceRange);
765
+ relationshipIndex++;
766
+ }
767
+
768
+ return designItems;
769
+ }
770
+
771
+ function writeRequirementDiagram(textWriter: ITextWriter, designItems: IDesignItem[], updatePositions?: boolean, rootDesignItem?: IDesignItem) {
772
+ const rootDirection = rootDesignItem?.getAttribute(mermaidFlowchartDirectionAttribute);
773
+ const direction = isRequirementDirection(rootDirection) ? rootDirection : "TB";
774
+ writeMermaidFrontmatter(textWriter, designItems, rootDesignItem);
775
+ textWriter.writeLine("requirementDiagram");
776
+ if (direction !== "TB")
777
+ textWriter.writeLine(" direction " + direction);
778
+ for (const designItem of designItems) {
779
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
780
+ if (element.nodeName === "MERMAID-REQUIREMENT-NODE" && element.createMermaid)
781
+ writeDesignItemLine(textWriter, designItem, " " + element.createMermaid(), updatePositions);
782
+ }
783
+ for (const designItem of designItems) {
784
+ const element = designItem.element as HTMLElement & { createMermaid?: () => string };
785
+ if (element.nodeName === "MERMAID-REQUIREMENT-RELATIONSHIP" && element.createMermaid)
786
+ writeDesignItemLine(textWriter, designItem, " " + element.createMermaid(), updatePositions);
787
+ }
788
+ }
789
+
790
+ function parseSequenceParticipant(line: string, sourceStart: number): ParsedSequenceParticipant {
791
+ const cursor = new SourceCursor(line);
792
+ const keyword = cursor.readIdentifier();
793
+ if (!equalsIgnoreCase(keyword, "participant") && !equalsIgnoreCase(keyword, "actor"))
794
+ return null;
795
+ if (!cursor.skipRequiredWhitespace())
796
+ return null;
797
+ const id = cursor.readIdentifier();
798
+ if (!id)
799
+ return null;
800
+
801
+ let label = id;
802
+ cursor.skipWhitespace();
803
+ if (!cursor.atEnd()) {
804
+ const marker = cursor.readIdentifier();
805
+ if (!equalsIgnoreCase(marker, "as"))
806
+ return null;
807
+ if (!cursor.skipRequiredWhitespace())
808
+ return null;
809
+ label = cursor.readRest().trim();
810
+ }
811
+
812
+ return {
813
+ id,
814
+ label: unquoteLabel(label),
815
+ participantType: keyword.toLowerCase(),
816
+ sourceRange: { start: sourceStart, length: line.length },
817
+ };
818
+ }
819
+
820
+ function parseSequenceMessage(line: string, sourceStart: number): ParsedSequenceMessage {
821
+ const parsed = parseBinaryStatement(line, ["-->>", "->>", "-->", "->", "--x", "-x", "--)", "-)"]);
822
+ if (!parsed)
823
+ return null;
824
+ const separatorIndex = parsed.right.indexOf(":");
825
+ if (separatorIndex < 0)
826
+ return null;
827
+ const to = parsed.right.substring(0, separatorIndex).trim();
828
+ const label = parsed.right.substring(separatorIndex + 1).trim();
829
+ if (!to || !isIdentifier(to))
830
+ return null;
831
+
832
+ return {
833
+ from: parsed.left,
834
+ to,
835
+ label: unquoteLabel(label),
836
+ messageType: getSequenceMessageType(parsed.operator),
837
+ connector: parsed.operator,
838
+ sourceRange: { start: sourceStart, length: line.length },
839
+ };
840
+ }
841
+
842
+ function ensureSequenceParticipant(participants: Map<string, ParsedSequenceParticipant>, id: string) {
843
+ if (!participants.has(id))
844
+ participants.set(id, { id, label: id, participantType: "participant", implicit: true });
845
+ }
846
+
847
+ function getSequenceMessageType(connector: string) {
848
+ if (connector.includes(")"))
849
+ return "async";
850
+ if (connector.includes("--"))
851
+ return "dotted";
852
+ if (connector.includes("x"))
853
+ return "cross";
854
+ if (connector === "->")
855
+ return "open";
856
+ return "solid";
857
+ }
858
+
859
+ class SourceCursor {
860
+ public position = 0;
861
+
862
+ constructor(private readonly text: string) {
863
+ }
864
+
865
+ atEnd() {
866
+ return this.position >= this.text.length;
867
+ }
868
+
869
+ skipWhitespace() {
870
+ while (!this.atEnd() && isWhitespace(this.text[this.position]))
871
+ this.position++;
872
+ }
873
+
874
+ skipRequiredWhitespace() {
875
+ const start = this.position;
876
+ this.skipWhitespace();
877
+ return this.position > start;
878
+ }
879
+
880
+ readIdentifier() {
881
+ if (this.atEnd() || !isIdentifierStart(this.text[this.position]))
882
+ return "";
883
+ const start = this.position;
884
+ this.position++;
885
+ while (!this.atEnd() && isIdentifierPart(this.text[this.position]))
886
+ this.position++;
887
+ return this.text.substring(start, this.position);
888
+ }
889
+
890
+ readRest() {
891
+ const rest = this.text.substring(this.position);
892
+ this.position = this.text.length;
893
+ return rest;
894
+ }
895
+
896
+ consume(value: string) {
897
+ if (!this.text.startsWith(value, this.position))
898
+ return false;
899
+ this.position += value.length;
900
+ return true;
901
+ }
902
+ }
903
+
904
+ function parseFlowchartDirection(line: string): FlowchartDirection | null {
905
+ const cursor = new SourceCursor(line);
906
+ const keyword = cursor.readIdentifier();
907
+ if (!equalsIgnoreCase(keyword, "graph") && !equalsIgnoreCase(keyword, "flowchart"))
908
+ return null;
909
+ if (!cursor.skipRequiredWhitespace())
910
+ return null;
911
+ const direction = cursor.readIdentifier().toUpperCase();
912
+ return isFlowchartDirection(direction) ? direction : null;
913
+ }
914
+
915
+ function parseDirectionStatement(line: string): FlowchartDirection | null {
916
+ const cursor = new SourceCursor(line);
917
+ const keyword = cursor.readIdentifier();
918
+ if (!equalsIgnoreCase(keyword, "direction"))
919
+ return null;
920
+ if (!cursor.skipRequiredWhitespace())
921
+ return null;
922
+ const direction = cursor.readIdentifier().toUpperCase();
923
+ return isRequirementDirection(direction) ? direction : null;
924
+ }
925
+
926
+ function parseSubgraphStart(line: string, sourceStart: number, parentId?: string): ParsedSubgraph | null {
927
+ const cursor = new SourceCursor(line);
928
+ const keyword = cursor.readIdentifier();
929
+ if (!equalsIgnoreCase(keyword, "subgraph"))
930
+ return null;
931
+ if (!cursor.skipRequiredWhitespace())
932
+ return null;
933
+ const rest = cursor.readRest().trim();
934
+ if (!rest)
935
+ return null;
936
+ const bracketStart = rest.indexOf("[");
937
+ const bracketEnd = rest.endsWith("]") ? rest.length - 1 : -1;
938
+ if (bracketStart > 0 && bracketEnd > bracketStart) {
939
+ const id = rest.substring(0, bracketStart).trim();
940
+ const title = unquoteLabel(rest.substring(bracketStart + 1, bracketEnd).trim());
941
+ return { id, title, parentId, sourceRange: { start: sourceStart, length: line.length } };
942
+ }
943
+ const title = unquoteLabel(rest);
944
+ return { id: sanitizeDirectiveId(title), title, parentId, sourceRange: { start: sourceStart, length: line.length } };
945
+ }
946
+
947
+ function parseFlowchartDirective(line: string, sourceStart: number): ParsedFlowchartDirective | null {
948
+ const cursor = new SourceCursor(line);
949
+ const keyword = cursor.readIdentifier();
950
+ if (!keyword)
951
+ return null;
952
+ if (equalsIgnoreCase(keyword, "style") || equalsIgnoreCase(keyword, "classDef") || equalsIgnoreCase(keyword, "class") || equalsIgnoreCase(keyword, "click") || equalsIgnoreCase(keyword, "linkStyle"))
953
+ return { line, sourceRange: { start: sourceStart, length: line.length } };
954
+ if (line.includes("@{") && !line.trim().startsWith("subgraph"))
955
+ return null;
956
+ return null;
957
+ }
958
+
959
+ function parseBinaryStatement(line: string, operators: string[]) {
960
+ const parsed = findOperator(line, operators);
961
+ if (!parsed)
962
+ return null;
963
+
964
+ const leftRange = trimRange(line, 0, parsed.index);
965
+ const rightRange = trimRange(line, parsed.index + parsed.operator.length, line.length);
966
+ if (leftRange.start >= leftRange.end || rightRange.start >= rightRange.end)
967
+ return null;
968
+
969
+ return {
970
+ left: line.substring(leftRange.start, leftRange.end),
971
+ leftStart: leftRange.start,
972
+ operator: parsed.operator,
973
+ operatorStart: parsed.index,
974
+ right: line.substring(rightRange.start, rightRange.end),
975
+ rightStart: rightRange.start,
976
+ };
977
+ }
978
+
979
+ function parseRequirementBlockStart(line: string): { kind: "requirement" | "element"; type: string; id: string } | null {
980
+ const cursor = new SourceCursor(line);
981
+ const type = cursor.readIdentifier();
982
+ if (!type)
983
+ return null;
984
+ const kind = equalsIgnoreCase(type, "element") ? "element" : isRequirementType(type) ? "requirement" : null;
985
+ if (!kind)
986
+ return null;
987
+ if (!cursor.skipRequiredWhitespace())
988
+ return null;
989
+ const id = cursor.readIdentifier();
990
+ if (!id)
991
+ return null;
992
+ cursor.skipWhitespace();
993
+ if (cursor.consume(":::")) {
994
+ cursor.readIdentifier();
995
+ cursor.skipWhitespace();
996
+ }
997
+ if (!cursor.consume("{"))
998
+ return null;
999
+ return { kind, type, id };
1000
+ }
1001
+
1002
+ function parseRequirementBlock(blockStart: { kind: "requirement" | "element"; type: string; id: string }, lines: LineRecord[], sourceStart: number, sourceLength: number): ParsedRequirementNode {
1003
+ const values = new Map<string, string>();
1004
+ for (const line of lines) {
1005
+ const separator = findTopLevelColon(line.trimmed);
1006
+ if (separator < 0)
1007
+ continue;
1008
+ const key = line.trimmed.substring(0, separator).trim().toLowerCase();
1009
+ const value = unquoteLabel(line.trimmed.substring(separator + 1).trim());
1010
+ values.set(key, value);
1011
+ }
1012
+
1013
+ if (blockStart.kind === "element") {
1014
+ return {
1015
+ id: blockStart.id,
1016
+ kind: "element",
1017
+ elementType: values.get("type") ?? "",
1018
+ docRef: values.get("docref") ?? "",
1019
+ sourceRange: { start: sourceStart, length: sourceLength },
1020
+ };
1021
+ }
1022
+
1023
+ return {
1024
+ id: blockStart.id,
1025
+ kind: "requirement",
1026
+ requirementType: blockStart.type,
1027
+ requirementId: values.get("id") ?? "",
1028
+ text: values.get("text") ?? "",
1029
+ risk: values.get("risk") ?? "",
1030
+ verifyMethod: values.get("verifymethod") ?? values.get("verifymethod") ?? "",
1031
+ sourceRange: { start: sourceStart, length: sourceLength },
1032
+ };
1033
+ }
1034
+
1035
+ function parseRequirementRelationship(line: string, sourceStart: number): ParsedRequirementRelationship | null {
1036
+ const forward = parseRequirementRelationshipForward(line, sourceStart);
1037
+ if (forward)
1038
+ return forward;
1039
+ return parseRequirementRelationshipReverse(line, sourceStart);
1040
+ }
1041
+
1042
+ function parseRequirementRelationshipForward(line: string, sourceStart: number): ParsedRequirementRelationship | null {
1043
+ const cursor = new SourceCursor(line);
1044
+ const from = cursor.readIdentifier();
1045
+ if (!from)
1046
+ return null;
1047
+ cursor.skipWhitespace();
1048
+ if (!cursor.consume("-"))
1049
+ return null;
1050
+ cursor.skipWhitespace();
1051
+ const relationshipType = cursor.readIdentifier();
1052
+ if (!isRequirementRelationshipType(relationshipType))
1053
+ return null;
1054
+ cursor.skipWhitespace();
1055
+ if (!cursor.consume("->"))
1056
+ return null;
1057
+ cursor.skipWhitespace();
1058
+ const to = cursor.readIdentifier();
1059
+ if (!to)
1060
+ return null;
1061
+ return { from, to, relationshipType, syntaxDirection: "forward", sourceRange: { start: sourceStart, length: line.length } };
1062
+ }
1063
+
1064
+ function parseRequirementRelationshipReverse(line: string, sourceStart: number): ParsedRequirementRelationship | null {
1065
+ const cursor = new SourceCursor(line);
1066
+ const to = cursor.readIdentifier();
1067
+ if (!to)
1068
+ return null;
1069
+ cursor.skipWhitespace();
1070
+ if (!cursor.consume("<-"))
1071
+ return null;
1072
+ cursor.skipWhitespace();
1073
+ const relationshipType = cursor.readIdentifier();
1074
+ if (!isRequirementRelationshipType(relationshipType))
1075
+ return null;
1076
+ cursor.skipWhitespace();
1077
+ if (!cursor.consume("-"))
1078
+ return null;
1079
+ cursor.skipWhitespace();
1080
+ const from = cursor.readIdentifier();
1081
+ if (!from)
1082
+ return null;
1083
+ return { from, to, relationshipType, syntaxDirection: "reverse", sourceRange: { start: sourceStart, length: line.length } };
1084
+ }
1085
+
1086
+ function parseFlowchartEdgeStatement(line: string) {
1087
+ const parsed = parseBinaryStatement(line, getFlowchartOperators());
1088
+ if (!parsed)
1089
+ return null;
1090
+
1091
+ let left = parsed.left;
1092
+ let leftStart = parsed.leftStart;
1093
+ let edgeId = "";
1094
+ const edgeIdSeparator = left.lastIndexOf("@");
1095
+ if (edgeIdSeparator > 0) {
1096
+ const candidate = left.substring(edgeIdSeparator + 1).trim();
1097
+ if (!candidate) {
1098
+ const idRange = trimRange(left, 0, edgeIdSeparator);
1099
+ const idCandidate = left.substring(idRange.start, idRange.end).split(" ").pop();
1100
+ if (isIdentifier(idCandidate)) {
1101
+ edgeId = idCandidate;
1102
+ left = left.substring(0, left.lastIndexOf(idCandidate)).trim();
1103
+ leftStart = parsed.leftStart;
1104
+ }
1105
+ }
1106
+ }
1107
+
1108
+ let label = "";
1109
+ let labelPartLength = 0;
1110
+ const right = parsed.right;
1111
+ if (right[0] === "|") {
1112
+ const end = right.indexOf("|", 1);
1113
+ if (end > 0) {
1114
+ label = right.substring(1, end);
1115
+ const afterLabel = right.substring(end + 1).trim();
1116
+ const skipped = countLeadingWhitespace(right);
1117
+ labelPartLength = skipped + end + 1;
1118
+ const afterLabelWhitespace = countLeadingWhitespace(right.substring(end + 1));
1119
+ return {
1120
+ ...parsed,
1121
+ left,
1122
+ leftStart,
1123
+ right: afterLabel,
1124
+ rightStart: parsed.rightStart + skipped + end + 1 + afterLabelWhitespace,
1125
+ label,
1126
+ labelPartLength,
1127
+ edgeId,
1128
+ };
1129
+ }
1130
+ }
1131
+
1132
+ return { ...parsed, left, leftStart, label, labelPartLength, edgeId };
1133
+ }
1134
+
1135
+ function getFlowchartOperators() {
1136
+ return [
1137
+ "<-->", "<==>", "<-.->",
1138
+ "--o", "--x", "o--o", "x--x", "o-->", "x-->",
1139
+ "~~~",
1140
+ "-...->", "-..->", "-.->", "-...-", "-..-", "-.-",
1141
+ "====>", "===>", "==>", "====", "===",
1142
+ "---->", "--->", "-->", "-----", "----", "---",
1143
+ ];
1144
+ }
1145
+
1146
+ function parseExpandedShape(value: string): { shape: string; label?: string } | null {
1147
+ const cursor = new SourceCursor(value);
1148
+ if (!cursor.consume("@{"))
1149
+ return null;
1150
+ const contentEnd = value.lastIndexOf("}");
1151
+ const content = contentEnd >= 0 ? value.substring(cursor.position, contentEnd) : value.substring(cursor.position);
1152
+ const properties = parseObjectLiteralProperties(content);
1153
+ const shape = properties.get("shape");
1154
+ if (!shape)
1155
+ return null;
1156
+ return { shape, label: properties.get("label") };
1157
+ }
1158
+
1159
+ function parseDelimitedShapeValue(value: string): { label: string; shape: string } | null {
1160
+ const candidates: Array<{ start: string; end: string; shape: string }> = [
1161
+ { start: "(((", end: ")))", shape: "doubleCircle" },
1162
+ { start: "((", end: "))", shape: "circle" },
1163
+ { start: "([", end: "])", shape: "stadium" },
1164
+ { start: "(", end: ")", shape: "round" },
1165
+ { start: "[[", end: "]]", shape: "subroutine" },
1166
+ { start: "[(", end: ")]", shape: "cylinder" },
1167
+ { start: ">", end: "]", shape: "asymmetric" },
1168
+ { start: "{{", end: "}}", shape: "hexagon" },
1169
+ { start: "{", end: "}", shape: "decision" },
1170
+ { start: "[/", end: "/]", shape: "parallelogram" },
1171
+ { start: "[\\", end: "\\]", shape: "parallelogramAlt" },
1172
+ { start: "[/", end: "\\]", shape: "trapezoid" },
1173
+ { start: "[\\", end: "/]", shape: "trapezoidAlt" },
1174
+ { start: "[", end: "]", shape: "rectangle" },
1175
+ ];
1176
+
1177
+ for (const candidate of candidates) {
1178
+ if (value.startsWith(candidate.start) && value.endsWith(candidate.end)) {
1179
+ return {
1180
+ label: value.substring(candidate.start.length, value.length - candidate.end.length).trim(),
1181
+ shape: candidate.shape,
1182
+ };
1183
+ }
1184
+ }
1185
+
1186
+ return null;
1187
+ }
1188
+
1189
+ function parseObjectLiteralProperties(content: string) {
1190
+ const properties = new Map<string, string>();
1191
+ let start = 0;
1192
+ let quote = "";
1193
+ for (let i = 0; i <= content.length; i++) {
1194
+ const char = content[i];
1195
+ if (quote) {
1196
+ if (char === quote)
1197
+ quote = "";
1198
+ continue;
1199
+ }
1200
+ if (char === "\"" || char === "'") {
1201
+ quote = char;
1202
+ continue;
1203
+ }
1204
+ if (i === content.length || char === ",") {
1205
+ const part = content.substring(start, i).trim();
1206
+ const separator = findTopLevelColon(part);
1207
+ if (separator > 0) {
1208
+ const key = part.substring(0, separator).trim();
1209
+ const value = unquoteLabel(part.substring(separator + 1).trim());
1210
+ properties.set(key, value);
1211
+ }
1212
+ start = i + 1;
1213
+ }
1214
+ }
1215
+ return properties;
1216
+ }
1217
+
1218
+ function findOperator(line: string, operators: string[]) {
1219
+ let depth = 0;
1220
+ let quote = "";
1221
+ for (let i = 0; i < line.length; i++) {
1222
+ const char = line[i];
1223
+ if (quote) {
1224
+ if (char === quote)
1225
+ quote = "";
1226
+ continue;
1227
+ }
1228
+ if (char === "\"" || char === "'") {
1229
+ quote = char;
1230
+ continue;
1231
+ }
1232
+ if (char === "[" || char === "(" || char === "{")
1233
+ depth++;
1234
+ else if (char === "]" || char === ")" || char === "}")
1235
+ depth = Math.max(0, depth - 1);
1236
+ if (depth > 0)
1237
+ continue;
1238
+ for (const operator of operators) {
1239
+ if (line.startsWith(operator, i))
1240
+ return { index: i, operator };
1241
+ }
1242
+ }
1243
+ return null;
1244
+ }
1245
+
1246
+ function trimRange(text: string, start: number, end: number) {
1247
+ while (start < end && isWhitespace(text[start]))
1248
+ start++;
1249
+ while (end > start && isWhitespace(text[end - 1]))
1250
+ end--;
1251
+ return { start, end };
1252
+ }
1253
+
1254
+ function countLeadingWhitespace(text: string) {
1255
+ let count = 0;
1256
+ while (count < text.length && isWhitespace(text[count]))
1257
+ count++;
1258
+ return count;
1259
+ }
1260
+
1261
+ function equalsIgnoreCase(a: string, b: string) {
1262
+ return a.toLowerCase() === b.toLowerCase();
1263
+ }
1264
+
1265
+ function isIdentifier(value: string) {
1266
+ const cursor = new SourceCursor(value);
1267
+ const id = cursor.readIdentifier();
1268
+ cursor.skipWhitespace();
1269
+ return id.length === value.length || (id.length > 0 && cursor.atEnd());
1270
+ }
1271
+
1272
+ function isIdentifierStart(char: string) {
1273
+ return isAsciiLetter(char) || char === "_";
1274
+ }
1275
+
1276
+ function isIdentifierPart(char: string) {
1277
+ return isIdentifierStart(char) || isAsciiDigit(char) || char === "-";
1278
+ }
1279
+
1280
+ function isAsciiLetter(char: string) {
1281
+ if (!char)
1282
+ return false;
1283
+ const code = char.charCodeAt(0);
1284
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
1285
+ }
1286
+
1287
+ function isAsciiDigit(char: string) {
1288
+ if (!char)
1289
+ return false;
1290
+ const code = char.charCodeAt(0);
1291
+ return code >= 48 && code <= 57;
1292
+ }
1293
+
1294
+ function isWhitespace(char: string) {
1295
+ return char === " " || char === "\t" || char === "\r" || char === "\n";
1296
+ }
1297
+
1298
+ async function getMermaidFlowchartData(code: string): Promise<{ nodes: ParsedNode[]; edges: ParsedEdge[] } | null> {
1299
+ try {
1300
+ const mermaid = await import("mermaid");
1301
+ mermaid.default.initialize({ startOnLoad: false, securityLevel: "loose" });
1302
+ const diagram = await mermaid.default.mermaidAPI.getDiagramFromText(code);
1303
+ const db = diagram.db as any;
1304
+ const vertices = db?.getVertices?.();
1305
+ const mermaidEdges = db?.getEdges?.();
1306
+ if (!vertices || !mermaidEdges)
1307
+ return null;
1308
+
1309
+ const nodes: ParsedNode[] = Array.from(vertices.values()).map((vertex: any) => ({
1310
+ id: vertex.id,
1311
+ label: normalizeMermaidText(vertex.text ?? vertex.label ?? vertex.id),
1312
+ shape: mapMermaidVertexType(vertex.type),
1313
+ }));
1314
+ const edges: ParsedEdge[] = mermaidEdges.map((edge: any) => ({
1315
+ from: edge.start,
1316
+ to: edge.end,
1317
+ label: normalizeMermaidText(edge.text ?? ""),
1318
+ edgeType: mapMermaidEdgeType(edge),
1319
+ }));
1320
+
1321
+ return { nodes, edges };
1322
+ } catch {
1323
+ return null;
1324
+ }
1325
+ }
1326
+
1327
+ async function getMermaidSequenceData(code: string): Promise<{ participants: ParsedSequenceParticipant[]; messages: ParsedSequenceMessage[] } | null> {
1328
+ try {
1329
+ const mermaid = await import("mermaid");
1330
+ mermaid.default.initialize({ startOnLoad: false, securityLevel: "loose" });
1331
+ const diagram = await mermaid.default.mermaidAPI.getDiagramFromText(code);
1332
+ const db = diagram.db as any;
1333
+ const actors = db?.getActors?.();
1334
+ const mermaidMessages = db?.getMessages?.();
1335
+ if (!actors || !mermaidMessages)
1336
+ return null;
1337
+
1338
+ const participants: ParsedSequenceParticipant[] = Array.from(actors.entries()).map(([id, actor]: [string, any]) => ({
1339
+ id,
1340
+ label: actor.description ?? actor.name ?? id,
1341
+ participantType: actor.type ?? "participant",
1342
+ }));
1343
+ const messages: ParsedSequenceMessage[] = mermaidMessages
1344
+ .filter((message: any) => typeof message.from === "string" && typeof message.to === "string")
1345
+ .map((message: any) => {
1346
+ const connector = mapMermaidSequenceConnector(message.type);
1347
+ return {
1348
+ from: message.from,
1349
+ to: message.to,
1350
+ label: message.message ?? "",
1351
+ messageType: getSequenceMessageType(connector),
1352
+ connector,
1353
+ };
1354
+ });
1355
+
1356
+ return { participants, messages };
1357
+ } catch {
1358
+ return null;
1359
+ }
1360
+ }
1361
+
1362
+ function getScannedEdge(scannedEdges: ParsedEdge[], edge: ParsedEdge): Partial<ParsedEdge> {
1363
+ return scannedEdges.find(scannedEdge => scannedEdge.from === edge.from && scannedEdge.to === edge.to && scannedEdge.label === edge.label) ?? {};
1364
+ }
1365
+
1366
+ function mapMermaidVertexType(type: string) {
1367
+ const expanded = mapExpandedShape(type);
1368
+ if (expanded !== "rectangle")
1369
+ return expanded;
1370
+ switch (type) {
1371
+ case "diamond":
1372
+ return "decision";
1373
+ case "round":
1374
+ return "round";
1375
+ case "stadium":
1376
+ return "stadium";
1377
+ case "circle":
1378
+ return "circle";
1379
+ case "doublecircle":
1380
+ return "doubleCircle";
1381
+ case "subroutine":
1382
+ return "subroutine";
1383
+ case "cylinder":
1384
+ return "cylinder";
1385
+ case "odd":
1386
+ return "asymmetric";
1387
+ case "hexagon":
1388
+ return "hexagon";
1389
+ case "lean_right":
1390
+ return "parallelogram";
1391
+ case "lean_left":
1392
+ return "parallelogramAlt";
1393
+ case "trapezoid":
1394
+ return "trapezoid";
1395
+ case "inv_trapezoid":
1396
+ return "trapezoidAlt";
1397
+ default:
1398
+ return "rectangle";
1399
+ }
1400
+ }
1401
+
1402
+ function mapMermaidEdgeType(edge: any) {
1403
+ if (edge.stroke === "dotted")
1404
+ return "dotted";
1405
+ if (edge.stroke === "thick")
1406
+ return "thick";
1407
+ if (!edge.type?.includes("arrow"))
1408
+ return "open";
1409
+ return "arrow";
1410
+ }
1411
+
1412
+ function mapMermaidSequenceConnector(type: number) {
1413
+ switch (type) {
1414
+ case 1:
1415
+ return "-->>";
1416
+ case 3:
1417
+ return "-x";
1418
+ case 4:
1419
+ return "--x";
1420
+ case 5:
1421
+ return "->";
1422
+ case 6:
1423
+ return "-->";
1424
+ case 24:
1425
+ return "-)";
1426
+ case 25:
1427
+ return "--)";
1428
+ default:
1429
+ return "->>";
1430
+ }
1431
+ }
1432
+
1433
+ function normalizeMermaidText(value: any) {
1434
+ if (value == null)
1435
+ return "";
1436
+ if (typeof value === "string")
1437
+ return stripMarkdownString(value);
1438
+ if (Array.isArray(value))
1439
+ return value.map(normalizeMermaidText).join("\n");
1440
+ if (typeof value === "object") {
1441
+ if (typeof value.text === "string")
1442
+ return stripMarkdownString(value.text);
1443
+ if (typeof value.label === "string")
1444
+ return stripMarkdownString(value.label);
1445
+ if (typeof value.markdown === "string")
1446
+ return stripMarkdownString(value.markdown);
1447
+ }
1448
+ return stripMarkdownString(value.toString());
1449
+ }
1450
+
1451
+ function stripMarkdownString(value: string) {
1452
+ let result = value;
1453
+ if (result.startsWith("`") && result.endsWith("`") && result.length >= 2)
1454
+ result = result.substring(1, result.length - 1);
1455
+ return normalizeLabelLineBreaks(result);
1456
+ }
1457
+
1458
+ function mergeNode(nodes: Map<string, ParsedNode>, node: ParsedNode) {
1459
+ const existing = nodes.get(node.id);
1460
+ if (!existing || existing.label === existing.id || node.label !== node.id)
1461
+ nodes.set(node.id, node);
1462
+ }
1463
+
1464
+ function parseNode(line: string, sourceStart?: number): ParsedNode {
1465
+ const cursor = new SourceCursor(line);
1466
+ const id = cursor.readIdentifier();
1467
+ if (!id)
1468
+ return null;
1469
+
1470
+ cursor.skipWhitespace();
1471
+ const value = cursor.readRest().trim();
1472
+ const parsedShape = parseShapeValue(id, value);
1473
+ if (!parsedShape)
1474
+ return null;
1475
+
1476
+ return {
1477
+ ...parsedShape,
1478
+ sourceRange: sourceStart == null ? undefined : { start: sourceStart, length: line.length },
1479
+ };
1480
+ }
1481
+
1482
+ function parseMindmapNode(line: string, index: number, parentId: string, sourceStart: number, sourceLength: number, indent: number): ParsedMindmapNode {
1483
+ const parsedNode = parseNode(line);
1484
+ if (parsedNode) {
1485
+ return {
1486
+ id: parsedNode.id,
1487
+ parentId,
1488
+ label: parsedNode.label,
1489
+ shape: mapMindmapShape(parsedNode.shape),
1490
+ indent,
1491
+ sourceRange: { start: sourceStart, length: sourceLength },
1492
+ };
1493
+ }
1494
+
1495
+ const id = sanitizeMindmapId(line, index);
1496
+ return {
1497
+ id,
1498
+ parentId,
1499
+ label: unquoteLabel(line),
1500
+ shape: "default",
1501
+ indent,
1502
+ sourceRange: { start: sourceStart, length: sourceLength },
1503
+ };
1504
+ }
1505
+
1506
+ function parseEdge(line: string, sourceStart: number): ParsedEdge & { fromNode: ParsedNode; toNode: ParsedNode } {
1507
+ const parsed = parseFlowchartEdgeStatement(line);
1508
+ if (!parsed)
1509
+ return null;
1510
+
1511
+ const fromNode = parseNodeToken(parsed.left);
1512
+ const toNode = parseNodeToken(parsed.right);
1513
+ if (!fromNode || !toNode)
1514
+ return null;
1515
+
1516
+ fromNode.sourceRange = { start: sourceStart + parsed.leftStart + parsed.left.indexOf(fromNode.id), length: fromNode.id.length };
1517
+ toNode.sourceRange = { start: sourceStart + parsed.rightStart + parsed.right.indexOf(toNode.id), length: toNode.id.length };
1518
+
1519
+ return {
1520
+ from: fromNode.id,
1521
+ to: toNode.id,
1522
+ fromNode,
1523
+ toNode,
1524
+ label: parsed.label,
1525
+ edgeType: getEdgeType(parsed.operator),
1526
+ connector: parsed.operator,
1527
+ edgeId: parsed.edgeId,
1528
+ connectorRange: { start: sourceStart + parsed.operatorStart, length: parsed.operator.length + parsed.labelPartLength },
1529
+ sourceRange: { start: sourceStart, length: line.length },
1530
+ };
1531
+ }
1532
+
1533
+ function parseNodeToken(token: string): ParsedNode {
1534
+ const node = parseNode(token);
1535
+ if (node)
1536
+ return node;
1537
+
1538
+ const id = new SourceCursor(token).readIdentifier();
1539
+ return id ? { id, label: id, shape: "rectangle" } : null;
1540
+ }
1541
+
1542
+ function parseShapeValue(id: string, value: string): ParsedNode {
1543
+ if (!value)
1544
+ return { id, label: id, shape: "rectangle" };
1545
+
1546
+ const expandedShape = parseExpandedShape(value);
1547
+ if (expandedShape)
1548
+ return { id, label: expandedShape.label ?? id, shape: mapExpandedShape(expandedShape.shape) };
1549
+
1550
+ const shapeValue = parseDelimitedShapeValue(value);
1551
+ if (shapeValue)
1552
+ return { id, label: unquoteLabel(shapeValue.label), shape: shapeValue.shape };
1553
+
1554
+ return null;
1555
+ }
1556
+
1557
+ function getEdgeType(connector: string) {
1558
+ if (connector.includes("~"))
1559
+ return "invisible";
1560
+ if (connector.includes("o"))
1561
+ return "circle";
1562
+ if (connector.includes("x"))
1563
+ return "cross";
1564
+ if (connector.startsWith("<") && connector.endsWith(">"))
1565
+ return "multi";
1566
+ if (connector.includes("=="))
1567
+ return "thick";
1568
+ if (connector.includes("-."))
1569
+ return "dotted";
1570
+ if (!connector.includes(">"))
1571
+ return "open";
1572
+ return "arrow";
1573
+ }
1574
+
1575
+ function unquoteLabel(label: string) {
1576
+ let result = label.trim();
1577
+ if (result.length >= 2) {
1578
+ const first = result[0];
1579
+ const last = result[result.length - 1];
1580
+ if ((first === "\"" && last === "\"") || (first === "'" && last === "'"))
1581
+ result = result.substring(1, result.length - 1);
1582
+ }
1583
+ return normalizeLabelLineBreaks(result);
1584
+ }
1585
+
1586
+ function mapExpandedShape(shape: string) {
1587
+ switch (shape) {
1588
+ case "rect":
1589
+ case "proc":
1590
+ case "process":
1591
+ case "rectangle":
1592
+ return "rectangle";
1593
+ case "bang":
1594
+ return "bang";
1595
+ case "notch-rect":
1596
+ case "card":
1597
+ case "notched-rectangle":
1598
+ return "notch-rect";
1599
+ case "cloud":
1600
+ return "cloud";
1601
+ case "hourglass":
1602
+ case "collate":
1603
+ return "hourglass";
1604
+ case "bolt":
1605
+ case "com-link":
1606
+ case "lightning-bolt":
1607
+ return "bolt";
1608
+ case "brace":
1609
+ case "brace-l":
1610
+ case "comment":
1611
+ return "brace";
1612
+ case "brace-r":
1613
+ return "brace-r";
1614
+ case "braces":
1615
+ return "braces";
1616
+ case "datastore":
1617
+ case "data-store":
1618
+ return "datastore";
1619
+ case "delay":
1620
+ case "half-rounded-rectangle":
1621
+ return "delay";
1622
+ case "h-cyl":
1623
+ case "das":
1624
+ case "horizontal-cylinder":
1625
+ return "h-cyl";
1626
+ case "lin-cyl":
1627
+ case "disk":
1628
+ case "lined-cylinder":
1629
+ return "lin-cyl";
1630
+ case "curv-trap":
1631
+ case "curved-trapezoid":
1632
+ case "display":
1633
+ return "curv-trap";
1634
+ case "div-rect":
1635
+ case "div-proc":
1636
+ case "divided-process":
1637
+ case "divided-rectangle":
1638
+ return "div-rect";
1639
+ case "doc":
1640
+ case "document":
1641
+ return "doc";
1642
+ case "tri":
1643
+ case "extract":
1644
+ case "triangle":
1645
+ return "tri";
1646
+ case "fork":
1647
+ case "join":
1648
+ return "fork";
1649
+ case "win-pane":
1650
+ case "internal-storage":
1651
+ case "window-pane":
1652
+ return "win-pane";
1653
+ case "f-circ":
1654
+ case "filled-circle":
1655
+ case "junction":
1656
+ return "f-circ";
1657
+ case "lin-doc":
1658
+ case "lined-document":
1659
+ return "lin-doc";
1660
+ case "lin-rect":
1661
+ case "lin-proc":
1662
+ case "lined-process":
1663
+ case "lined-rectangle":
1664
+ case "shaded-process":
1665
+ return "lin-rect";
1666
+ case "notch-pent":
1667
+ case "loop-limit":
1668
+ case "notched-pentagon":
1669
+ return "notch-pent";
1670
+ case "flip-tri":
1671
+ case "flipped-triangle":
1672
+ case "manual-file":
1673
+ return "flip-tri";
1674
+ case "sl-rect":
1675
+ case "manual-input":
1676
+ case "sloped-rectangle":
1677
+ return "sl-rect";
1678
+ case "docs":
1679
+ case "documents":
1680
+ case "st-doc":
1681
+ case "stacked-document":
1682
+ return "docs";
1683
+ case "st-rect":
1684
+ case "processes":
1685
+ case "procs":
1686
+ case "stacked-rectangle":
1687
+ return "st-rect";
1688
+ case "odd":
1689
+ return "asymmetric";
1690
+ case "flag":
1691
+ case "paper-tape":
1692
+ return "flag";
1693
+ case "bow-rect":
1694
+ case "bow-tie-rectangle":
1695
+ case "stored-data":
1696
+ return "bow-rect";
1697
+ case "fr-circ":
1698
+ case "framed-circle":
1699
+ case "stop":
1700
+ return "fr-circ";
1701
+ case "cross-circ":
1702
+ case "crossed-circle":
1703
+ case "summary":
1704
+ return "cross-circ";
1705
+ case "tag-doc":
1706
+ case "tagged-document":
1707
+ return "tag-doc";
1708
+ case "tag-rect":
1709
+ case "tag-proc":
1710
+ case "tagged-process":
1711
+ case "tagged-rectangle":
1712
+ return "tag-rect";
1713
+ case "text":
1714
+ return "text";
1715
+ case "diam":
1716
+ case "diamond":
1717
+ case "decision":
1718
+ case "question":
1719
+ return "decision";
1720
+ case "rounded":
1721
+ case "round":
1722
+ return "round";
1723
+ case "stadium":
1724
+ case "terminal":
1725
+ return "stadium";
1726
+ case "subroutine":
1727
+ case "subprocess":
1728
+ case "subproc":
1729
+ case "fr-rect":
1730
+ return "subroutine";
1731
+ case "cyl":
1732
+ case "cylinder":
1733
+ case "database":
1734
+ case "db":
1735
+ return "cylinder";
1736
+ case "hex":
1737
+ case "hexagon":
1738
+ return "hexagon";
1739
+ case "circle":
1740
+ return "circle";
1741
+ case "dbl-circ":
1742
+ case "double-circle":
1743
+ return "doubleCircle";
1744
+ case "lean-r":
1745
+ case "in-out":
1746
+ case "lean-right":
1747
+ return "parallelogram";
1748
+ case "lean-l":
1749
+ case "lean-left":
1750
+ case "out-in":
1751
+ return "parallelogramAlt";
1752
+ case "trap-b":
1753
+ case "priority":
1754
+ case "trapezoid":
1755
+ case "trapezoid-bottom":
1756
+ return "trapezoid";
1757
+ case "trap-t":
1758
+ case "inv-trapezoid":
1759
+ case "manual":
1760
+ case "trapezoid-top":
1761
+ return "trapezoidAlt";
1762
+ default:
1763
+ return "rectangle";
1764
+ }
1765
+ }
1766
+
1767
+ function mapMindmapShape(shape: string) {
1768
+ switch (shape) {
1769
+ case "rectangle":
1770
+ return "square";
1771
+ case "round":
1772
+ case "circle":
1773
+ case "hexagon":
1774
+ return shape;
1775
+ default:
1776
+ return "default";
1777
+ }
1778
+ }
1779
+
1780
+ function sanitizeMindmapId(label: string, index: number) {
1781
+ let result = "";
1782
+ for (const char of label) {
1783
+ if (isIdentifierPart(char))
1784
+ result += char;
1785
+ else if (isWhitespace(char) && result && result[result.length - 1] !== "_")
1786
+ result += "_";
1787
+ }
1788
+ result = result.trim();
1789
+ return result || "mindmap_" + index;
1790
+ }
1791
+
1792
+ function sanitizeDirectiveId(label: string) {
1793
+ let result = "";
1794
+ for (const char of label) {
1795
+ if (isIdentifierPart(char))
1796
+ result += char;
1797
+ else if (isWhitespace(char) && result && result[result.length - 1] !== "_")
1798
+ result += "_";
1799
+ }
1800
+ return result || "subgraph";
1801
+ }
1802
+
1803
+ function getDefaultMindmapNodeSize(shape: string) {
1804
+ switch (shape) {
1805
+ case "circle":
1806
+ case "bang":
1807
+ return { width: 88, height: 88 };
1808
+ case "hexagon":
1809
+ return { width: 150, height: 58 };
1810
+ default:
1811
+ return { width: 150, height: 44 };
1812
+ }
1813
+ }
1814
+
1815
+ function getDefaultRequirementNodeSize(node: ParsedRequirementNode) {
1816
+ if (node.kind === "element")
1817
+ return { width: 170, height: node.docRef ? 108 : 84 };
1818
+ return { width: 220, height: 160 };
1819
+ }
1820
+
1821
+ function getDefaultNodeSize(shape: string) {
1822
+ switch (shape) {
1823
+ case "decision":
1824
+ return { width: 120, height: 80 };
1825
+ case "circle":
1826
+ case "doubleCircle":
1827
+ case "fr-circ":
1828
+ case "cross-circ":
1829
+ case "f-circ":
1830
+ return { width: 80, height: 80 };
1831
+ case "bang":
1832
+ return { width: 92, height: 92 };
1833
+ case "fork":
1834
+ return { width: 140, height: 28 };
1835
+ case "tri":
1836
+ case "flip-tri":
1837
+ return { width: 110, height: 90 };
1838
+ case "brace":
1839
+ case "brace-r":
1840
+ case "braces":
1841
+ case "text":
1842
+ return { width: 140, height: 54 };
1843
+ default:
1844
+ return { width: 120, height: 54 };
1845
+ }
1846
+ }
1847
+
1848
+ function getFallbackRequirementNodePosition(index: number, total: number, direction: FlowchartDirection) {
1849
+ const columns = direction === "LR" || direction === "RL" ? Math.max(1, Math.ceil(total / 3)) : 3;
1850
+ const column = index % columns;
1851
+ const row = Math.floor(index / columns);
1852
+ const left = 40 + column * 300;
1853
+ const top = 40 + row * 230;
1854
+ if (direction === "RL")
1855
+ return { left: 40 + (columns - column - 1) * 300, top };
1856
+ if (direction === "BT")
1857
+ return { left, top: 40 + (Math.ceil(total / columns) - row - 1) * 230 };
1858
+ return { left, top };
1859
+ }
1860
+
1861
+ function getFallbackFlowchartNodePosition(index: number, count: number, direction: FlowchartDirection) {
1862
+ const xStep = 180;
1863
+ const yStep = 110;
1864
+ switch (direction) {
1865
+ case "LR":
1866
+ return { left: 40 + index * xStep, top: 40 };
1867
+ case "RL":
1868
+ return { left: 40 + (count - index - 1) * xStep, top: 40 };
1869
+ case "BT":
1870
+ return { left: 40, top: 40 + (count - index - 1) * yStep };
1871
+ case "TD":
1872
+ case "TB":
1873
+ default:
1874
+ return { left: 40, top: 40 + index * yStep };
1875
+ }
1876
+ }
1877
+
1878
+ function readMermaidDocument(text: string): ParsedMermaidDocument {
1879
+ const lines = getLineRecords(text);
1880
+ if (lines[0]?.trimmed !== "---")
1881
+ return { lines, title: "", frontmatter: "" };
1882
+
1883
+ let frontmatterEnd = -1;
1884
+ for (let i = 1; i < lines.length; i++) {
1885
+ if (lines[i].trimmed === "---") {
1886
+ frontmatterEnd = i;
1887
+ break;
1888
+ }
1889
+ }
1890
+
1891
+ if (frontmatterEnd < 0)
1892
+ return { lines, title: "", frontmatter: "" };
1893
+
1894
+ const frontmatterLines = lines.slice(1, frontmatterEnd);
1895
+
1896
+ return {
1897
+ lines: lines.filter((_, index) => index > frontmatterEnd),
1898
+ title: readFrontmatterTitle(frontmatterLines),
1899
+ frontmatter: readFrontmatterWithoutTitle(frontmatterLines),
1900
+ };
1901
+ }
1902
+
1903
+ function readFrontmatterTitle(lines: LineRecord[]) {
1904
+ for (const line of lines) {
1905
+ const separator = line.trimmed.indexOf(":");
1906
+ if (separator < 0)
1907
+ continue;
1908
+ const key = line.trimmed.substring(0, separator).trim();
1909
+ if (equalsIgnoreCase(key, "title"))
1910
+ return unquoteLabel(line.trimmed.substring(separator + 1).trim());
1911
+ }
1912
+ return "";
1913
+ }
1914
+
1915
+ function readFrontmatterWithoutTitle(lines: LineRecord[]) {
1916
+ const remainingLines: string[] = [];
1917
+ for (let i = 0; i < lines.length; i++) {
1918
+ const line = lines[i];
1919
+ const separator = line.trimmed.indexOf(":");
1920
+ const key = separator >= 0 ? line.trimmed.substring(0, separator).trim() : "";
1921
+ if (equalsIgnoreCase(key, "title"))
1922
+ continue;
1923
+ remainingLines.push(line.text);
1924
+ }
1925
+ return trimBlankLines(remainingLines).join("\n");
1926
+ }
1927
+
1928
+ function trimBlankLines(lines: string[]) {
1929
+ let start = 0;
1930
+ let end = lines.length;
1931
+ while (start < end && !lines[start].trim())
1932
+ start++;
1933
+ while (end > start && !lines[end - 1].trim())
1934
+ end--;
1935
+ return lines.slice(start, end);
1936
+ }
1937
+
1938
+ function getLineRecords(text: string) {
1939
+ const records: LineRecord[] = [];
1940
+ let offset = 0;
1941
+ for (const line of splitLines(text)) {
1942
+ const leadingWhitespaceLength = countLeadingWhitespace(line);
1943
+ records.push({ text: line, trimmed: line.trim(), indent: leadingWhitespaceLength, start: offset + leadingWhitespaceLength });
1944
+ offset += line.length + 1;
1945
+ }
1946
+ return records;
1947
+ }
1948
+
1949
+ function splitLines(text: string) {
1950
+ const lines: string[] = [];
1951
+ let start = 0;
1952
+ for (let i = 0; i < text.length; i++) {
1953
+ if (text[i] === "\n") {
1954
+ let end = i;
1955
+ if (end > start && text[end - 1] === "\r")
1956
+ end--;
1957
+ lines.push(text.substring(start, end));
1958
+ start = i + 1;
1959
+ }
1960
+ }
1961
+ lines.push(text.substring(start));
1962
+ return lines;
1963
+ }
1964
+
1965
+ function getDiagramDirection(designItems: IDesignItem[]) {
1966
+ const rootDesignItem = getRootDesignItem(designItems);
1967
+ const rootDirection = rootDesignItem?.getAttribute(mermaidFlowchartDirectionAttribute);
1968
+ if (isFlowchartDirection(rootDirection))
1969
+ return rootDirection;
1970
+
1971
+ for (const designItem of designItems) {
1972
+ const direction = designItem.element.getAttribute("diagram-direction");
1973
+ if (isFlowchartDirection(direction))
1974
+ return direction;
1975
+ }
1976
+ return inferDiagramDirection(designItems);
1977
+ }
1978
+
1979
+ function inferDiagramDirection(designItems: IDesignItem[]): FlowchartDirection {
1980
+ const nodes = designItems
1981
+ .filter(designItem => designItem.element.localName === "mermaid-node")
1982
+ .map(designItem => {
1983
+ const element = designItem.element as HTMLElement;
1984
+ return {
1985
+ left: Number.parseFloat(element.style.left || "0"),
1986
+ top: Number.parseFloat(element.style.top || "0"),
1987
+ };
1988
+ });
1989
+
1990
+ if (nodes.length < 2)
1991
+ return "TD";
1992
+
1993
+ const first = nodes[0];
1994
+ const last = nodes[nodes.length - 1];
1995
+ const dx = last.left - first.left;
1996
+ const dy = last.top - first.top;
1997
+
1998
+ if (Math.abs(dx) > Math.abs(dy))
1999
+ return dx >= 0 ? "LR" : "RL";
2000
+
2001
+ return dy >= 0 ? "TD" : "BT";
2002
+ }
2003
+
2004
+ function isFlowchartDirection(value: string): value is FlowchartDirection {
2005
+ return value === "TB" || value === "TD" || value === "BT" || value === "RL" || value === "LR";
2006
+ }
2007
+
2008
+ function isRequirementDirection(value: string): value is FlowchartDirection {
2009
+ return value === "TB" || value === "BT" || value === "RL" || value === "LR";
2010
+ }
2011
+
2012
+ function setMermaidDocumentAttributes(instanceServiceContainer: InstanceServiceContainer, diagramType: MermaidDocumentDiagramType, direction?: FlowchartDirection, title?: string, frontmatter?: string) {
2013
+ const rootDesignItem = instanceServiceContainer?.designerCanvas?.rootDesignItem;
2014
+ rootDesignItem?._withoutUndoSetAttribute(mermaidDiagramTypeAttribute, diagramType);
2015
+ if (direction)
2016
+ rootDesignItem?._withoutUndoSetAttribute(mermaidFlowchartDirectionAttribute, direction);
2017
+ else
2018
+ rootDesignItem?._withoutUndoRemoveAttribute(mermaidFlowchartDirectionAttribute);
2019
+ if (title)
2020
+ rootDesignItem?._withoutUndoSetAttribute(mermaidTitleAttribute, title);
2021
+ else
2022
+ rootDesignItem?._withoutUndoRemoveAttribute(mermaidTitleAttribute);
2023
+ if (frontmatter)
2024
+ rootDesignItem?._withoutUndoSetAttribute(mermaidFrontmatterAttribute, frontmatter);
2025
+ else
2026
+ rootDesignItem?._withoutUndoRemoveAttribute(mermaidFrontmatterAttribute);
2027
+ }
2028
+
2029
+ function writeMermaidFrontmatter(textWriter: ITextWriter, designItems: IDesignItem[], rootDesignItem?: IDesignItem) {
2030
+ const root = rootDesignItem ?? getRootDesignItem(designItems);
2031
+ const title = getMermaidDocumentTitle(root);
2032
+ const frontmatter = getMermaidDocumentFrontmatter(root);
2033
+ if (!title && !frontmatter)
2034
+ return;
2035
+ textWriter.writeLine("---");
2036
+ if (title)
2037
+ textWriter.writeLine("title: " + title);
2038
+ if (frontmatter) {
2039
+ for (const line of splitLines(frontmatter))
2040
+ textWriter.writeLine(line);
2041
+ }
2042
+ textWriter.writeLine("---");
2043
+ }
2044
+
2045
+ function getWritableDocumentDiagramType(designItems: IDesignItem[]): MermaidDocumentDiagramType {
2046
+ const hasSequenceItems = designItems.some(designItem => designItem.element.localName === MermaidSequenceParticipant.is || designItem.element.localName === MermaidSequenceMessage.is);
2047
+ const hasFlowchartItems = designItems.some(designItem => designItem.element.localName === MermaidNode.is || designItem.element.localName === MermaidEdge.is);
2048
+ const hasMindmapItems = designItems.some(designItem => designItem.element.localName === MermaidMindmapNode.is);
2049
+ const hasRequirementItems = designItems.some(designItem => designItem.element.localName === MermaidRequirementNode.is || designItem.element.localName === MermaidRequirementRelationship.is);
2050
+ const rootDesignItem = getRootDesignItem(designItems);
2051
+ const documentType = rootDesignItem ? getMermaidDocumentDiagramType(rootDesignItem) : null;
2052
+
2053
+ if (documentType === "requirementDiagram" && !hasFlowchartItems && !hasSequenceItems && !hasMindmapItems)
2054
+ return "requirementDiagram";
2055
+ if (documentType === "mindmap" && !hasFlowchartItems && !hasSequenceItems && !hasRequirementItems)
2056
+ return "mindmap";
2057
+ if (documentType === "sequenceDiagram" && !hasFlowchartItems && !hasMindmapItems && !hasRequirementItems)
2058
+ return "sequenceDiagram";
2059
+ if (documentType === "flowchart" && !hasSequenceItems && !hasMindmapItems && !hasRequirementItems)
2060
+ return "flowchart";
2061
+ if (hasRequirementItems)
2062
+ return "requirementDiagram";
2063
+ if (hasMindmapItems)
2064
+ return "mindmap";
2065
+ if (hasSequenceItems)
2066
+ return "sequenceDiagram";
2067
+ return "flowchart";
2068
+ }
2069
+
2070
+ function getRootDesignItem(designItems: IDesignItem[]) {
2071
+ return designItems[0]?.isRootItem ? designItems[0] : designItems[0]?.instanceServiceContainer?.designerCanvas?.rootDesignItem;
2072
+ }
2073
+
2074
+ function getMermaidDesignItems(designItems: IDesignItem[]) {
2075
+ if (designItems[0]?.isRootItem)
2076
+ return Array.from(designItems[0].children());
2077
+ return designItems;
2078
+ }
2079
+
2080
+ function getMindmapSortValue(designItem: IDesignItem) {
2081
+ const element = designItem.element as HTMLElement;
2082
+ const top = Number.parseFloat(element.style.top || "0");
2083
+ const left = Number.parseFloat(element.style.left || "0");
2084
+ return top * 10000 + left;
2085
+ }
2086
+
2087
+ function sortMindmapItems(items: IDesignItem[]) {
2088
+ return [...items].sort((a, b) => getMindmapSortValue(a) - getMindmapSortValue(b));
2089
+ }
2090
+
2091
+ function repeatText(value: string, count: number) {
2092
+ let result = "";
2093
+ for (let i = 0; i < count; i++)
2094
+ result += value;
2095
+ return result;
2096
+ }
2097
+
2098
+ function writeDesignItemLine(textWriter: ITextWriter, designItem: IDesignItem, line: string, updatePositions?: boolean) {
2099
+ const start = textWriter.position;
2100
+ line = indentEmbeddedNewlines(line);
2101
+ textWriter.writeLine(line);
2102
+ if (updatePositions)
2103
+ designItem.instanceServiceContainer.designItemDocumentPositionService?.setPosition(designItem, { start, length: line.length });
2104
+ }
2105
+
2106
+ function indentEmbeddedNewlines(line: string) {
2107
+ const newlineIndex = line.indexOf("\n");
2108
+ if (newlineIndex < 0)
2109
+ return line;
2110
+ const indent = line.substring(0, countLeadingWhitespace(line));
2111
+ return line.replaceAll("\n", "\n" + indent);
2112
+ }
2113
+
2114
+ async function getMermaidLayout(code: string, nodes: Map<string, ParsedNode>) {
2115
+ if (typeof document === "undefined" || typeof DOMParser === "undefined")
2116
+ return null;
2117
+
2118
+ try {
2119
+ const mermaid = await import("mermaid");
2120
+ const id = "mermaid-layout-" + Math.random().toString(36).slice(2);
2121
+ mermaid.default.initialize({ startOnLoad: false, securityLevel: "strict" });
2122
+ const result = await mermaid.default.render(id, code);
2123
+ const doc = new DOMParser().parseFromString(result.svg, "image/svg+xml");
2124
+ const layoutNodes = new Map<string, { x: number; y: number; width: number; height: number }>();
2125
+ const layoutSubgraphs = new Map<string, { x: number; y: number; width: number; height: number }>();
2126
+ let minX = Number.POSITIVE_INFINITY;
2127
+ let minY = Number.POSITIVE_INFINITY;
2128
+
2129
+ for (const nodeElement of Array.from(doc.querySelectorAll("g.node"))) {
2130
+ const nodeId = nodeElement.getAttribute("data-id") ?? getFlowchartNodeIdFromDomId(nodeElement.id);
2131
+ if (!nodeId || !nodes.has(nodeId))
2132
+ continue;
2133
+
2134
+ const center = parseTranslate(nodeElement.getAttribute("transform"));
2135
+ const size = getSvgNodeSize(nodeElement);
2136
+ const layout = {
2137
+ x: center.x - size.width / 2,
2138
+ y: center.y - size.height / 2,
2139
+ width: size.width,
2140
+ height: size.height,
2141
+ };
2142
+ layoutNodes.set(nodeId, layout);
2143
+ minX = Math.min(minX, layout.x);
2144
+ minY = Math.min(minY, layout.y);
2145
+ }
2146
+
2147
+ for (const clusterElement of Array.from(doc.querySelectorAll("g.cluster"))) {
2148
+ const clusterId = getClusterIdFromDomId(clusterElement.id, id);
2149
+ if (!clusterId)
2150
+ continue;
2151
+ const rect = clusterElement.querySelector("rect");
2152
+ if (!rect)
2153
+ continue;
2154
+ const translate = parseTranslate(clusterElement.getAttribute("transform"));
2155
+ const x = (Number.parseFloat(rect.getAttribute("x") ?? "0") || 0) + translate.x;
2156
+ const y = (Number.parseFloat(rect.getAttribute("y") ?? "0") || 0) + translate.y;
2157
+ const width = Number.parseFloat(rect.getAttribute("width") ?? "");
2158
+ const height = Number.parseFloat(rect.getAttribute("height") ?? "");
2159
+ if (!Number.isFinite(width) || !Number.isFinite(height))
2160
+ continue;
2161
+ const layout = { x, y, width, height };
2162
+ layoutSubgraphs.set(clusterId, layout);
2163
+ minX = Math.min(minX, layout.x);
2164
+ minY = Math.min(minY, layout.y);
2165
+ }
2166
+
2167
+ if (!layoutNodes.size && !layoutSubgraphs.size)
2168
+ return null;
2169
+
2170
+ const offsetX = 40 - minX;
2171
+ const offsetY = 40 - minY;
2172
+ for (const layout of layoutNodes.values()) {
2173
+ layout.x += offsetX;
2174
+ layout.y += offsetY;
2175
+ }
2176
+ for (const layout of layoutSubgraphs.values()) {
2177
+ layout.x += offsetX;
2178
+ layout.y += offsetY;
2179
+ }
2180
+
2181
+ return { nodes: layoutNodes, subgraphs: layoutSubgraphs };
2182
+ } catch {
2183
+ return null;
2184
+ }
2185
+ }
2186
+
2187
+ async function getMermaidRequirementLayout(code: string, nodes: Map<string, ParsedRequirementNode>) {
2188
+ if (typeof document === "undefined" || typeof DOMParser === "undefined")
2189
+ return null;
2190
+
2191
+ try {
2192
+ const mermaid = await import("mermaid");
2193
+ const id = "mermaid-requirement-layout-" + Math.random().toString(36).slice(2);
2194
+ mermaid.default.initialize({ startOnLoad: false, securityLevel: "strict" });
2195
+ const result = await mermaid.default.render(id, code);
2196
+ const doc = new DOMParser().parseFromString(result.svg, "image/svg+xml");
2197
+ const layoutNodes = new Map<string, { x: number; y: number; width: number; height: number }>();
2198
+ let minX = Number.POSITIVE_INFINITY;
2199
+ let minY = Number.POSITIVE_INFINITY;
2200
+
2201
+ for (const nodeElement of Array.from(doc.querySelectorAll("g.node"))) {
2202
+ const nodeId = getRequirementNodeIdFromSvgId(nodeElement.id, id, nodes);
2203
+ const node = nodeId ? nodes.get(nodeId) : null;
2204
+ if (!node)
2205
+ continue;
2206
+ const center = parseTranslate(nodeElement.getAttribute("transform"));
2207
+ const size = getDefaultRequirementNodeSize(node);
2208
+ const layout = {
2209
+ x: center.x - size.width / 2,
2210
+ y: center.y - size.height / 2,
2211
+ width: size.width,
2212
+ height: size.height,
2213
+ };
2214
+ layoutNodes.set(nodeId, layout);
2215
+ minX = Math.min(minX, layout.x);
2216
+ minY = Math.min(minY, layout.y);
2217
+ }
2218
+
2219
+ if (!layoutNodes.size)
2220
+ return null;
2221
+
2222
+ const offsetX = 40 - minX;
2223
+ const offsetY = 40 - minY;
2224
+ for (const layout of layoutNodes.values()) {
2225
+ layout.x += offsetX;
2226
+ layout.y += offsetY;
2227
+ }
2228
+
2229
+ return { nodes: layoutNodes };
2230
+ } catch {
2231
+ return null;
2232
+ }
2233
+ }
2234
+
2235
+ async function getMermaidMindmapLayout(code: string, nodes: ParsedMindmapNode[]) {
2236
+ if (typeof document === "undefined" || typeof DOMParser === "undefined")
2237
+ return null;
2238
+
2239
+ try {
2240
+ const mermaid = await import("mermaid");
2241
+ const id = "mermaid-mindmap-layout-" + Math.random().toString(36).slice(2);
2242
+ mermaid.default.initialize({ startOnLoad: false, securityLevel: "strict" });
2243
+ const result = await mermaid.default.render(id, code);
2244
+ const doc = new DOMParser().parseFromString(result.svg, "image/svg+xml");
2245
+ const layoutNodes = new Map<string, { x: number; y: number; width: number; height: number }>();
2246
+ const candidateElements = Array.from(doc.querySelectorAll("g.node.mindmap-node"));
2247
+ let minX = Number.POSITIVE_INFINITY;
2248
+ let minY = Number.POSITIVE_INFINITY;
2249
+ let nextNodeIndex = 0;
2250
+
2251
+ for (const nodeElement of candidateElements) {
2252
+ if (nextNodeIndex >= nodes.length)
2253
+ break;
2254
+ if (!nodeElement.querySelector("text, foreignObject"))
2255
+ continue;
2256
+
2257
+ const node = nodes[nextNodeIndex++];
2258
+ const center = parseTranslateFromElementTree(nodeElement);
2259
+ const size = getMindmapWidgetSize(getSvgNodeSize(nodeElement), node.shape);
2260
+ const layout = {
2261
+ x: center.x - size.width / 2,
2262
+ y: center.y - size.height / 2,
2263
+ width: size.width,
2264
+ height: size.height,
2265
+ };
2266
+ layoutNodes.set(node.id, layout);
2267
+ minX = Math.min(minX, layout.x);
2268
+ minY = Math.min(minY, layout.y);
2269
+ }
2270
+
2271
+ if (!layoutNodes.size)
2272
+ return null;
2273
+
2274
+ const offsetX = 40 - minX;
2275
+ const offsetY = 40 - minY;
2276
+ for (const layout of layoutNodes.values()) {
2277
+ layout.x += offsetX;
2278
+ layout.y += offsetY;
2279
+ }
2280
+
2281
+ return { nodes: layoutNodes };
2282
+ } catch {
2283
+ return null;
2284
+ }
2285
+ }
2286
+
2287
+ function parseTranslateFromElementTree(element: Element) {
2288
+ let x = 0;
2289
+ let y = 0;
2290
+ let current: Element = element;
2291
+ while (current) {
2292
+ const translate = parseTranslate(current.getAttribute("transform"));
2293
+ x += translate.x;
2294
+ y += translate.y;
2295
+ current = current.parentElement;
2296
+ }
2297
+ return { x, y };
2298
+ }
2299
+
2300
+ function parseTranslate(transform: string) {
2301
+ const values = parseTranslateValues(transform);
2302
+ return {
2303
+ x: values.x,
2304
+ y: values.y,
2305
+ };
2306
+ }
2307
+
2308
+ function getFlowchartNodeIdFromDomId(domId: string) {
2309
+ const prefix = "flowchart-";
2310
+ if (!domId?.startsWith(prefix))
2311
+ return "";
2312
+ const withoutPrefix = domId.substring(prefix.length);
2313
+ const lastDash = withoutPrefix.lastIndexOf("-");
2314
+ if (lastDash < 0)
2315
+ return withoutPrefix;
2316
+ const suffix = withoutPrefix.substring(lastDash + 1);
2317
+ return isAllDigits(suffix) ? withoutPrefix.substring(0, lastDash) : withoutPrefix;
2318
+ }
2319
+
2320
+ function getRequirementNodeIdFromSvgId(svgId: string, renderId: string, nodes: Map<string, ParsedRequirementNode>) {
2321
+ if (!svgId)
2322
+ return "";
2323
+ const prefix = renderId + "-";
2324
+ if (svgId.startsWith(prefix)) {
2325
+ const id = svgId.substring(prefix.length);
2326
+ if (nodes.has(id))
2327
+ return id;
2328
+ }
2329
+ let match = "";
2330
+ for (const id of nodes.keys()) {
2331
+ if (svgId.endsWith("-" + id) && id.length > match.length)
2332
+ match = id;
2333
+ }
2334
+ return match;
2335
+ }
2336
+
2337
+ function getClusterIdFromDomId(domId: string, renderId: string) {
2338
+ if (!domId)
2339
+ return "";
2340
+ const prefixes = [renderId + "_flowchart-", "flowchart-", renderId + "-", "cluster-"];
2341
+ for (const prefix of prefixes) {
2342
+ if (domId.startsWith(prefix))
2343
+ return domId.substring(prefix.length);
2344
+ }
2345
+ return domId;
2346
+ }
2347
+
2348
+ function parseTranslateValues(transform: string) {
2349
+ const result = { x: 0, y: 0 };
2350
+ if (!transform)
2351
+ return result;
2352
+ const name = "translate(";
2353
+ const start = transform.indexOf(name);
2354
+ if (start < 0)
2355
+ return result;
2356
+ const end = transform.indexOf(")", start + name.length);
2357
+ if (end < 0)
2358
+ return result;
2359
+ const content = transform.substring(start + name.length, end).trim();
2360
+ const separator = content.includes(",") ? content.indexOf(",") : content.indexOf(" ");
2361
+ if (separator < 0)
2362
+ return result;
2363
+ result.x = Number.parseFloat(content.substring(0, separator).trim()) || 0;
2364
+ result.y = Number.parseFloat(content.substring(separator + 1).trim()) || 0;
2365
+ return result;
2366
+ }
2367
+
2368
+ function findTopLevelColon(text: string) {
2369
+ let quote = "";
2370
+ for (let i = 0; i < text.length; i++) {
2371
+ const char = text[i];
2372
+ if (quote) {
2373
+ if (char === quote)
2374
+ quote = "";
2375
+ continue;
2376
+ }
2377
+ if (char === "\"" || char === "'") {
2378
+ quote = char;
2379
+ continue;
2380
+ }
2381
+ if (char === ":")
2382
+ return i;
2383
+ }
2384
+ return -1;
2385
+ }
2386
+
2387
+ function isRequirementType(value: string) {
2388
+ return equalsIgnoreCase(value, "requirement")
2389
+ || equalsIgnoreCase(value, "functionalRequirement")
2390
+ || equalsIgnoreCase(value, "interfaceRequirement")
2391
+ || equalsIgnoreCase(value, "performanceRequirement")
2392
+ || equalsIgnoreCase(value, "physicalRequirement")
2393
+ || equalsIgnoreCase(value, "designConstraint");
2394
+ }
2395
+
2396
+ function isRequirementRelationshipType(value: string) {
2397
+ return equalsIgnoreCase(value, "contains")
2398
+ || equalsIgnoreCase(value, "copies")
2399
+ || equalsIgnoreCase(value, "derives")
2400
+ || equalsIgnoreCase(value, "satisfies")
2401
+ || equalsIgnoreCase(value, "verifies")
2402
+ || equalsIgnoreCase(value, "refines")
2403
+ || equalsIgnoreCase(value, "traces");
2404
+ }
2405
+
2406
+ function isAllDigits(value: string) {
2407
+ if (!value)
2408
+ return false;
2409
+ for (const char of value) {
2410
+ if (!isAsciiDigit(char))
2411
+ return false;
2412
+ }
2413
+ return true;
2414
+ }
2415
+
2416
+ function getSvgNodeSize(nodeElement: Element) {
2417
+ const foreignObject = nodeElement.querySelector("foreignObject");
2418
+ if (foreignObject) {
2419
+ const width = Number.parseFloat(foreignObject.getAttribute("width") ?? "");
2420
+ const height = Number.parseFloat(foreignObject.getAttribute("height") ?? "");
2421
+ if (Number.isFinite(width) && Number.isFinite(height))
2422
+ return { width, height };
2423
+ }
2424
+
2425
+ const rect = nodeElement.querySelector("rect");
2426
+ if (rect) {
2427
+ const width = Number.parseFloat(rect.getAttribute("width") ?? "");
2428
+ const height = Number.parseFloat(rect.getAttribute("height") ?? "");
2429
+ if (Number.isFinite(width) && Number.isFinite(height))
2430
+ return { width, height };
2431
+ }
2432
+
2433
+ const polygon = nodeElement.querySelector("polygon");
2434
+ if (polygon) {
2435
+ const points = splitWhitespace(polygon.getAttribute("points") ?? "").map(point => {
2436
+ const [x, y] = point.split(",").map(Number);
2437
+ return { x, y };
2438
+ }).filter(point => Number.isFinite(point.x) && Number.isFinite(point.y));
2439
+ if (points.length) {
2440
+ const xs = points.map(point => point.x);
2441
+ const ys = points.map(point => point.y);
2442
+ return { width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) };
2443
+ }
2444
+ }
2445
+
2446
+ return { width: 120, height: 54 };
2447
+ }
2448
+
2449
+ function getMindmapWidgetSize(svgSize: { width: number; height: number }, shape: string) {
2450
+ const defaultSize = getDefaultMindmapNodeSize(shape);
2451
+ return {
2452
+ width: Math.max(svgSize.width, defaultSize.width),
2453
+ height: Math.max(svgSize.height, defaultSize.height),
2454
+ };
2455
+ }
2456
+
2457
+ function splitWhitespace(text: string) {
2458
+ const parts: string[] = [];
2459
+ let start = -1;
2460
+ for (let i = 0; i < text.length; i++) {
2461
+ if (isWhitespace(text[i])) {
2462
+ if (start >= 0) {
2463
+ parts.push(text.substring(start, i));
2464
+ start = -1;
2465
+ }
2466
+ } else if (start < 0) {
2467
+ start = i;
2468
+ }
2469
+ }
2470
+ if (start >= 0)
2471
+ parts.push(text.substring(start));
2472
+ return parts;
2473
+ }