@md2nativedocx/core 0.7.0 → 0.8.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.
Files changed (199) hide show
  1. package/dist/diagrams/architecture-diagram/icons.d.ts +24 -0
  2. package/dist/diagrams/architecture-diagram/icons.js +148 -0
  3. package/dist/diagrams/architecture-diagram/icons.js.map +1 -0
  4. package/dist/diagrams/architecture-diagram/layout.d.ts +71 -0
  5. package/dist/diagrams/architecture-diagram/layout.js +388 -0
  6. package/dist/diagrams/architecture-diagram/layout.js.map +1 -0
  7. package/dist/diagrams/architecture-diagram/parser.d.ts +14 -19
  8. package/dist/diagrams/architecture-diagram/parser.js +316 -113
  9. package/dist/diagrams/architecture-diagram/parser.js.map +1 -1
  10. package/dist/diagrams/architecture-diagram/translator.d.ts +26 -36
  11. package/dist/diagrams/architecture-diagram/translator.js +234 -147
  12. package/dist/diagrams/architecture-diagram/translator.js.map +1 -1
  13. package/dist/diagrams/architecture-diagram/types.d.ts +26 -16
  14. package/dist/diagrams/architecture-diagram/types.js +4 -14
  15. package/dist/diagrams/architecture-diagram/types.js.map +1 -1
  16. package/dist/diagrams/c4/parser.d.ts +11 -19
  17. package/dist/diagrams/c4/parser.js +242 -90
  18. package/dist/diagrams/c4/parser.js.map +1 -1
  19. package/dist/diagrams/c4/translator.d.ts +23 -43
  20. package/dist/diagrams/c4/translator.js +333 -204
  21. package/dist/diagrams/c4/translator.js.map +1 -1
  22. package/dist/diagrams/c4/types.d.ts +78 -45
  23. package/dist/diagrams/c4/types.js +17 -38
  24. package/dist/diagrams/c4/types.js.map +1 -1
  25. package/dist/diagrams/class-diagram/parser.d.ts +10 -11
  26. package/dist/diagrams/class-diagram/parser.js +316 -74
  27. package/dist/diagrams/class-diagram/parser.js.map +1 -1
  28. package/dist/diagrams/class-diagram/translator.d.ts +5 -0
  29. package/dist/diagrams/class-diagram/translator.js +292 -24
  30. package/dist/diagrams/class-diagram/translator.js.map +1 -1
  31. package/dist/diagrams/class-diagram/types.d.ts +61 -4
  32. package/dist/diagrams/er-diagram/parser.d.ts +22 -19
  33. package/dist/diagrams/er-diagram/parser.js +412 -89
  34. package/dist/diagrams/er-diagram/parser.js.map +1 -1
  35. package/dist/diagrams/er-diagram/translator.d.ts +8 -0
  36. package/dist/diagrams/er-diagram/translator.js +170 -38
  37. package/dist/diagrams/er-diagram/translator.js.map +1 -1
  38. package/dist/diagrams/er-diagram/types.d.ts +32 -5
  39. package/dist/diagrams/er-diagram/types.js +2 -5
  40. package/dist/diagrams/er-diagram/types.js.map +1 -1
  41. package/dist/diagrams/gantt/date-utils.d.ts +55 -33
  42. package/dist/diagrams/gantt/date-utils.js +147 -58
  43. package/dist/diagrams/gantt/date-utils.js.map +1 -1
  44. package/dist/diagrams/gantt/parser.d.ts +31 -22
  45. package/dist/diagrams/gantt/parser.js +259 -141
  46. package/dist/diagrams/gantt/parser.js.map +1 -1
  47. package/dist/diagrams/gantt/time-axis.d.ts +44 -0
  48. package/dist/diagrams/gantt/time-axis.js +158 -0
  49. package/dist/diagrams/gantt/time-axis.js.map +1 -0
  50. package/dist/diagrams/gantt/translator.d.ts +8 -5
  51. package/dist/diagrams/gantt/translator.js +67 -56
  52. package/dist/diagrams/gantt/translator.js.map +1 -1
  53. package/dist/diagrams/gantt/types.d.ts +25 -4
  54. package/dist/diagrams/gantt/types.js +4 -3
  55. package/dist/diagrams/gantt/types.js.map +1 -1
  56. package/dist/diagrams/mindmap/parser.d.ts +18 -14
  57. package/dist/diagrams/mindmap/parser.js +169 -69
  58. package/dist/diagrams/mindmap/parser.js.map +1 -1
  59. package/dist/diagrams/mindmap/translator.js +88 -35
  60. package/dist/diagrams/mindmap/translator.js.map +1 -1
  61. package/dist/diagrams/mindmap/types.d.ts +18 -0
  62. package/dist/diagrams/plantuml/class-parser.d.ts +2 -1
  63. package/dist/diagrams/plantuml/class-parser.js +19 -11
  64. package/dist/diagrams/plantuml/class-parser.js.map +1 -1
  65. package/dist/diagrams/plantuml/sequence-parser.d.ts +3 -2
  66. package/dist/diagrams/plantuml/sequence-parser.js +28 -12
  67. package/dist/diagrams/plantuml/sequence-parser.js.map +1 -1
  68. package/dist/diagrams/plantuml/state-parser.d.ts +5 -3
  69. package/dist/diagrams/plantuml/state-parser.js +141 -19
  70. package/dist/diagrams/plantuml/state-parser.js.map +1 -1
  71. package/dist/diagrams/requirement-diagram/parser.d.ts +26 -19
  72. package/dist/diagrams/requirement-diagram/parser.js +249 -70
  73. package/dist/diagrams/requirement-diagram/parser.js.map +1 -1
  74. package/dist/diagrams/requirement-diagram/translator.d.ts +16 -11
  75. package/dist/diagrams/requirement-diagram/translator.js +170 -50
  76. package/dist/diagrams/requirement-diagram/translator.js.map +1 -1
  77. package/dist/diagrams/requirement-diagram/types.d.ts +30 -9
  78. package/dist/diagrams/requirement-diagram/types.js +7 -5
  79. package/dist/diagrams/requirement-diagram/types.js.map +1 -1
  80. package/dist/diagrams/sequence/parser.d.ts +8 -7
  81. package/dist/diagrams/sequence/parser.js +100 -31
  82. package/dist/diagrams/sequence/parser.js.map +1 -1
  83. package/dist/diagrams/sequence/participant-glyph.d.ts +38 -0
  84. package/dist/diagrams/sequence/participant-glyph.js +97 -0
  85. package/dist/diagrams/sequence/participant-glyph.js.map +1 -0
  86. package/dist/diagrams/sequence/participant-kind.d.ts +7 -0
  87. package/dist/diagrams/sequence/participant-kind.js +19 -0
  88. package/dist/diagrams/sequence/participant-kind.js.map +1 -0
  89. package/dist/diagrams/sequence/translator.d.ts +7 -3
  90. package/dist/diagrams/sequence/translator.js +134 -25
  91. package/dist/diagrams/sequence/translator.js.map +1 -1
  92. package/dist/diagrams/sequence/types.d.ts +24 -1
  93. package/dist/diagrams/state-diagram/parser.d.ts +24 -24
  94. package/dist/diagrams/state-diagram/parser.js +259 -73
  95. package/dist/diagrams/state-diagram/parser.js.map +1 -1
  96. package/dist/diagrams/state-diagram/translator.d.ts +13 -1
  97. package/dist/diagrams/state-diagram/translator.js +554 -72
  98. package/dist/diagrams/state-diagram/translator.js.map +1 -1
  99. package/dist/diagrams/state-diagram/types.d.ts +57 -11
  100. package/dist/diagrams/state-diagram/types.js +5 -7
  101. package/dist/diagrams/state-diagram/types.js.map +1 -1
  102. package/dist/diagrams/tree-view/implicit-root.d.ts +11 -0
  103. package/dist/diagrams/tree-view/implicit-root.js +14 -0
  104. package/dist/diagrams/tree-view/implicit-root.js.map +1 -0
  105. package/dist/diagrams/tree-view/parser.d.ts +23 -8
  106. package/dist/diagrams/tree-view/parser.js +242 -98
  107. package/dist/diagrams/tree-view/parser.js.map +1 -1
  108. package/dist/diagrams/tree-view/translator.d.ts +6 -5
  109. package/dist/diagrams/tree-view/translator.js +40 -23
  110. package/dist/diagrams/tree-view/translator.js.map +1 -1
  111. package/dist/diagrams/tree-view/types.d.ts +22 -6
  112. package/dist/diagrams/tree-view/types.js +2 -2
  113. package/dist/diagrams/treemap/parser.d.ts +2 -2
  114. package/dist/diagrams/treemap/parser.js +5 -12
  115. package/dist/diagrams/treemap/parser.js.map +1 -1
  116. package/dist/diagrams/zenuml/parser.d.ts +2 -2
  117. package/dist/diagrams/zenuml/parser.js +14 -7
  118. package/dist/diagrams/zenuml/parser.js.map +1 -1
  119. package/dist/index.d.ts +1 -1
  120. package/dist/index.js +1 -1
  121. package/dist/index.js.map +1 -1
  122. package/dist/layout/collapse-subgraphs.d.ts +18 -0
  123. package/dist/layout/collapse-subgraphs.js +80 -0
  124. package/dist/layout/collapse-subgraphs.js.map +1 -0
  125. package/dist/layout/layout.d.ts +9 -0
  126. package/dist/layout/layout.js +77 -17
  127. package/dist/layout/layout.js.map +1 -1
  128. package/dist/parser/css-named-colors.d.ts +7 -0
  129. package/dist/parser/css-named-colors.js +157 -0
  130. package/dist/parser/css-named-colors.js.map +1 -0
  131. package/dist/parser/css-style.d.ts +39 -0
  132. package/dist/parser/css-style.js +88 -0
  133. package/dist/parser/css-style.js.map +1 -0
  134. package/dist/parser/entities.d.ts +5 -0
  135. package/dist/parser/entities.js +52 -0
  136. package/dist/parser/entities.js.map +1 -0
  137. package/dist/parser/frontmatter.d.ts +4 -2
  138. package/dist/parser/frontmatter.js +7 -5
  139. package/dist/parser/frontmatter.js.map +1 -1
  140. package/dist/parser/label.d.ts +37 -0
  141. package/dist/parser/label.js +73 -0
  142. package/dist/parser/label.js.map +1 -0
  143. package/dist/parser/parser.d.ts +2 -1
  144. package/dist/parser/parser.js +295 -329
  145. package/dist/parser/parser.js.map +1 -1
  146. package/dist/render-diagram-odf.d.ts +2 -1
  147. package/dist/render-diagram-odf.js +20 -5
  148. package/dist/render-diagram-odf.js.map +1 -1
  149. package/dist/render-diagram.d.ts +11 -3
  150. package/dist/render-diagram.js +44 -21
  151. package/dist/render-diagram.js.map +1 -1
  152. package/dist/smartart/chain.js +1 -1
  153. package/dist/smartart/chain.js.map +1 -1
  154. package/dist/smartart/cycle.js +1 -1
  155. package/dist/smartart/cycle.js.map +1 -1
  156. package/dist/smartart/drawing.js +2 -10
  157. package/dist/smartart/drawing.js.map +1 -1
  158. package/dist/smartart/embed.d.ts +4 -3
  159. package/dist/smartart/embed.js +5 -4
  160. package/dist/smartart/embed.js.map +1 -1
  161. package/dist/smartart/from-graph.d.ts +13 -3
  162. package/dist/smartart/from-graph.js +39 -7
  163. package/dist/smartart/from-graph.js.map +1 -1
  164. package/dist/smartart/from-tree.d.ts +9 -5
  165. package/dist/smartart/from-tree.js +23 -11
  166. package/dist/smartart/from-tree.js.map +1 -1
  167. package/dist/smartart/text.d.ts +18 -4
  168. package/dist/smartart/text.js +32 -8
  169. package/dist/smartart/text.js.map +1 -1
  170. package/dist/smartart/tree-deep.js +1 -1
  171. package/dist/smartart/tree-deep.js.map +1 -1
  172. package/dist/smartart/tree.js +2 -2
  173. package/dist/smartart/tree.js.map +1 -1
  174. package/dist/translator/boxes.d.ts +1 -1
  175. package/dist/translator/canvas.d.ts +9 -1
  176. package/dist/translator/canvas.js +19 -16
  177. package/dist/translator/canvas.js.map +1 -1
  178. package/dist/translator/custom-geometry.d.ts +28 -0
  179. package/dist/translator/custom-geometry.js +59 -0
  180. package/dist/translator/custom-geometry.js.map +1 -0
  181. package/dist/translator/elbow-connector.d.ts +52 -0
  182. package/dist/translator/elbow-connector.js +110 -0
  183. package/dist/translator/elbow-connector.js.map +1 -0
  184. package/dist/translator/graph-shapes.d.ts +17 -4
  185. package/dist/translator/graph-shapes.js +25 -6
  186. package/dist/translator/graph-shapes.js.map +1 -1
  187. package/dist/translator/label-runs.d.ts +14 -0
  188. package/dist/translator/label-runs.js +36 -0
  189. package/dist/translator/label-runs.js.map +1 -0
  190. package/dist/translator/odf-translator.js +20 -22
  191. package/dist/translator/odf-translator.js.map +1 -1
  192. package/dist/translator/ooxml-translator.d.ts +17 -11
  193. package/dist/translator/ooxml-translator.js +73 -139
  194. package/dist/translator/ooxml-translator.js.map +1 -1
  195. package/dist/translator/text-color.d.ts +9 -0
  196. package/dist/translator/text-color.js +17 -0
  197. package/dist/translator/text-color.js.map +1 -0
  198. package/dist/types.d.ts +20 -3
  199. package/package.json +1 -1
@@ -3,13 +3,16 @@
3
3
  *
4
4
  * V1 scope (spec §5.1): `graph`/`flowchart` with `TD`/`LR` direction only.
5
5
  * Supports node shapes from §6.1, edge types from §6.2, and `subgraph`
6
- * containers. `classDef`/`style` are intentionally ignored in V1 (§6.3).
6
+ * containers. `classDef` (including `default`), `class`/`:::` and `style` set a node's fill, stroke
7
+ * and text colour, layered as Mermaid layers them (see resolveNodeStyles); `linkStyle` an edge's.
7
8
  *
8
9
  * This module is a pure function from untrusted text to a typed AST. It never
9
10
  * emits XML itself — escaping happens in the translator.
10
11
  */
11
12
  import { splitLines, splitStatements } from './normalize-statements.js';
12
13
  import { INTERACTIVE_DIRECTIVES_IGNORED, isInteractiveDirective } from './interactive.js';
14
+ import { parseLabel } from './label.js';
15
+ import { extractNodeStyle, parseCssStyleProps, parseHexColor } from './css-style.js';
13
16
  /** Shape of a node based on its bracket syntax (spec §6.1). */
14
17
  const SHAPE_BY_SYNTAX = [
15
18
  // Longest/most specific patterns first, so e.g. `[[` matches subroutine
@@ -249,34 +252,48 @@ const EDGE_OPERATORS = [
249
252
  * {@link EdgeType} within that family. Only matched when no full token from
250
253
  * {@link EDGE_OPERATORS} already matched at the same position (checked first
251
254
  * in {@link parseEdgeChain}), so a plain `A-->B` is never reinterpreted here.
252
- * Each family's closings are ordered longest-token-first so e.g. `.-` doesn't
253
- * capture prematurely and strand the `>` of `.->`.
255
+ *
256
+ * As in Mermaid's grammar, a closing marker may be longer than its shortest
257
+ * form (`A-- No ---->B` is an arrow, a longer one in Mermaid's layout): a run
258
+ * of at least two dashes (or `=`) then the end character, or dots then `-`.
259
+ * Each family's closings are tried in order, arrow forms first, so a line
260
+ * form never captures the dashes of an arrow and strands its `>`.
254
261
  */
255
262
  const MID_LABEL_FAMILIES = [
256
263
  {
257
264
  open: '--',
258
265
  closings: [
259
- { token: '-->', type: 'arrow' },
260
- { token: '--o', type: 'circle' },
261
- { token: '--x', type: 'cross' },
262
- { token: '---', type: 'line' },
266
+ { pattern: /-{2,}>/y, type: 'arrow' },
267
+ { pattern: /-{2,}o/y, type: 'circle' },
268
+ { pattern: /-{2,}x/y, type: 'cross' },
269
+ { pattern: /-{3,}/y, type: 'line' },
263
270
  ],
264
271
  },
265
272
  {
266
273
  open: '-.',
267
274
  closings: [
268
- { token: '.->', type: 'dotted' },
269
- { token: '.-', type: 'dottedLine' },
275
+ { pattern: /\.+->/y, type: 'dotted' },
276
+ { pattern: /\.+-/y, type: 'dottedLine' },
270
277
  ],
271
278
  },
272
279
  {
273
280
  open: '==',
274
281
  closings: [
275
- { token: '==>', type: 'thick' },
276
- { token: '===', type: 'thickLine' },
282
+ { pattern: /={2,}>/y, type: 'thick' },
283
+ { pattern: /={3,}/y, type: 'thickLine' },
277
284
  ],
278
285
  },
279
286
  ];
287
+ /** Length of a closing marker of `family` starting at `at`, and its edge type; `null` if none starts there. */
288
+ function matchClosing(line, at, family) {
289
+ for (const closing of family.closings) {
290
+ closing.pattern.lastIndex = at;
291
+ const m = closing.pattern.exec(line);
292
+ if (m)
293
+ return { length: m[0].length, type: closing.type };
294
+ }
295
+ return null;
296
+ }
280
297
  /**
281
298
  * Node ids that collide with Object.prototype members. Dagre stores nodes in a
282
299
  * plain object, so an id like `__proto__`, `constructor`, or `length` would
@@ -314,184 +331,44 @@ function stripQuotedLabel(text) {
314
331
  }
315
332
  return text;
316
333
  }
317
- /** Mermaid's named HTML-derived entity codes (written without the leading
318
- * `&`, e.g. `#quot;`), the ones Mermaid's own docs call out explicitly. */
319
- const NAMED_ENTITIES = [
320
- ['quot', '"'],
321
- ['amp', '&'],
322
- ['lt', '<'],
323
- ['gt', '>'],
324
- ['nbsp', ' '],
325
- ['apos', "'"],
326
- ];
327
- /**
328
- * Parse the small set of inline-text conveniences Mermaid supports (found via
329
- * `docs/markdown-mermaid-compliance-table.md` §5, logged in `TODO.md`) into
330
- * both a flattened plain-text fallback (`text`, used for box-name attributes
331
- * and `layout.ts`'s width/height estimation — neither needs to know about a
332
- * bold/italic span) and a structured rich-text body (`runs`, `types.ts`'s
333
- * `LabelToken[]` — what the translator actually renders):
334
- * - Mermaid's entity codes (`#quot;`, `#9829;`, ...) are decoded to their
335
- * character first — the numeric form via its Unicode code point, plus the
336
- * handful of named entities Mermaid documents — regardless of the two
337
- * cases below.
338
- * - `<br/>` (and `<br>`, `<br />`, case-insensitive) becomes a real line
339
- * break: a `{ break: true }` token in `runs` (`text` flattens it to a
340
- * single space instead, same as before this function could produce real
341
- * breaks — a fallback string has nowhere to put a second line).
342
- * - A "Markdown string" (a label wrapped in backticks) has its delimiters
343
- * stripped, and `**bold**`/`__bold__`/`*italic*`/`_italic_` spans become
344
- * real `LabelRun.bold`/`.italic` tokens instead of literal asterisks or a
345
- * stripped-to-plain-text approximation. Emphasis markers are only
346
- * recognized inside a Markdown string — Mermaid's classic (non-backtick)
347
- * label syntax never interprets them, so a literal `**` in an ordinary
348
- * label stays literal, unchanged from before.
349
- */
350
- function parseLabel(text) {
351
- let decoded = text.replace(/#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)));
352
- for (const [name, char] of NAMED_ENTITIES) {
353
- decoded = decoded.split(`#${name};`).join(char);
354
- }
355
- const isMarkdownString = decoded.length >= 2 && decoded.startsWith('`') && decoded.endsWith('`');
356
- if (isMarkdownString)
357
- decoded = decoded.slice(1, -1);
358
- const segments = decoded.split(/<br\s*\/?>/gi);
359
- const runs = [];
360
- const plainSegments = [];
361
- segments.forEach((segment, i) => {
362
- if (i > 0)
363
- runs.push({ break: true });
364
- const segmentRuns = isMarkdownString
365
- ? parseEmphasis(segment)
366
- : segment.length > 0
367
- ? [{ text: segment }]
368
- : [];
369
- runs.push(...segmentRuns);
370
- plainSegments.push(segmentRuns.map((r) => r.text).join(''));
371
- });
372
- return { text: plainSegments.join(' '), runs };
373
- }
374
- /**
375
- * Split a Markdown-string segment (no `<br/>` in it — {@link parseLabel}
376
- * already split those out) into plain/bold/italic {@link LabelRun}s.
377
- * Non-nested and non-overlapping — CommonMark's full emphasis-resolution
378
- * algorithm is out of scope here (V1 tolerance, same spirit as the rest of
379
- * this parser); `**`/`__` (bold) is tried before `*`/`_` (italic) at each
380
- * position so a bold span is never misread as two italic markers.
381
- */
382
- function parseEmphasis(text) {
383
- const runs = [];
384
- const re = /(\*\*|__)([\s\S]+?)\1|(\*|_)([\s\S]+?)\3/g;
385
- let last = 0;
386
- let m;
387
- while ((m = re.exec(text)) !== null) {
388
- if (m.index > last)
389
- runs.push({ text: text.slice(last, m.index) });
390
- if (m[1] !== undefined)
391
- runs.push({ text: m[2], bold: true });
392
- else
393
- runs.push({ text: m[4], italic: true });
394
- last = re.lastIndex;
395
- }
396
- if (last < text.length)
397
- runs.push({ text: text.slice(last) });
398
- return runs;
399
- }
400
- /**
401
- * Parse a CSS-like `prop:value,prop:value` property list (`classDef`/`style`/
402
- * `linkStyle`, spec §6.3) into a lowercase-keyed map. Order-independent by
403
- * design — unlike the old `classDef` regex this replaces, which required
404
- * `fill:` to be the first (and only) property, silently failing the whole
405
- * line otherwise. Values that themselves contain a comma (e.g. a
406
- * `stroke-dasharray` list) will fragment here, but none of the properties
407
- * this parser actually reads (`fill`, `stroke`, `stroke-width`) are affected.
408
- */
409
- function parseCssStyleProps(text) {
410
- const props = new Map();
411
- for (const part of text.split(',')) {
412
- const i = part.indexOf(':');
413
- if (i === -1)
414
- continue;
415
- const key = part.slice(0, i).trim().toLowerCase();
416
- const value = part.slice(i + 1).trim();
417
- if (key.length > 0 && value.length > 0)
418
- props.set(key, value);
419
- }
420
- return props;
334
+ /** Record that `className` was assigned to `nodeId` (`class` or `:::`), in source order. */
335
+ function addNodeClass(nodeClasses, nodeId, className) {
336
+ if (!className)
337
+ return;
338
+ const list = nodeClasses.get(nodeId);
339
+ if (list)
340
+ list.push(className);
341
+ else
342
+ nodeClasses.set(nodeId, [className]);
421
343
  }
422
344
  /**
423
- * Normalize a CSS color value to a bare 6-digit uppercase hex string (what
424
- * the translator's `hexColor()` expects), expanding the 3-digit shorthand
425
- * (`#f9f` -> `FF99FF`). Returns `null` for anything else (a named color like
426
- * `red`, `transparent`, a `rgb(...)` call, ...) — deliberately out of scope,
427
- * same tolerant-degradation style as an unrecognized `@{shape: ...}` name:
428
- * the property is just dropped rather than failing the whole statement.
345
+ * Give every node its final colours, layered as Mermaid 12.3 layers them (`getCompiledStyles`
346
+ * in its flowchart database, then the node's inline styles): `classDef default`, `classDef node`,
347
+ * each class assigned to the node in source order, and last the node's `style` statements. This
348
+ * runs once the whole source is read, so a `classDef` or a node may come after the statement that
349
+ * refers to it. Returns the names assigned but never defined, in order of first assignment.
429
350
  */
430
- function parseHexColor(value) {
431
- const v = value.trim();
432
- const hex6 = v.match(/^#?([0-9A-Fa-f]{6})$/);
433
- if (hex6)
434
- return hex6[1].toUpperCase();
435
- const hex3 = v.match(/^#?([0-9A-Fa-f]{3})$/);
436
- if (hex3) {
437
- const [r, g, b] = hex3[1];
438
- return `${r}${r}${g}${g}${b}${b}`.toUpperCase();
351
+ function resolveNodeStyles(nodes, classDefs, nodeClasses, inlineStyles) {
352
+ const undefinedNames = new Set();
353
+ for (const names of nodeClasses.values()) {
354
+ for (const name of names)
355
+ if (!classDefs.has(name))
356
+ undefinedNames.add(name);
439
357
  }
440
- return null;
441
- }
442
- /** Extract `fill`/`stroke`/`color` from a parsed property map, dropping anything not
443
- * a recognized hex color (see {@link parseHexColor}). */
444
- function extractNodeStyle(props) {
445
- const patch = {};
446
- const fillValue = props.get('fill');
447
- if (fillValue) {
448
- const hex = parseHexColor(fillValue);
449
- if (hex)
450
- patch.fill = hex;
451
- }
452
- const strokeValue = props.get('stroke');
453
- if (strokeValue) {
454
- const hex = parseHexColor(strokeValue);
455
- if (hex)
456
- patch.stroke = hex;
457
- }
458
- const colorValue = props.get('color');
459
- if (colorValue) {
460
- const hex = parseHexColor(colorValue);
461
- if (hex)
462
- patch.color = hex;
463
- }
464
- return patch;
465
- }
466
- /**
467
- * Apply a `fill`/`stroke` patch to a node, or — if the node hasn't been
468
- * declared yet (a class/style referencing a node defined later in the
469
- * source) — remember it in `pendingStyles` for the end-of-parse sweep. Merges
470
- * onto whatever patch (if any) is already pending, so `style A stroke:#000`
471
- * followed later by `A:::crit` (a fill-only class) doesn't clobber the
472
- * stroke the first statement set.
473
- */
474
- function applyNodeStyle(nodes, pendingStyles, nodeId, patch) {
475
- if (patch.fill === undefined && patch.stroke === undefined && patch.color === undefined)
476
- return;
477
- const existing = nodes.get(nodeId);
478
- if (existing) {
358
+ for (const node of nodes.values()) {
359
+ const patch = {};
360
+ for (const name of ['default', 'node', ...(nodeClasses.get(node.id) ?? [])]) {
361
+ Object.assign(patch, classDefs.get(name));
362
+ }
363
+ Object.assign(patch, inlineStyles.get(node.id));
479
364
  if (patch.fill !== undefined)
480
- existing.fill = patch.fill;
365
+ node.fill = patch.fill;
481
366
  if (patch.stroke !== undefined)
482
- existing.stroke = patch.stroke;
367
+ node.stroke = patch.stroke;
483
368
  if (patch.color !== undefined)
484
- existing.textColor = patch.color;
485
- return;
369
+ node.textColor = patch.color;
486
370
  }
487
- const pending = pendingStyles.get(nodeId) ?? {};
488
- if (patch.fill !== undefined)
489
- pending.fill = patch.fill;
490
- if (patch.stroke !== undefined)
491
- pending.stroke = patch.stroke;
492
- if (patch.color !== undefined)
493
- pending.color = patch.color;
494
- pendingStyles.set(nodeId, pending);
371
+ return [...undefinedNames];
495
372
  }
496
373
  /**
497
374
  * Merge physical lines that a bracketed node label wraps across, e.g.
@@ -503,30 +380,40 @@ function applyNodeStyle(nodes, pendingStyles, nodeId, patch) {
503
380
  * edge — disconnecting the diagram. Found via medium-realistic.mmd
504
381
  * (2026-09-04). Lines that are already bracket-balanced (the common case)
505
382
  * flush immediately and are unaffected.
383
+ *
384
+ * A bracket or quote that never closes (`A[Receive ticket --> B[Assign crew]`) is a syntax error in
385
+ * Mermaid. Joining to the end of the block would turn every following line into that node's label and
386
+ * draw a single box; instead the line that opened it is kept as a statement of its own (read normally if
387
+ * it can be, e.g. a stray `\"` inside a quoted label, otherwise warned about as unclosed), and the lines
388
+ * after it are read again.
506
389
  */
507
390
  function joinBracketContinuations(lines) {
508
- const result = [];
509
- let buffer = [];
510
- let depth = 0;
511
- // Carried across lines: a quoted label may span several (`a["`Line1` / `Line 2`"]`), and its closing
512
- // quote must not be read as an opening one.
513
- let inQuotes = false;
514
- for (const line of lines) {
515
- buffer.push(line.trim());
516
- const scan = bracketDelta(line, inQuotes);
517
- depth += scan.delta;
518
- inQuotes = scan.inQuotes;
519
- if (depth <= 0) {
520
- result.push(buffer.join(' '));
521
- buffer = [];
522
- depth = 0;
523
- inQuotes = false;
391
+ const statements = [];
392
+ let pending = lines;
393
+ while (pending.length > 0) {
394
+ let buffer = [];
395
+ let depth = 0;
396
+ // Carried across lines: a quoted label may span several (`a["`Line1` / `Line 2`"]`), and its closing
397
+ // quote must not be read as an opening one.
398
+ let inQuotes = false;
399
+ for (const line of pending) {
400
+ buffer.push(line.trim());
401
+ const scan = bracketDelta(line, inQuotes);
402
+ depth += scan.delta;
403
+ inQuotes = scan.inQuotes;
404
+ if (depth <= 0) {
405
+ statements.push(buffer.join(' '));
406
+ buffer = [];
407
+ depth = 0;
408
+ inQuotes = false;
409
+ }
524
410
  }
411
+ if (buffer.length === 0)
412
+ break;
413
+ statements.push(buffer[0]);
414
+ pending = pending.slice(pending.length - buffer.length + 1);
525
415
  }
526
- if (buffer.length > 0) {
527
- result.push(buffer.join(' '));
528
- }
529
- return result;
416
+ return statements;
530
417
  }
531
418
  /**
532
419
  * Remove edge ids (`A e1@--> B`, `A e1@==> B`) from a statement, adding each to `edgeIds`. Only outside
@@ -590,20 +477,14 @@ export function parseMermaid(text) {
590
477
  const edges = [];
591
478
  const subgraphs = [];
592
479
  const subgraphStack = [];
593
- // Node ids whose subgraph membership (or lack of one) has already been
594
- // decided, by the first line that mentions them — see attachToCurrentSubgraph.
595
- const subgraphAttached = new Set();
480
+ // Node ids already kept by a subgraph that has closed — see closeSubgraph.
481
+ const claimedBySubgraph = new Set();
596
482
  // class name -> style patch, from `classDef` (spec §6.3).
597
483
  const classDefs = new Map();
598
- // node id -> style patch, for nodes styled (via class/`:::`/`style`) before they are defined.
599
- const pendingStyles = new Map();
600
- // Deferred `class`/`:::` assignments whose `classDef` hadn't been seen yet
601
- // at the point the assignment was parsed — `classDef` conventionally comes
602
- // first in a diagram but nothing requires it to; resolved once the whole
603
- // document (and therefore every `classDef`) is known, mirroring how
604
- // `pendingStyles` above already handles the opposite ordering (a class
605
- // applied to a node declared later in the source).
606
- const pendingClassAssignments = [];
484
+ // node id -> classes assigned by `class`/`:::`, and -> merged `style` statements; both resolved
485
+ // against `classDefs` once the whole source is read (resolveNodeStyles).
486
+ const nodeClasses = new Map();
487
+ const inlineStyles = new Map();
607
488
  // Deferred `linkStyle` statements (spec §6.3): applied after the full edge
608
489
  // list is known, since an index can refer to an edge declared later in the
609
490
  // source (the common case — `linkStyle` conventionally comes last).
@@ -614,15 +495,22 @@ export function parseMermaid(text) {
614
495
  // edge (`e1@{ animate: true }`, `class e1 animate`) are not taken for nodes.
615
496
  const edgeIds = new Set();
616
497
  const lines = rawLines.map((l) => stripEdgeIds(l, edgeIds));
498
+ // Ids given `view: collapsed` (`S@{ view: collapsed }`), see linkSubgraphEndpoints.
499
+ const collapsedViews = new Set();
617
500
  for (const rawLine of lines) {
618
501
  const line = rawLine.trim();
619
502
  if (line.length === 0)
620
503
  continue;
621
504
  // Edge metadata (`e1@{ animate: true, curve: linear }`): animation and per-edge curve have no
622
505
  // counterpart in a static Word drawing.
623
- const edgeMeta = /^([A-Za-z_][\w-]*)@\{.*\}$/.exec(line);
506
+ const edgeMeta = /^([A-Za-z_][\w-]*)@\{(.*)\}$/.exec(line);
624
507
  if (edgeMeta && edgeIds.has(edgeMeta[1]))
625
508
  continue;
509
+ // `S@{ view: collapsed }` folds a subgraph in Mermaid. Whether `S` is a subgraph is only known at
510
+ // the end (it may be declared later), so it is noted here and the line goes on as a node statement.
511
+ if (edgeMeta && parseAtShapeProps(edgeMeta[2]).get('view')?.toLowerCase() === 'collapsed') {
512
+ collapsedViews.add(edgeMeta[1]);
513
+ }
626
514
  if (isInteractiveDirective(line, ['click'])) {
627
515
  if (!warnings.includes(INTERACTIVE_DIRECTIVES_IGNORED))
628
516
  warnings.push(INTERACTIVE_DIRECTIVES_IGNORED);
@@ -676,23 +564,19 @@ export function parseMermaid(text) {
676
564
  .map((s) => s.trim())
677
565
  // A class on an edge id (`class e1 animate`) styles an edge animation, not a node.
678
566
  .filter((s) => s.length > 0 && !edgeIds.has(s));
679
- if (ids.length === 0)
680
- continue;
681
- const patch = classDefs.get(className);
682
- if (patch) {
683
- for (const id of ids)
684
- applyNodeStyle(nodes, pendingStyles, id, patch);
685
- }
686
- else {
687
- pendingClassAssignments.push({ nodeIds: ids, className });
688
- }
567
+ for (const id of ids)
568
+ addNodeClass(nodeClasses, id, className);
689
569
  continue;
690
570
  }
691
571
  // style A fill:#XXX,stroke:#XXX,... (spec §6.3) — direct styling, no
692
- // classDef indirection. Same property parser as classDef/linkStyle.
572
+ // classDef indirection, drawn over every class. Same property parser as classDef/linkStyle.
693
573
  const styleStmt = line.match(/^style\s+([A-Za-z0-9_-]+)\s+(.+)$/i);
694
574
  if (styleStmt) {
695
- applyNodeStyle(nodes, pendingStyles, styleStmt[1], extractNodeStyle(parseCssStyleProps(styleStmt[2])));
575
+ const id = styleStmt[1];
576
+ inlineStyles.set(id, {
577
+ ...inlineStyles.get(id),
578
+ ...extractNodeStyle(parseCssStyleProps(styleStmt[2])),
579
+ });
696
580
  continue;
697
581
  }
698
582
  // linkStyle 0,2 stroke:#XXX,stroke-width:Npx / linkStyle default ...
@@ -738,6 +622,7 @@ export function parseMermaid(text) {
738
622
  if (/^end\s*$/i.test(line)) {
739
623
  if (subgraphStack.length > 0) {
740
624
  const closed = subgraphStack.pop();
625
+ closeSubgraph(closed, claimedBySubgraph);
741
626
  const parent = subgraphStack[subgraphStack.length - 1];
742
627
  if (parent && !parent.subgraphIds.includes(closed.id)) {
743
628
  parent.subgraphIds.push(closed.id);
@@ -783,10 +668,10 @@ export function parseMermaid(text) {
783
668
  warnings.push(`Node id "${edge.to}" is reserved and was ignored.`);
784
669
  }
785
670
  // Apply inline class styles (`A:::crit`) to the edge endpoints.
786
- applyClassToNode(nodes, pendingStyles, classDefs, pendingClassAssignments, edge.from, edge.fromClass);
787
- applyClassToNode(nodes, pendingStyles, classDefs, pendingClassAssignments, edge.to, edge.toClass);
788
- attachToCurrentSubgraph(subgraphStack, edge.from, subgraphAttached);
789
- attachToCurrentSubgraph(subgraphStack, edge.to, subgraphAttached);
671
+ addNodeClass(nodeClasses, edge.from, edge.fromClass);
672
+ addNodeClass(nodeClasses, edge.to, edge.toClass);
673
+ mentionInCurrentSubgraph(subgraphStack, edge.from);
674
+ mentionInCurrentSubgraph(subgraphStack, edge.to);
790
675
  }
791
676
  continue;
792
677
  }
@@ -796,40 +681,17 @@ export function parseMermaid(text) {
796
681
  if (!registerNode(nodes, node.id, node.label, node.labelRuns, node.shape)) {
797
682
  warnings.push(`Node id "${node.id}" is reserved and was ignored.`);
798
683
  }
799
- applyClassToNode(nodes, pendingStyles, classDefs, pendingClassAssignments, node.id, node.className);
800
- attachToCurrentSubgraph(subgraphStack, node.id, subgraphAttached);
684
+ addNodeClass(nodeClasses, node.id, node.className);
685
+ mentionInCurrentSubgraph(subgraphStack, node.id);
801
686
  continue;
802
687
  }
803
688
  // Unsupported construct — warn but keep going (V1 tolerance).
804
- warnings.push(`Unsupported line ignored: ${line}`);
689
+ const reason = unsupportedLineReason(line);
690
+ warnings.push(reason ? `Unsupported line ignored (${reason}): ${line}` : `Unsupported line ignored: ${line}`);
805
691
  }
806
- // Resolve class/`:::` assignments whose `classDef` appeared later in the
807
- // source (or never at all) — a class name still undefined at this point,
808
- // once the whole document has been scanned, is a genuine typo/omission and
809
- // still warns, just later than before.
810
- for (const { nodeIds, className } of pendingClassAssignments) {
811
- const patch = classDefs.get(className);
812
- if (!patch) {
813
- warnings.push(`classDef "${className}" referenced but not defined.`);
814
- continue;
815
- }
816
- for (const id of nodeIds) {
817
- applyNodeStyle(nodes, pendingStyles, id, patch);
818
- }
819
- }
820
- // Apply any pending class/style patches (including ones just resolved
821
- // above) to nodes that were defined after the class/style statement that
822
- // targets them.
823
- for (const [id, patch] of pendingStyles) {
824
- const existing = nodes.get(id);
825
- if (existing) {
826
- if (patch.fill !== undefined)
827
- existing.fill = patch.fill;
828
- if (patch.stroke !== undefined)
829
- existing.stroke = patch.stroke;
830
- if (patch.color !== undefined)
831
- existing.textColor = patch.color;
832
- }
692
+ // A class name still undefined once the whole document is read is a typo or an omission.
693
+ for (const name of resolveNodeStyles(nodes, classDefs, nodeClasses, inlineStyles)) {
694
+ warnings.push(`classDef "${name}" referenced but not defined.`);
833
695
  }
834
696
  // Apply deferred `linkStyle` statements now that the edge list is final —
835
697
  // `default` covers every edge, otherwise each index picks one edge in
@@ -847,52 +709,111 @@ export function parseMermaid(text) {
847
709
  edge.strokeWidth = patch.strokeWidth;
848
710
  }
849
711
  }
850
- // A subgraph id must not also be a node: Mermaid allows edges between
851
- // subgraphs (e.g. `U1 --> Y2`), and our parser would otherwise register the
852
- // subgraph id as a plain node, which breaks Dagre (an id cannot be both a
853
- // node and a cluster). Drop such nodes and warn. Edges referencing subgraphs
854
- // as endpoints are dropped too (V1 does not support inter-subgraph edges).
855
- const subgraphIdSet = new Set(subgraphs.map((s) => s.id));
856
- for (const id of subgraphIdSet) {
857
- if (nodes.has(id)) {
858
- nodes.delete(id);
859
- warnings.push(`Subgraph "${id}" was also used as a node; node ignored.`);
860
- }
861
- }
862
- const edgesWithoutSubgraphs = edges.filter((e) => {
863
- if (subgraphIdSet.has(e.from) || subgraphIdSet.has(e.to)) {
864
- warnings.push(`Edge ${e.from} -> ${e.to} references a subgraph; ignored (V1).`);
865
- return false;
866
- }
867
- return true;
868
- });
869
712
  if (subgraphStack.length > 0) {
870
713
  warnings.push('Unclosed `subgraph` block.');
714
+ // Still drawn as if closed at the end, innermost first, as an `end` would have.
715
+ for (const open of [...subgraphStack].reverse())
716
+ closeSubgraph(open, claimedBySubgraph);
871
717
  }
718
+ // Before the node list is taken: this removes the nodes registered under a subgraph's id.
719
+ const keptEdges = linkSubgraphEndpoints(nodes, edges, subgraphs, collapsedViews, warnings);
872
720
  return {
873
721
  ast: {
874
722
  direction,
875
723
  nodes: [...nodes.values()],
876
- edges: edgesWithoutSubgraphs,
724
+ edges: keptEdges,
877
725
  subgraphs,
878
726
  },
879
727
  warnings,
880
728
  };
881
729
  }
730
+ /**
731
+ * Settle the links whose end is a subgraph (`A --> S`, `S1 --> S2`), which Mermaid draws to the
732
+ * subgraph's border. The parser registered such an end as a plain node; it is removed here, so that an
733
+ * id is never both a node and a subgraph, and the link keeps the subgraph's id as its end (see
734
+ * {@link FlowEdge}). A subgraph's member lists drop the subgraph ids a link inside it mentioned.
735
+ *
736
+ * Warned and dropped: a link between a subgraph and something inside it (no border to stop at), and a
737
+ * link to a subgraph with no node in it (no box to draw). Warned and kept: a node declared with its own
738
+ * label or shape under a subgraph's id (the subgraph wins, as in Mermaid's drawing). A subgraph given
739
+ * `view: collapsed` is marked {@link Subgraph.collapsed}.
740
+ */
741
+ function linkSubgraphEndpoints(nodes, edges, subgraphs, collapsedViews, warnings) {
742
+ const byId = new Map(subgraphs.map((s) => [s.id, s]));
743
+ for (const [id, sg] of byId) {
744
+ const node = nodes.get(id);
745
+ if (node) {
746
+ nodes.delete(id);
747
+ // `A --> S` registers `S` as a bare node: that is how a link to a subgraph is written.
748
+ if (node.label !== id || node.shape !== 'rect') {
749
+ warnings.push(`Subgraph "${id}" was also declared as a node; the node is not drawn.`);
750
+ }
751
+ }
752
+ sg.nodeIds = sg.nodeIds.filter((member) => !byId.has(member));
753
+ if (collapsedViews.has(id))
754
+ sg.collapsed = true;
755
+ }
756
+ // Everything inside a subgraph, nested subgraphs included, memoized: a link is checked at both ends.
757
+ const contents = new Map();
758
+ const contentsOf = (sg, seen = new Set()) => {
759
+ const known = contents.get(sg.id);
760
+ if (known)
761
+ return known;
762
+ const all = new Set(sg.nodeIds);
763
+ seen.add(sg.id);
764
+ for (const childId of sg.subgraphIds) {
765
+ const child = byId.get(childId);
766
+ // `seen` guards against a cycle, which the parser cannot build but a caller-made AST could.
767
+ if (!child || seen.has(childId))
768
+ continue;
769
+ all.add(childId);
770
+ for (const id of contentsOf(child, seen))
771
+ all.add(id);
772
+ }
773
+ contents.set(sg.id, all);
774
+ return all;
775
+ };
776
+ const hasNode = (sg) => [...contentsOf(sg)].some((id) => !byId.has(id));
777
+ return edges.filter((e) => {
778
+ for (const [end, other] of [
779
+ [e.from, e.to],
780
+ [e.to, e.from],
781
+ ]) {
782
+ const sg = byId.get(end);
783
+ if (!sg)
784
+ continue;
785
+ if (end === other || contentsOf(sg).has(other)) {
786
+ warnings.push(`Edge ${e.from} -> ${e.to} links subgraph "${end}" to something inside it; ignored.`);
787
+ return false;
788
+ }
789
+ if (!hasNode(sg)) {
790
+ warnings.push(`Edge ${e.from} -> ${e.to} links to subgraph "${end}", which holds no node; ignored.`);
791
+ return false;
792
+ }
793
+ }
794
+ return true;
795
+ });
796
+ }
882
797
  function parseSubgraphHeader(line) {
883
798
  const rest = line.replace(/^subgraph\b/i, '').trim();
799
+ // A title is read like a node label (Markdown string, `#name;` entities, `<br>`): the reader sees its
800
+ // text, never the syntax around it.
801
+ const title = (raw) => parseLabel(raw).text;
884
802
  // subgraph id["Title"] or subgraph id[Title] or subgraph "Title" or subgraph id
885
803
  const withTitle = rest.match(/^([A-Za-z0-9_-]+)\s*\[\s*"([^"]*)"\s*\]/);
886
804
  if (withTitle) {
887
- return { id: withTitle[1], title: withTitle[2], nodeIds: [], subgraphIds: [] };
805
+ return { id: withTitle[1], title: title(withTitle[2]), nodeIds: [], subgraphIds: [] };
888
806
  }
889
807
  const withTitleNoQuotes = rest.match(/^([A-Za-z0-9_-]+)\s*\[\s*([^\]]*)\s*\]/);
890
808
  if (withTitleNoQuotes) {
891
- return { id: withTitleNoQuotes[1], title: withTitleNoQuotes[2].trim(), nodeIds: [], subgraphIds: [] };
809
+ return { id: withTitleNoQuotes[1], title: title(withTitleNoQuotes[2].trim()), nodeIds: [], subgraphIds: [] };
892
810
  }
893
811
  const quotedTitle = rest.match(/^"([^"]+)"\s*$/);
894
812
  if (quotedTitle) {
895
- return { id: quotedTitle[1], title: quotedTitle[1], nodeIds: [], subgraphIds: [] };
813
+ // As in Mermaid, the id is the quoted text, without the backticks of a Markdown string.
814
+ const text = quotedTitle[1];
815
+ const id = text.length >= 2 && text.startsWith('`') && text.endsWith('`') ? text.slice(1, -1) : text;
816
+ return { id, title: title(text), nodeIds: [], subgraphIds: [] };
896
817
  }
897
818
  // Bare id (or id with spaces used as title).
898
819
  const bare = rest.match(/^([A-Za-z0-9_-]+)\s*$/);
@@ -903,22 +824,30 @@ function parseSubgraphHeader(line) {
903
824
  return { id: rest, title: rest, nodeIds: [], subgraphIds: [] };
904
825
  }
905
826
  /**
906
- * Attach a node to the innermost currently-open subgraph, but only the FIRST
907
- * time that node id is seen — matching Mermaid's own semantics, where a
908
- * node's subgraph membership is decided by where it's first declared, not by
909
- * every later line that happens to mention it. Without this, a node declared
910
- * inside a nested subgraph gets re-attached to an ENCLOSING subgraph the next
911
- * time an edge outside the nested block references it (e.g. `B --> C` after
912
- * `C`'s subgraph already closed), leaking it into the wrong cluster.
827
+ * Note that the innermost open subgraph mentions `nodeId` (a node statement or
828
+ * either end of a link inside it). Membership is settled when the subgraph
829
+ * closes, see {@link closeSubgraph}.
913
830
  */
914
- function attachToCurrentSubgraph(stack, nodeId, attached) {
915
- if (attached.has(nodeId))
916
- return;
917
- attached.add(nodeId);
831
+ function mentionInCurrentSubgraph(stack, nodeId) {
918
832
  const top = stack[stack.length - 1];
919
- if (top)
833
+ if (top && !top.nodeIds.includes(nodeId))
920
834
  top.nodeIds.push(nodeId);
921
835
  }
836
+ /**
837
+ * Settle a subgraph's members when it closes, the way Mermaid does: every node
838
+ * it mentions, wherever that node was first declared (`c1 --> a2` at the top,
839
+ * then `a1 --> a2` inside `one`, puts `a2` in `one`), except the nodes a
840
+ * subgraph that closed earlier already keeps. A nested subgraph closes before
841
+ * its parent, so `B --> C` written in the parent after the nested block keeps
842
+ * `C` in the nested subgraph; of two sibling subgraphs mentioning the same
843
+ * node, the first one to close keeps it. Checked against Mermaid itself on its
844
+ * official examples (`tools/mermaid-differential/`).
845
+ */
846
+ function closeSubgraph(subgraph, claimed) {
847
+ subgraph.nodeIds = subgraph.nodeIds.filter((id) => !claimed.has(id));
848
+ for (const id of subgraph.nodeIds)
849
+ claimed.add(id);
850
+ }
922
851
  function registerNode(nodes, id, label, labelRuns, shape = 'rect') {
923
852
  // Reject ids that collide with Object.prototype (Dagre breaks on them).
924
853
  if (!isSafeId(id))
@@ -931,24 +860,6 @@ function registerNode(nodes, id, label, labelRuns, shape = 'rect') {
931
860
  nodes.set(id, { id, label, labelRuns, shape });
932
861
  return true;
933
862
  }
934
- /**
935
- * Apply a class's style patch to a node (from `:::class` inline or `class`).
936
- * If the node is not yet defined, the patch is remembered in `pendingStyles`
937
- * (via {@link applyNodeStyle}). If the class itself isn't defined *yet* (its
938
- * `classDef` may still come later in the source), the assignment is queued in
939
- * `pendingClassAssignments` for the end-of-parse sweep instead of warning
940
- * immediately — see that array's doc comment in {@link parseMermaid}.
941
- */
942
- function applyClassToNode(nodes, pendingStyles, classDefs, pendingClassAssignments, nodeId, className) {
943
- if (!className)
944
- return;
945
- const patch = classDefs.get(className);
946
- if (!patch) {
947
- pendingClassAssignments.push({ nodeIds: [nodeId], className });
948
- return;
949
- }
950
- applyNodeStyle(nodes, pendingStyles, nodeId, patch);
951
- }
952
863
  /**
953
864
  * Parse a node statement like `A[Text]`, `B{Decision}`, or bare `C` —
954
865
  * including an optional inline class shorthand (`A[Text]:::crit` or bare
@@ -982,16 +893,77 @@ function parseNodeStatement(line) {
982
893
  className,
983
894
  };
984
895
  }
896
+ const bracketed = matchShapeSyntax(rest);
897
+ return bracketed ? { id, ...bracketed, className } : null;
898
+ }
899
+ /**
900
+ * Why a flowchart line could not be read, when the cause is one of the two mistakes seen most in
901
+ * generated diagrams (agent benchmark, 2026-11): a bracket or quote left open, or `->`, which is not a
902
+ * Mermaid link. `null` when neither applies. Text inside quotes and brackets is not looked at, so a label
903
+ * such as `A["x -> y"]` is not mistaken for a link.
904
+ */
905
+ function unsupportedLineReason(line) {
906
+ const scan = bracketDelta(line);
907
+ if (scan.delta > 0 || scan.inQuotes)
908
+ return 'unclosed bracket or quote';
909
+ let outside = '';
910
+ let depth = 0;
911
+ let inQuotes = false;
912
+ for (const ch of line) {
913
+ if (ch === '"')
914
+ inQuotes = !inQuotes;
915
+ else if (inQuotes)
916
+ continue;
917
+ else if (ch === '[' || ch === '(' || ch === '{')
918
+ depth++;
919
+ else if (ch === ']' || ch === ')' || ch === '}')
920
+ depth = Math.max(0, depth - 1);
921
+ else if (depth === 0)
922
+ outside += ch;
923
+ }
924
+ return /(^|[^-=.])->/.test(outside) ? '`->` is not a link, use `-->`' : null;
925
+ }
926
+ /**
927
+ * Read `rest` as one bracketed node shape (`[Text]`, `{Text}`, `((Text))`…) covering all of it, longest
928
+ * syntax first so `(` does not match `((`. The shape's own bracket must close exactly at the end:
929
+ * `[Receive ticket] -> B[Assign crew]` starts with `[` and ends with `]`, but it is two bracketed texts
930
+ * joined by something that is not a link (Mermaid rejects it), not one node labelled
931
+ * `Receive ticket] -> B[Assign crew`. Only the bracket pair that closes the shape is counted, so a label
932
+ * with another kind of bracket (`A[Step 1)]`, `A[f(x)]`) is read as before; a quoted label is taken whole.
933
+ */
934
+ function matchShapeSyntax(rest) {
985
935
  for (const { open, close, shape } of SHAPE_BY_SYNTAX) {
986
- // Longest patterns first to avoid `(` matching `((`.
987
- if (rest.startsWith(open) && rest.endsWith(close)) {
988
- const inner = rest.slice(open.length, rest.length - close.length).trim();
989
- const parsed = parseLabel(stripQuotedLabel(inner));
990
- return { id, label: parsed.text, labelRuns: parsed.runs, shape, className };
991
- }
936
+ if (!rest.startsWith(open) || !rest.endsWith(close))
937
+ continue;
938
+ const inner = rest.slice(open.length, rest.length - close.length).trim();
939
+ if (!closesOnlyAtEnd(inner, close[close.length - 1]))
940
+ continue;
941
+ const parsed = parseLabel(stripQuotedLabel(inner));
942
+ return { label: parsed.text, labelRuns: parsed.runs, shape };
992
943
  }
993
944
  return null;
994
945
  }
946
+ /**
947
+ * Whether an unquoted label leaves its shape's bracket open to the end: its `[`/`]` (or `(`/`)`,
948
+ * `{`/`}`, after `closing`) are balanced and never close more than they opened. Double-quoted text is
949
+ * skipped, so `A["a] x [b"]` stays one label, as in Mermaid.
950
+ */
951
+ function closesOnlyAtEnd(inner, closing) {
952
+ const opening = closing === ']' ? '[' : closing === ')' ? '(' : '{';
953
+ let depth = 0;
954
+ let inQuotes = false;
955
+ for (const ch of inner) {
956
+ if (ch === '"')
957
+ inQuotes = !inQuotes;
958
+ else if (inQuotes)
959
+ continue;
960
+ else if (ch === opening)
961
+ depth++;
962
+ else if (ch === closing && --depth < 0)
963
+ return false;
964
+ }
965
+ return depth === 0;
966
+ }
995
967
  /** Parse a node reference at an edge endpoint: bare id or id with shape. */
996
968
  function parseNodeRef(ref) {
997
969
  const trimmed = ref.trim();
@@ -1019,14 +991,8 @@ function parseNodeRef(ref) {
1019
991
  className,
1020
992
  };
1021
993
  }
1022
- for (const { open, close, shape } of SHAPE_BY_SYNTAX) {
1023
- if (rest.startsWith(open) && rest.endsWith(close)) {
1024
- const inner = rest.slice(open.length, rest.length - close.length).trim();
1025
- const parsed = parseLabel(stripQuotedLabel(inner));
1026
- return { id, label: parsed.text, labelRuns: parsed.runs, shape, className };
1027
- }
1028
- }
1029
- return null;
994
+ const bracketed = matchShapeSyntax(rest);
995
+ return bracketed ? { id, ...bracketed, className } : null;
1030
996
  }
1031
997
  /**
1032
998
  * Try to match a mid-chain-label edge (`A-- text -->B`) starting at `start`,
@@ -1044,10 +1010,10 @@ function matchMidLabelEdge(line, start) {
1044
1010
  let j = start + family.open.length;
1045
1011
  while (j < line.length) {
1046
1012
  if (depth === 0) {
1047
- const closing = family.closings.find((c) => line.startsWith(c.token, j));
1013
+ const closing = matchClosing(line, j, family);
1048
1014
  if (closing) {
1049
1015
  const parsed = parseLabel(stripQuotedLabel(line.slice(start + family.open.length, j).trim()));
1050
- return { type: closing.type, end: j + closing.token.length, label: parsed.text, labelRuns: parsed.runs };
1016
+ return { type: closing.type, end: j + closing.length, label: parsed.text, labelRuns: parsed.runs };
1051
1017
  }
1052
1018
  }
1053
1019
  const ch = line[j];