agentic-mermaid 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. package/CHANGELOG.md +149 -4
  2. package/LICENSES/Apache-2.0.txt +202 -0
  3. package/README.md +25 -32
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/assets/fonts/FONT-LICENSES.md +9 -5
  6. package/assets/fonts/Inter-Bold.ttf +0 -0
  7. package/assets/fonts/Inter-Medium.ttf +0 -0
  8. package/assets/fonts/Inter-Regular.ttf +0 -0
  9. package/assets/fonts/Inter-SemiBold.ttf +0 -0
  10. package/dist/agent-core.d.ts +463 -0
  11. package/dist/agent-core.js +397 -0
  12. package/dist/agent.d.ts +81 -1822
  13. package/dist/agent.js +336 -36839
  14. package/dist/agentic-mermaid-mcp.js +7 -37908
  15. package/dist/am.js +33638 -36261
  16. package/dist/chunk-4QECACIA.js +4702 -0
  17. package/dist/chunk-CDPKJ2BQ.js +37 -0
  18. package/dist/chunk-QKDLMOJJ.js +3487 -0
  19. package/dist/chunk-WI35L7IR.js +615 -0
  20. package/dist/chunk-WN3YDOBG.js +149 -0
  21. package/dist/chunk-ZYMMKQ3I.js +62637 -0
  22. package/dist/index-D54dqSdC.d.ts +6777 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +310 -32836
  25. package/dist/mcp-cli-SBQSTJFC.js +17 -0
  26. package/docs/README.md +14 -6
  27. package/docs/schemas/style-spec.schema.json +1221 -30
  28. package/examples/styles/catalog.json +54 -0
  29. package/examples/styles/cloudflare-workers-inspired-prototype.mmd +9 -0
  30. package/examples/styles/cloudflare-workers-inspired-prototype.style.json +110 -0
  31. package/examples/styles/cupertino-prototype.mmd +10 -0
  32. package/examples/styles/cupertino-prototype.style.json +63 -0
  33. package/examples/styles/mid-century-report.style.json +2 -2
  34. package/examples/styles/star-chart-atlas.style.json +2 -1
  35. package/examples/styles/transit-route-map.style.json +2 -2
  36. package/examples/styles/vercel-inspired-prototype.mmd +6 -0
  37. package/examples/styles/vercel-inspired-prototype.style.json +87 -0
  38. package/package.json +70 -43
  39. package/server.json +41 -0
  40. package/skills/agentic-mermaid-diagram-workflow/SKILL.md +17 -36
  41. package/skills/agentic-mermaid-diagram-workflow/references/cli.md +4 -5
  42. package/skills/agentic-mermaid-diagram-workflow/references/code-mode.md +15 -31
  43. package/skills/agentic-mermaid-diagram-workflow/references/sequence.md +10 -14
  44. package/skills/agentic-mermaid-live-editor/SKILL.md +100 -206
  45. package/AGENT_NATIVE.md +0 -602
  46. package/Instructions_for_agents.md +0 -83
  47. package/TODO.md +0 -662
  48. package/assets/hero.png +0 -0
  49. package/dist/index-x2Cj1dVv.d.ts +0 -1089
  50. package/docs/agent-api-cookbook.md +0 -308
  51. package/docs/agent-mutation-policy.md +0 -104
  52. package/docs/agent-workflow-examples.md +0 -46
  53. package/docs/api.md +0 -203
  54. package/docs/ascii.md +0 -103
  55. package/docs/assets/improvements/box-start-connector.png +0 -0
  56. package/docs/assets/improvements/comment-dropped-lint.png +0 -0
  57. package/docs/assets/improvements/er-content-loss.png +0 -0
  58. package/docs/assets/improvements/fan-in-trunks.png +0 -0
  59. package/docs/assets/improvements/gantt-family.png +0 -0
  60. package/docs/assets/improvements/gantt-milestone-clamp.png +0 -0
  61. package/docs/assets/improvements/gantt-verify-seam.png +0 -0
  62. package/docs/assets/improvements/subgraph-container-edges.png +0 -0
  63. package/docs/assets/improvements/wrapper-frontmatter.png +0 -0
  64. package/docs/assets/improvements/wrapper-init-directive.png +0 -0
  65. package/docs/assets/improvements/wrapper-leading-comment.png +0 -0
  66. package/docs/assets/style-cookbook/mid-century-report.png +0 -0
  67. package/docs/assets/style-cookbook/star-chart-atlas.png +0 -0
  68. package/docs/assets/style-cookbook/transit-route-map.png +0 -0
  69. package/docs/comparison.md +0 -94
  70. package/docs/config.md +0 -105
  71. package/docs/contributing/adding-diagram-types.md +0 -144
  72. package/docs/contributing/diagram-family-citizenship.matrix.json +0 -2127
  73. package/docs/contributing/diagram-family-citizenship.md +0 -82
  74. package/docs/contributing/harvesting-upstream-tests.md +0 -126
  75. package/docs/contributing/lessons-learned.md +0 -276
  76. package/docs/contributing/releasing.md +0 -71
  77. package/docs/contributing/visual-review-evidence.md +0 -53
  78. package/docs/custom-style-cookbook.md +0 -154
  79. package/docs/design/families/README.md +0 -26
  80. package/docs/design/families/architecture-beta.md +0 -48
  81. package/docs/design/families/flowchart-parser-conformance.md +0 -22
  82. package/docs/design/families/gantt-research.md +0 -137
  83. package/docs/design/families/gantt.md +0 -329
  84. package/docs/design/families/journey-agentic-cards-before.png +0 -0
  85. package/docs/design/families/journey-mermaid-classic-implementation.png +0 -0
  86. package/docs/design/families/journey-mermaid-classic-prototype.png +0 -0
  87. package/docs/design/families/journey-mermaid-classic-prototype.svg +0 -163
  88. package/docs/design/families/journey-mermaid-classic-prototype.svg.png +0 -0
  89. package/docs/design/families/journey-migration-parity.md +0 -433
  90. package/docs/design/families/journey-usage-research.md +0 -423
  91. package/docs/design/families/journey.md +0 -125
  92. package/docs/design/families/xychart.md +0 -85
  93. package/docs/design/system/README.md +0 -45
  94. package/docs/design/system/abstraction-audit.md +0 -224
  95. package/docs/design/system/abstraction-recommendations.md +0 -655
  96. package/docs/design/system/architecture.mmd +0 -29
  97. package/docs/design/system/architecture.svg +0 -137
  98. package/docs/design/system/layout-guarantees-and-robustness.md +0 -351
  99. package/docs/design/system/layout-rubric.md +0 -138
  100. package/docs/design/system/route-contracts.md +0 -848
  101. package/docs/design/system/source-preservation-ladder.md +0 -52
  102. package/docs/design/system/styles-rollout.md +0 -216
  103. package/docs/design/system/ugly-layouts.md +0 -119
  104. package/docs/diagram-families.md +0 -193
  105. package/docs/features.md +0 -147
  106. package/docs/fork-differences.md +0 -130
  107. package/docs/getting-started.md +0 -175
  108. package/docs/issue-derived-test-cases.md +0 -156
  109. package/docs/layout-characterization/README.md +0 -245
  110. package/docs/layout-characterization/contact-sheet-families.md +0 -496
  111. package/docs/layout-characterization/contact-sheet.md +0 -638
  112. package/docs/layout-characterization/properties.md +0 -281
  113. package/docs/layout-characterization/visual-quality.md +0 -160
  114. package/docs/layout-characterization/visual-snapshots/architecture.svg +0 -79
  115. package/docs/layout-characterization/visual-snapshots/class.svg +0 -60
  116. package/docs/layout-characterization/visual-snapshots/er.svg +0 -61
  117. package/docs/layout-characterization/visual-snapshots/flowchart.svg +0 -58
  118. package/docs/layout-characterization/visual-snapshots/gantt.svg +0 -52
  119. package/docs/layout-characterization/visual-snapshots/journey.svg +0 -118
  120. package/docs/layout-characterization/visual-snapshots/pie.svg +0 -36
  121. package/docs/layout-characterization/visual-snapshots/quadrant.svg +0 -47
  122. package/docs/layout-characterization/visual-snapshots/sequence.svg +0 -59
  123. package/docs/layout-characterization/visual-snapshots/state.svg +0 -52
  124. package/docs/layout-characterization/visual-snapshots/timeline.svg +0 -64
  125. package/docs/layout-characterization/visual-snapshots/xychart.svg +0 -97
  126. package/docs/mcp-code-mode-rationale.md +0 -101
  127. package/docs/mcp-http-transport.md +0 -223
  128. package/docs/mermaid-layout-complaints.md +0 -837
  129. package/docs/mutation-testing.md +0 -206
  130. package/docs/project/divergences.md +0 -98
  131. package/docs/project/dogfooding-docs-strategy.md +0 -66
  132. package/docs/project/hosted-mcp-cloudflare-plan.md +0 -338
  133. package/docs/project/lessons-learned.md +0 -1019
  134. package/docs/project/remove-role-styling-plan.md +0 -176
  135. package/docs/quality.md +0 -212
  136. package/docs/react.md +0 -97
  137. package/docs/style-authoring.md +0 -133
  138. package/docs/testing-strategy.md +0 -335
  139. package/docs/theming.md +0 -162
  140. package/examples/agent-improve-auth-flow.ts +0 -206
  141. package/examples/agent-loop.ts +0 -53
  142. package/examples/mcp-vs-cli-complex-diagrams.ts +0 -133
  143. package/llms.txt +0 -104
  144. package/skill-evals/README.md +0 -77
  145. package/skill-evals/fixtures/architecture-cache/input.mmd +0 -5
  146. package/skill-evals/fixtures/class-payment/input.mmd +0 -4
  147. package/skill-evals/fixtures/er-orders/input.mmd +0 -10
  148. package/skill-evals/fixtures/flowchart-cache/input.mmd +0 -3
  149. package/skill-evals/fixtures/gantt-release/input.mmd +0 -7
  150. package/skill-evals/fixtures/journey-checkout/input.mmd +0 -6
  151. package/skill-evals/fixtures/pie-exports/input.mmd +0 -5
  152. package/skill-evals/fixtures/quadrant-priorities/input.mmd +0 -11
  153. package/skill-evals/fixtures/sequence-retry/input.mmd +0 -8
  154. package/skill-evals/fixtures/state-lifecycle/input.mmd +0 -5
  155. package/skill-evals/fixtures/timeline-release/input.mmd +0 -6
  156. package/skill-evals/fixtures/xychart-growth/input.mmd +0 -5
  157. package/skill-evals/shared-benchmark.json +0 -510
  158. package/src/agent/analyze.ts +0 -157
  159. package/src/agent/apply.ts +0 -146
  160. package/src/agent/architecture-body.ts +0 -458
  161. package/src/agent/certificates.ts +0 -110
  162. package/src/agent/class-body.ts +0 -319
  163. package/src/agent/core.ts +0 -207
  164. package/src/agent/create.ts +0 -106
  165. package/src/agent/describe.ts +0 -364
  166. package/src/agent/er-body.ts +0 -224
  167. package/src/agent/facts.ts +0 -337
  168. package/src/agent/families-builtin.ts +0 -934
  169. package/src/agent/families.ts +0 -232
  170. package/src/agent/family-layouts.ts +0 -826
  171. package/src/agent/flowchart-body.ts +0 -372
  172. package/src/agent/flowchart-unsupported.ts +0 -243
  173. package/src/agent/gantt-body.ts +0 -495
  174. package/src/agent/index.ts +0 -10
  175. package/src/agent/journey-body.ts +0 -414
  176. package/src/agent/label-metrics.ts +0 -28
  177. package/src/agent/layout-to-rendered.ts +0 -63
  178. package/src/agent/mutate.ts +0 -97
  179. package/src/agent/mutation-ops.ts +0 -51
  180. package/src/agent/op-schema.ts +0 -439
  181. package/src/agent/parse.ts +0 -223
  182. package/src/agent/pie-body.ts +0 -270
  183. package/src/agent/png.ts +0 -117
  184. package/src/agent/quadrant-body.ts +0 -336
  185. package/src/agent/quality.ts +0 -363
  186. package/src/agent/readability-audit.ts +0 -92
  187. package/src/agent/rendered-route-audit.ts +0 -61
  188. package/src/agent/sequence-body.ts +0 -345
  189. package/src/agent/serialize.ts +0 -214
  190. package/src/agent/state-body.ts +0 -589
  191. package/src/agent/structural-count.ts +0 -150
  192. package/src/agent/timeline-body.ts +0 -280
  193. package/src/agent/trace-log.ts +0 -43
  194. package/src/agent/types.ts +0 -979
  195. package/src/agent/verify.ts +0 -571
  196. package/src/agent/xychart-body.ts +0 -472
  197. package/src/architecture/config.ts +0 -282
  198. package/src/architecture/layout.ts +0 -496
  199. package/src/architecture/parser.ts +0 -375
  200. package/src/architecture/renderer.ts +0 -611
  201. package/src/architecture/types.ts +0 -113
  202. package/src/ascii/ansi.ts +0 -423
  203. package/src/ascii/architecture.ts +0 -210
  204. package/src/ascii/canvas.ts +0 -443
  205. package/src/ascii/class-diagram.ts +0 -697
  206. package/src/ascii/converter.ts +0 -475
  207. package/src/ascii/draw.ts +0 -1693
  208. package/src/ascii/edge-bundling.ts +0 -328
  209. package/src/ascii/edge-routing.ts +0 -330
  210. package/src/ascii/er-diagram.ts +0 -439
  211. package/src/ascii/gantt.ts +0 -276
  212. package/src/ascii/grid.ts +0 -747
  213. package/src/ascii/index.ts +0 -196
  214. package/src/ascii/journey.ts +0 -189
  215. package/src/ascii/meta.ts +0 -244
  216. package/src/ascii/multiline-utils.ts +0 -80
  217. package/src/ascii/pathfinder.ts +0 -301
  218. package/src/ascii/pie.ts +0 -67
  219. package/src/ascii/quadrant.ts +0 -158
  220. package/src/ascii/reverse.ts +0 -216
  221. package/src/ascii/sequence.ts +0 -499
  222. package/src/ascii/shapes/circle.ts +0 -27
  223. package/src/ascii/shapes/corners.ts +0 -143
  224. package/src/ascii/shapes/diamond.ts +0 -27
  225. package/src/ascii/shapes/hexagon.ts +0 -27
  226. package/src/ascii/shapes/index.ts +0 -106
  227. package/src/ascii/shapes/rectangle.ts +0 -168
  228. package/src/ascii/shapes/rounded.ts +0 -27
  229. package/src/ascii/shapes/special.ts +0 -332
  230. package/src/ascii/shapes/stadium.ts +0 -110
  231. package/src/ascii/shapes/state.ts +0 -192
  232. package/src/ascii/shapes/types.ts +0 -73
  233. package/src/ascii/timeline.ts +0 -128
  234. package/src/ascii/types.ts +0 -312
  235. package/src/ascii/validate.ts +0 -120
  236. package/src/ascii/width.ts +0 -81
  237. package/src/ascii/xychart.ts +0 -919
  238. package/src/browser.ts +0 -29
  239. package/src/class/layout.ts +0 -240
  240. package/src/class/parser.ts +0 -332
  241. package/src/class/renderer.ts +0 -638
  242. package/src/class/types.ts +0 -129
  243. package/src/cli/agent-instructions.ts +0 -1
  244. package/src/cli/am-bin.ts +0 -6
  245. package/src/cli/exit-codes.ts +0 -18
  246. package/src/cli/index.ts +0 -1117
  247. package/src/cli/init-agent.ts +0 -147
  248. package/src/color-resolver.ts +0 -152
  249. package/src/elk-instance.ts +0 -114
  250. package/src/er/layout.ts +0 -187
  251. package/src/er/parser.ts +0 -226
  252. package/src/er/renderer.ts +0 -792
  253. package/src/er/types.ts +0 -99
  254. package/src/font-manifest.ts +0 -27
  255. package/src/gantt/layout.ts +0 -365
  256. package/src/gantt/parser.ts +0 -282
  257. package/src/gantt/pipeline.ts +0 -27
  258. package/src/gantt/renderer.ts +0 -414
  259. package/src/gantt/schedule.ts +0 -513
  260. package/src/gantt/types.ts +0 -255
  261. package/src/index.ts +0 -368
  262. package/src/journey/layout.ts +0 -520
  263. package/src/journey/parser.ts +0 -218
  264. package/src/journey/renderer.ts +0 -811
  265. package/src/journey/types.ts +0 -144
  266. package/src/layout/geometry.ts +0 -182
  267. package/src/layout/pass.ts +0 -142
  268. package/src/layout/passes/index.ts +0 -3916
  269. package/src/layout-engine.ts +0 -1565
  270. package/src/layout-rubric.ts +0 -659
  271. package/src/mcp/artifacts.ts +0 -137
  272. package/src/mcp/dynamic-harness.ts +0 -31
  273. package/src/mcp/dynamic-modules.d.ts +0 -7
  274. package/src/mcp/facade.ts +0 -608
  275. package/src/mcp/harness-runtime.ts +0 -203
  276. package/src/mcp/hosted-server.ts +0 -468
  277. package/src/mcp/mcp-bin.ts +0 -3
  278. package/src/mcp/mcp-cli.ts +0 -82
  279. package/src/mcp/protocol.ts +0 -13
  280. package/src/mcp/sandbox.ts +0 -195
  281. package/src/mcp/sdk-decl.ts +0 -387
  282. package/src/mcp/server.ts +0 -362
  283. package/src/mcp/tool-surface.ts +0 -146
  284. package/src/mermaid-source.ts +0 -655
  285. package/src/multiline-utils.ts +0 -228
  286. package/src/parser.ts +0 -1031
  287. package/src/pie/layout.ts +0 -168
  288. package/src/pie/parser.ts +0 -136
  289. package/src/pie/renderer.ts +0 -234
  290. package/src/pie/types.ts +0 -82
  291. package/src/quadrant/layout.ts +0 -191
  292. package/src/quadrant/parser.ts +0 -183
  293. package/src/quadrant/renderer.ts +0 -322
  294. package/src/quadrant/types.ts +0 -113
  295. package/src/render-family-hooks.ts +0 -244
  296. package/src/renderer.ts +0 -1099
  297. package/src/route-contracts.ts +0 -2723
  298. package/src/scene/backend.ts +0 -76
  299. package/src/scene/fidelity.ts +0 -183
  300. package/src/scene/hybrid-backend.ts +0 -174
  301. package/src/scene/ir.ts +0 -181
  302. package/src/scene/marks.ts +0 -127
  303. package/src/scene/rough-backend.ts +0 -378
  304. package/src/scene/seed.ts +0 -46
  305. package/src/scene/style-registry.ts +0 -556
  306. package/src/sequence/layout.ts +0 -456
  307. package/src/sequence/parser.ts +0 -255
  308. package/src/sequence/renderer.ts +0 -604
  309. package/src/sequence/types.ts +0 -154
  310. package/src/shape-clipping.ts +0 -351
  311. package/src/shared/accessibility-directives.ts +0 -22
  312. package/src/shared/batched.ts +0 -61
  313. package/src/shared/color-math.ts +0 -72
  314. package/src/shared/svg-a11y.ts +0 -29
  315. package/src/shared/syntax-error.ts +0 -17
  316. package/src/shared/unicode-ranges.ts +0 -135
  317. package/src/styles.ts +0 -318
  318. package/src/svg-paths.ts +0 -28
  319. package/src/text-metrics.ts +0 -248
  320. package/src/theme.ts +0 -639
  321. package/src/timeline/layout.ts +0 -381
  322. package/src/timeline/parser.ts +0 -215
  323. package/src/timeline/renderer.ts +0 -538
  324. package/src/timeline/types.ts +0 -105
  325. package/src/types.ts +0 -454
  326. package/src/website-worker-modules.d.ts +0 -18
  327. package/src/xychart/axis-utils.ts +0 -109
  328. package/src/xychart/colors.ts +0 -124
  329. package/src/xychart/config.ts +0 -88
  330. package/src/xychart/layout.ts +0 -656
  331. package/src/xychart/parser.ts +0 -504
  332. package/src/xychart/renderer.ts +0 -640
  333. package/src/xychart/types.ts +0 -282
@@ -1,934 +0,0 @@
1
- // ============================================================================
2
- // Built-in family registrations.
3
- //
4
- // Registers all built-in families with the plugin registry. Structured families own
5
- // their parse/serialize/mutate here (BUILD-3 consolidation): parseMermaid,
6
- // serializeMermaid, and mutate dispatch through these hooks, so adding a
7
- // family means one registration plus a body module — no core edits.
8
- //
9
- // Flowchart registers through `flowchartFamilyHooks('flowchart')` over the
10
- // legacy MermaidGraph body (error semantics, contributes a SourceMap).
11
- //
12
- // State registers through `structuredFamilyHooks('state', …)` over the
13
- // dedicated StateBody IR (BUILD-19): structured-or-opaque parse, state-shaped
14
- // ops, an `asState` narrower, and a verify hook that runs body-level Tier 1
15
- // checks (verify.ts adds the geometric Tier 2 pass via the graph projection).
16
- // ============================================================================
17
-
18
- import { registerFamily, extractLabelsGeneric, type ExtractedLabel, type FamilyPlugin } from './families.ts'
19
- import type { DiagramBody, DiagramKind, AnyMutationOp, MutationError, Result, LayoutWarning, SourceMap, ClassBody, ErBody, XyChartBody, PieBody, QuadrantBody, GanttBody } from './types.ts'
20
- import { ok, err } from './types.ts'
21
- import { verifyClass, parseClassBody, renderClass, mutateClass } from './class-body.ts'
22
- import { verifyErBody, parseErBody, renderEr, mutateEr } from './er-body.ts'
23
- import { parseSequenceBody, renderSequence, mutateSequence } from './sequence-body.ts'
24
- import { parseTimelineBody, renderTimeline, mutateTimeline } from './timeline-body.ts'
25
- import { parseJourneyBody, renderJourney, mutateJourney, verifyJourney } from './journey-body.ts'
26
- import { parseArchitectureBody, renderArchitecture, mutateArchitecture, verifyArchitecture } from './architecture-body.ts'
27
- import { parseXyChartBody, renderXyChart, mutateXyChart, verifyXyChart } from './xychart-body.ts'
28
- import { parsePieBody, renderPie, mutatePie, verifyPie } from './pie-body.ts'
29
- import { parseQuadrantBody, renderQuadrant, mutateQuadrant, verifyQuadrant } from './quadrant-body.ts'
30
- import { parseStateBody, renderState, mutateState, verifyState } from './state-body.ts'
31
- import { parseGanttBody, renderGantt, mutateGantt, verifyGantt } from './gantt-body.ts'
32
- import { parseFlowchartBody, renderFlowchart, mutateFlowchart, buildFlowchartSourceMap, type FlowchartBody } from './flowchart-body.ts'
33
- import { containsFlowchartOpaqueSyntax } from './flowchart-unsupported.ts'
34
-
35
- // Build the structured-or-opaque hook set shared by every structured family
36
- // that is not flowchart/state. `headerOk` gates structured parsing: families
37
- // with meaningful header suffixes (timeline, journey) stay opaque when the
38
- // header carries one, so the suffix round-trips verbatim.
39
- function structuredFamilyHooks<K extends DiagramBody['kind'] & DiagramKind>(
40
- kind: K,
41
- opts: {
42
- headerOk?: (header: string) => boolean
43
- parseBody: (lines: string[]) => Extract<DiagramBody, { kind: K }> | null
44
- serialize: (body: Extract<DiagramBody, { kind: K }>) => string
45
- mutate: (body: Extract<DiagramBody, { kind: K }>, op: never) => Result<Extract<DiagramBody, { kind: K }>, MutationError>
46
- },
47
- ): Pick<FamilyPlugin, 'parse' | 'serialize' | 'mutate'> {
48
- return {
49
- parse: (lines, opaqueSource) => {
50
- const headerOk = opts.headerOk?.(lines[0]?.trim() ?? '') ?? true
51
- const body = headerOk ? opts.parseBody(lines.slice(1)) : null
52
- return ok(body ?? { kind: 'opaque', family: kind, source: opaqueSource })
53
- },
54
- serialize: body => {
55
- if (body.kind !== kind) throw new Error(`${kind} serializer received body kind ${body.kind}`)
56
- return opts.serialize(body as Extract<DiagramBody, { kind: K }>)
57
- },
58
- mutate: (body: DiagramBody, op: AnyMutationOp) => {
59
- if (body.kind !== kind) return err<MutationError>({ code: 'INVALID_OP', message: `${kind} mutator received body kind ${body.kind}` })
60
- return opts.mutate(body as Extract<DiagramBody, { kind: K }>, op as never)
61
- },
62
- }
63
- }
64
-
65
- // ---- Flowchart ------------------------------------------------------------
66
- // Flowchart-specific label extraction:
67
- // - `A["text"]`, `A(text)`, `A([text])`, `A{text}`, `A{{text}}`, etc.
68
- // - `A -- text --> B`, `A -->|text| B`
69
- const FLOWCHART_LABEL_RE = /(?:\["((?:[^"\\]|\\.)*)"\]|\[(["'`]?)([^\]\n]+?)\2\]|\(\(([^)\n]+?)\)\)|\(([^)\n]+?)\)|\{([^}\n]+?)\}|\|([^|\n]+?)\||\>([^\]\n]+?)\])/g
70
-
71
- function extractFlowchartLabels(source: string): ExtractedLabel[] {
72
- const out: ExtractedLabel[] = []
73
- const lines = source.split(/\r?\n/)
74
- for (let i = 0; i < lines.length; i++) {
75
- const raw = lines[i]!.trim()
76
- if (!raw || raw.startsWith('%%')) continue
77
- const idMatch = raw.match(/^([A-Za-z_][\w-]*)/)
78
- const target = idMatch ? idMatch[1]! : `line${i + 1}`
79
- for (const m of raw.matchAll(FLOWCHART_LABEL_RE)) {
80
- const text = (m[1] ?? m[3] ?? m[4] ?? m[5] ?? m[6] ?? m[7] ?? m[8] ?? '').trim()
81
- if (text) out.push({ text, target })
82
- }
83
- }
84
- return out
85
- }
86
-
87
- // Flowchart owns the legacy MermaidGraph body: the diagram kind selects the
88
- // plugin, which binds the flowchart header.
89
- function flowchartFamilyHooks(): Pick<FamilyPlugin, 'parse' | 'buildSourceMap' | 'serialize' | 'mutate'> {
90
- return {
91
- parse: (_lines, opaqueSource, _meta, canonicalSource) => {
92
- if (containsFlowchartOpaqueSyntax(canonicalSource)) return ok<DiagramBody>({ kind: 'opaque', family: 'flowchart', source: opaqueSource })
93
- return parseFlowchartBody(canonicalSource)
94
- },
95
- buildSourceMap: (body, canonicalSource) =>
96
- body.kind === 'flowchart' ? buildFlowchartSourceMap(body as FlowchartBody, canonicalSource) : { nodes: new Map(), edges: new Map(), groups: new Map(), labels: new Map() },
97
- serialize: body => {
98
- if (body.kind !== 'flowchart') throw new Error(`flowchart serializer received body kind ${body.kind}`)
99
- return renderFlowchart(body.graph, 'flowchart')
100
- },
101
- mutate: (body, op) => {
102
- if (body.kind !== 'flowchart') return err<MutationError>({ code: 'INVALID_OP', message: `flowchart mutator received body kind ${body.kind}` })
103
- return mutateFlowchart(body, op as never)
104
- },
105
- }
106
- }
107
-
108
- registerFamily({
109
- id: 'flowchart',
110
- detect: l => l.startsWith('flowchart') || l.startsWith('graph'),
111
- extractLabels: extractFlowchartLabels,
112
- ...flowchartFamilyHooks(),
113
- })
114
-
115
- // ---- State ----------------------------------------------------------------
116
- // BUILD-19: state owns a dedicated StateBody IR (no longer the flowchart body).
117
- // State label extraction for opaque fallbacks: `state "Label" as id`,
118
- // `id : Description`, and transition labels `from --> to : label`.
119
- function extractStateLabels(source: string): ExtractedLabel[] {
120
- const out: ExtractedLabel[] = []
121
- const lines = source.split(/\r?\n/)
122
- for (let i = 0; i < lines.length; i++) {
123
- const raw = lines[i]!.trim()
124
- if (!raw || raw.startsWith('%%')) continue
125
- const target = `line${i + 1}`
126
- let m
127
- if ((m = raw.match(/^state\s+"([^"]+)"\s+as\s+/i))) {
128
- out.push({ text: m[1]!.trim(), target })
129
- } else if (raw.includes('-->') && raw.includes(':')) {
130
- const colon = raw.indexOf(':')
131
- out.push({ text: raw.slice(colon + 1).trim(), target })
132
- } else if ((m = raw.match(/^[\w\p{L}-]+\s*:\s*(.+)$/u))) {
133
- out.push({ text: m[1]!.trim(), target })
134
- } else if ((m = raw.match(/^note\s+(?:left of|right of)\s+\S+\s*:\s*(.+)$/i))) {
135
- out.push({ text: m[1]!.trim(), target })
136
- }
137
- }
138
- return out
139
- }
140
-
141
- registerFamily({
142
- id: 'state',
143
- detect: l => l.startsWith('statediagram') || l.startsWith('statediagram-v2'),
144
- extractLabels: extractStateLabels,
145
- // The verify hook covers body-level structural Tier 1 (EMPTY/MISANCHORED/
146
- // LABEL_OVERFLOW); verify.ts adds geometric Tier 2 via the graph projection.
147
- verify: (body, opts) => body.kind === 'state' ? verifyState(body, opts) : [],
148
- ...structuredFamilyHooks('state', {
149
- headerOk: h => /^statediagram(?:-v2)?\s*$/i.test(h),
150
- parseBody: parseStateBody, serialize: renderState, mutate: mutateState,
151
- }),
152
- })
153
-
154
- // ---- Sequence -------------------------------------------------------------
155
- // Sequence labels: messages (`A->>B: text`), participants (`participant X as Label`,
156
- // `actor X as Label`), notes (`Note over A: text`, `Note left of A: text`),
157
- // block headers (`loop label`, `alt label`, `else label`, `opt label`, `par label`).
158
- function extractSequenceLabels(source: string): ExtractedLabel[] {
159
- const out: ExtractedLabel[] = []
160
- const lines = source.split(/\r?\n/)
161
- for (let i = 0; i < lines.length; i++) {
162
- const raw = lines[i]!.trim()
163
- if (!raw || raw.startsWith('%%')) continue
164
- let m
165
- if ((m = raw.match(/^(?:participant|actor)\s+\S+\s+as\s+(.+)$/i))) {
166
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
167
- } else if ((m = raw.match(/^Note\s+(?:over|left of|right of)\s+[\w,\s]+?:\s*(.+)$/i))) {
168
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
169
- } else if ((m = raw.match(/->>?|-->>?|->|-->|-x|--x/)) && raw.includes(':')) {
170
- const colon = raw.indexOf(':')
171
- out.push({ text: raw.slice(colon + 1).trim(), target: `line${i + 1}` })
172
- } else if ((m = raw.match(/^(?:loop|alt|else|opt|par|and|critical|break|rect)\s+(.+)$/i))) {
173
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
174
- } else if ((m = raw.match(/^title\s+(.+)$/i))) {
175
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
176
- }
177
- }
178
- return out
179
- }
180
-
181
- // Sequence parse needs the RAW (indentation-preserving) body lines so
182
- // opaque-block segments round-trip verbatim. `opaqueSource` is the normalized
183
- // body INCLUDING the header line, with original indentation/blank lines/
184
- // comments intact — drop its header and pass alongside the trimmed lines.
185
- registerFamily({
186
- id: 'sequence',
187
- detect: l => l.startsWith('sequencediagram'),
188
- extractLabels: extractSequenceLabels,
189
- parse: (lines, opaqueSource) => {
190
- const expandedLines = expandInlineSequenceStatements(lines)
191
- const rawBodyLines = sequenceRawBodyLines(opaqueSource, expandedLines)
192
- const body = parseSequenceBody(expandedLines.slice(1), rawBodyLines)
193
- return ok(body ?? { kind: 'opaque', family: 'sequence', source: opaqueSource })
194
- },
195
- serialize: body => {
196
- if (body.kind !== 'sequence') throw new Error(`sequence serializer received body kind ${body.kind}`)
197
- return renderSequence(body)
198
- },
199
- mutate: (body, op) => {
200
- if (body.kind !== 'sequence') return err<MutationError>({ code: 'INVALID_OP', message: `sequence mutator received body kind ${body.kind}` })
201
- return mutateSequence(body, op as never)
202
- },
203
- })
204
-
205
- function expandInlineSequenceStatements(lines: string[]): string[] {
206
- const header = lines[0]?.trim() ?? ''
207
- if (!/^sequenceDiagram\s*;/i.test(header)) return lines
208
- return [...header.split(';').map(part => part.trim()).filter(Boolean), ...lines.slice(1)]
209
- }
210
-
211
- function sequenceRawBodyLines(opaqueSource: string, expandedLines: string[]): string[] {
212
- const raw = opaqueSource.split(/\r?\n/)
213
- const headerAt = raw.findIndex(l => /^sequenceDiagram\b/i.test(l.trim()))
214
- if (headerAt >= 0 && raw[headerAt]!.includes(';')) return expandedLines.slice(1)
215
- return headerAt >= 0 ? raw.slice(headerAt + 1) : raw.slice(1)
216
- }
217
-
218
- // ---- Timeline -------------------------------------------------------------
219
- function extractTimelineLabels(source: string): ExtractedLabel[] {
220
- const out: ExtractedLabel[] = []
221
- const lines = source.split(/\r?\n/)
222
- for (let i = 0; i < lines.length; i++) {
223
- const raw = lines[i]!.trim()
224
- if (!raw || raw.startsWith('%%')) continue
225
- let m
226
- if ((m = raw.match(/^title\s+(.+)$/i))) {
227
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
228
- } else if ((m = raw.match(/^section\s+(.+)$/i))) {
229
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
230
- } else if (raw.includes(':')) {
231
- // `<period> : <event> [: <event>...]` or continuation `: <event>`
232
- const parts = raw.split(':').map(p => p.trim()).filter(Boolean)
233
- for (const p of parts) out.push({ text: p, target: `line${i + 1}` })
234
- }
235
- }
236
- return out
237
- }
238
-
239
- registerFamily({
240
- id: 'timeline',
241
- detect: l => l.startsWith('timeline'),
242
- extractLabels: extractTimelineLabels,
243
- ...structuredFamilyHooks('timeline', {
244
- headerOk: h => /^timeline\s*$/i.test(h),
245
- parseBody: parseTimelineBody, serialize: renderTimeline, mutate: mutateTimeline,
246
- }),
247
- })
248
-
249
- // ---- Class ---------------------------------------------------------------
250
- // class Name { +member ... }, Class : +member, class A as "Display Label"
251
- function emptySourceMap(): SourceMap { return { nodes: new Map(), edges: new Map(), groups: new Map(), labels: new Map() } }
252
- function loc(line: number, col: number): { line: number; col: number } { return { line, col: Math.max(1, col) } }
253
- function firstIndex(line: string, text: string): number { const i = line.indexOf(text); return i >= 0 ? i + 1 : 1 }
254
-
255
- function buildClassSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
256
- const map = emptySourceMap()
257
- if (body.kind !== 'class') return map
258
- const b = body as ClassBody
259
- const lines = canonicalSource.split(/\r?\n/)
260
- for (const c of b.classes) {
261
- for (let i = 0; i < lines.length; i++) {
262
- const line = lines[i]!
263
- if (new RegExp(`\\b${escapeSourceMapRegex(c.id)}\\b`).test(line)) { map.nodes.set(c.id, loc(i + 1, firstIndex(line, c.id))); break }
264
- }
265
- c.members.forEach((member, index) => {
266
- for (let i = 0; i < lines.length; i++) {
267
- const col = lines[i]!.indexOf(member)
268
- if (col >= 0) { map.labels.set(`class:${c.id}:member#${index}`, loc(i + 1, col + 1)); break }
269
- }
270
- })
271
- }
272
- b.relations.forEach((r, index) => {
273
- for (let i = 0; i < lines.length; i++) {
274
- const line = lines[i]!
275
- if (!line.includes(r.from) || !line.includes(r.to)) continue
276
- const key = `rel#${index}:${r.from}->${r.to}`
277
- map.edges.set(key, loc(i + 1, firstIndex(line, r.from)))
278
- if (r.label) {
279
- const labelCol = line.lastIndexOf(r.label)
280
- if (labelCol >= 0) map.labels.set(key, loc(i + 1, labelCol + 1))
281
- }
282
- if (r.fromCardinality) {
283
- const col = line.indexOf(`"${r.fromCardinality}"`)
284
- if (col >= 0) map.labels.set(`${key}:fromCardinality`, loc(i + 1, col + 2))
285
- }
286
- if (r.toCardinality) {
287
- const col = line.indexOf(`"${r.toCardinality}"`)
288
- if (col >= 0) map.labels.set(`${key}:toCardinality`, loc(i + 1, col + 2))
289
- }
290
- break
291
- }
292
- })
293
- return map
294
- }
295
-
296
- function buildErSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
297
- const map = emptySourceMap()
298
- if (body.kind !== 'er') return map
299
- const b = body as ErBody
300
- const lines = canonicalSource.split(/\r?\n/)
301
- for (const e of b.entities) {
302
- for (let i = 0; i < lines.length; i++) {
303
- const line = lines[i]!
304
- if (new RegExp(`\\b${escapeSourceMapRegex(e.id)}\\b`).test(line)) { map.nodes.set(e.id, loc(i + 1, firstIndex(line, e.id))); break }
305
- }
306
- e.attributes.forEach((attr, index) => {
307
- for (let i = 0; i < lines.length; i++) {
308
- const col = lines[i]!.indexOf(attr.text)
309
- if (col >= 0) { map.labels.set(`er:${e.id}:attr#${index}`, loc(i + 1, col + 1)); break }
310
- }
311
- })
312
- }
313
- b.relations.forEach((r, index) => {
314
- for (let i = 0; i < lines.length; i++) {
315
- const line = lines[i]!
316
- if (!line.includes(r.from) || !line.includes(r.to)) continue
317
- const key = `rel#${index}:${r.from}->${r.to}`
318
- map.edges.set(key, loc(i + 1, firstIndex(line, r.from)))
319
- if (r.label) {
320
- const labelCol = line.lastIndexOf(r.label)
321
- if (labelCol >= 0) map.labels.set(key, loc(i + 1, labelCol + 1))
322
- }
323
- const between = line.slice(line.indexOf(r.from) + r.from.length, line.indexOf(r.to))
324
- const relStart = line.indexOf(between)
325
- const cardMatches = [...between.matchAll(/[|o}{]{2}/g)]
326
- if (cardMatches[0]) map.labels.set(`${key}:leftCardinality`, loc(i + 1, relStart + cardMatches[0].index! + 1))
327
- if (cardMatches[1]) map.labels.set(`${key}:rightCardinality`, loc(i + 1, relStart + cardMatches[1].index! + 1))
328
- break
329
- }
330
- })
331
- return map
332
- }
333
-
334
- function buildChartSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
335
- const map = emptySourceMap()
336
- const lines = canonicalSource.split(/\r?\n/)
337
- if (body.kind === 'xychart') {
338
- const b = body as XyChartBody
339
- b.series.forEach((series, si) => {
340
- const lineIndex = lines.findIndex(line => line.trim().startsWith(series.kind))
341
- if (lineIndex < 0) return
342
- const line = lines[lineIndex]!
343
- if (series.name) map.labels.set(`xychart:${series.id}:name`, loc(lineIndex + 1, firstIndex(line, series.name)))
344
- series.values.forEach((value, vi) => {
345
- const valueText = String(value)
346
- const col = line.indexOf(valueText)
347
- if (col >= 0) map.labels.set(`xychart:${series.id}:point#${vi}`, loc(lineIndex + 1, col + 1))
348
- })
349
- })
350
- } else if (body.kind === 'pie') {
351
- ;(body as PieBody).slices.forEach((slice, index) => {
352
- const lineIndex = lines.findIndex(line => line.includes(slice.label))
353
- if (lineIndex >= 0) map.labels.set(`pie:slice#${index}`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, slice.label)))
354
- })
355
- } else if (body.kind === 'quadrant') {
356
- ;(body as QuadrantBody).points.forEach((point, index) => {
357
- const lineIndex = lines.findIndex(line => line.includes(point.label))
358
- if (lineIndex >= 0) map.labels.set(`quadrant:point#${index}`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, point.label)))
359
- })
360
- }
361
- return map
362
- }
363
-
364
- function buildGanttSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
365
- const map = emptySourceMap()
366
- if (body.kind !== 'gantt') return map
367
- const b = body as GanttBody
368
- const lines = canonicalSource.split(/\r?\n/)
369
- for (const section of b.sections) {
370
- if (section.label) {
371
- const lineIndex = lines.findIndex(line => /^\s*section\s+/i.test(line) && line.includes(section.label!))
372
- if (lineIndex >= 0) { map.groups.set(section.id, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, section.label))); map.labels.set(`gantt:${section.id}:label`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, section.label))) }
373
- }
374
- for (const task of section.tasks) {
375
- const stableId = task.taskId ?? task.id
376
- const lineIndex = lines.findIndex(line => line.includes(task.label) && line.includes(task.end))
377
- if (lineIndex < 0) continue
378
- const line = lines[lineIndex]!
379
- map.nodes.set(stableId, loc(lineIndex + 1, firstIndex(line, task.label)))
380
- map.labels.set(`gantt:task:${stableId}`, loc(lineIndex + 1, firstIndex(line, task.label)))
381
- }
382
- }
383
- return map
384
- }
385
-
386
- function escapeSourceMapRegex(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }
387
-
388
- function extractClassLabels(source: string): ExtractedLabel[] {
389
- const out: ExtractedLabel[] = []
390
- const lines = source.split(/\r?\n/)
391
- for (let i = 0; i < lines.length; i++) {
392
- const raw = lines[i]!.trim()
393
- if (!raw || raw.startsWith('%%')) continue
394
- let m
395
- if ((m = raw.match(/^class\s+\S+\s+as\s+"([^"]+)"/i))) {
396
- out.push({ text: m[1]!, target: `line${i + 1}` })
397
- } else if ((m = raw.match(/^\S+\s*:\s*(.+)$/))) {
398
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
399
- } else if ((m = raw.match(/^[+\-#~]\s*(.+)$/))) {
400
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
401
- } else if ((m = raw.match(/^note\s+(?:for\s+\S+\s+)?"([^"]+)"/i))) {
402
- out.push({ text: m[1]!, target: `line${i + 1}` })
403
- }
404
- }
405
- return out
406
- }
407
-
408
- registerFamily({
409
- id: 'class',
410
- detect: l => l.startsWith('classdiagram'),
411
- extractLabels: extractClassLabels,
412
- // Loop 8 A1: the structured class verifier IS the verify path — verifyMermaid
413
- // routes class diagrams through this plugin hook (Loop 9 M2 removed the
414
- // duplicate per-body branch). Single source of truth.
415
- verify: (body, opts) => body.kind === 'class' ? verifyClass(body, opts) : [],
416
- buildSourceMap: buildClassSourceMap,
417
- ...structuredFamilyHooks('class', { parseBody: parseClassBody, serialize: renderClass, mutate: mutateClass }),
418
- })
419
-
420
- // ---- ER -------------------------------------------------------------------
421
- // CUSTOMER ||--o{ ORDER : places, attributes inside braces.
422
- function extractErLabels(source: string): ExtractedLabel[] {
423
- const out: ExtractedLabel[] = []
424
- const lines = source.split(/\r?\n/)
425
- for (let i = 0; i < lines.length; i++) {
426
- const raw = lines[i]!.trim()
427
- if (!raw || raw.startsWith('%%')) continue
428
- let m
429
- if ((m = raw.match(/:\s*"?([^"]+?)"?$/))) {
430
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
431
- }
432
- // Attribute lines inside `{ ... }` blocks
433
- if (raw.match(/^\s*\w+\s+\w+/) && !raw.match(/[<>|}]/)) {
434
- out.push({ text: raw, target: `line${i + 1}` })
435
- }
436
- }
437
- return out
438
- }
439
-
440
- registerFamily({
441
- id: 'er',
442
- detect: l => l.startsWith('erdiagram'),
443
- extractLabels: extractErLabels,
444
- // Loop 8 A1: same as class — this hook is the verify path for ER (Loop 9 M2
445
- // removed the duplicate per-body branch in verify.ts).
446
- verify: (body, opts) => body.kind === 'er' ? verifyErBody(body, opts) : [],
447
- buildSourceMap: buildErSourceMap,
448
- ...structuredFamilyHooks('er', { parseBody: parseErBody, serialize: renderEr, mutate: mutateEr }),
449
- })
450
-
451
- // ---- Journey --------------------------------------------------------------
452
- // title T, section S, task: 3: Me
453
- function extractJourneyLabels(source: string): ExtractedLabel[] {
454
- const out: ExtractedLabel[] = []
455
- const lines = source.split(/\r?\n/)
456
- for (let i = 0; i < lines.length; i++) {
457
- const raw = lines[i]!.trim()
458
- if (!raw || raw.startsWith('%%')) continue
459
- let m
460
- if ((m = raw.match(/^accDescr\s*:?\s*\{\s*(.*)$/i))) {
461
- const first = m[1]!
462
- const end = first.indexOf('}')
463
- if (end >= 0) {
464
- const text = first.slice(0, end).trim()
465
- if (text) out.push({ text, target: `line${i + 1}` })
466
- } else {
467
- const text = first.trim()
468
- if (text) out.push({ text, target: `line${i + 1}` })
469
- for (i += 1; i < lines.length; i++) {
470
- const line = lines[i]!.trim()
471
- const close = line.indexOf('}')
472
- const text = (close >= 0 ? line.slice(0, close) : line).trim()
473
- if (text) out.push({ text, target: `line${i + 1}` })
474
- if (close >= 0) break
475
- }
476
- }
477
- } else if ((m = raw.match(/^accTitle\s*:?\s*(.+)$/i))) {
478
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
479
- } else if ((m = raw.match(/^accDescr\s*:?\s*(.+)$/i))) {
480
- out.push({ text: m[1]!.replace(/^\{/, '').replace(/\}$/, '').trim(), target: `line${i + 1}` })
481
- } else if ((m = raw.match(/^title\s+(.+)$/i))) {
482
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
483
- } else if ((m = raw.match(/^section\s+(.+)$/i))) {
484
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
485
- } else if ((m = raw.match(/^(.+?):\s*\d+(?:\s*:\s*(.*))?$/))) {
486
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
487
- for (const actor of (m[2] ?? '').split(',')) {
488
- const text = actor.trim()
489
- if (text) out.push({ text, target: `line${i + 1}` })
490
- }
491
- }
492
- }
493
- return out
494
- }
495
-
496
- function verifyOpaqueJourney(body: DiagramBody): LayoutWarning[] {
497
- if (body.kind !== 'opaque' || body.family !== 'journey') return []
498
- const warnings: LayoutWarning[] = []
499
- const lines = body.source.split(/\r?\n/)
500
- for (let i = 0; i < lines.length; i++) {
501
- const diagnostic = invalidJourneyScoreDiagnostic(lines[i]!.trim())
502
- if (!diagnostic) continue
503
- warnings.push({
504
- code: 'UNSUPPORTED_SYNTAX',
505
- line: i + 1,
506
- syntax: 'journey_invalid_score',
507
- message: `Journey task "${diagnostic.text}" uses invalid score ${diagnostic.rawScore}; Mermaid Journey scores must be integers from 1 through 5.`,
508
- })
509
- }
510
- return warnings
511
- }
512
-
513
- function invalidJourneyScoreDiagnostic(raw: string): { text: string; rawScore: string } | null {
514
- if (!raw || raw.startsWith('%%')) return null
515
- if (/^(?:journey|title|section)\b/i.test(raw)) return null
516
- if (/^acc(?:Title|Descr)\b/i.test(raw)) return null
517
-
518
- const numeric = raw.match(/^(.+?)\s*:\s*([0-9]+)\s*(?::\s*(.*))?$/)
519
- if (numeric) {
520
- const score = Number.parseInt(numeric[2]!, 10)
521
- if (Number.isInteger(score) && score >= 1 && score <= 5) return null
522
- return { text: numeric[1]!.trim(), rawScore: numeric[2]! }
523
- }
524
-
525
- const taskLike = raw.match(/^(.+?)\s*:\s*([^:]+?)(?:\s*:\s*.*)?$/)
526
- if (!taskLike) return null
527
- const text = taskLike[1]!.trim()
528
- const rawScore = taskLike[2]!.trim()
529
- if (!text || !rawScore) return null
530
- return { text, rawScore }
531
- }
532
-
533
- registerFamily({
534
- id: 'journey',
535
- detect: l => l.startsWith('journey'),
536
- extractLabels: extractJourneyLabels,
537
- // BUILD-15: journey is structured-when-narrowed. The verify hook covers the
538
- // structured body; opaque fallbacks keep the universal label-extraction path.
539
- verify: (body, opts) => body.kind === 'journey' ? verifyJourney(body, opts) : verifyOpaqueJourney(body),
540
- ...structuredFamilyHooks('journey', {
541
- headerOk: h => /^journey\s*$/i.test(h),
542
- parseBody: parseJourneyBody, serialize: renderJourney, mutate: mutateJourney,
543
- }),
544
- })
545
-
546
- // ---- XY chart -------------------------------------------------------------
547
- // title "T", x-axis [a,b,c], y-axis "label"
548
- function extractXyChartLabels(source: string): ExtractedLabel[] {
549
- const out: ExtractedLabel[] = []
550
- const lines = source.split(/\r?\n/)
551
- for (let i = 0; i < lines.length; i++) {
552
- const rawLine = lines[i]!.trim()
553
- if (!rawLine || rawLine.startsWith('%%')) continue
554
- const statements = splitXyLabelStatements(rawLine)
555
- for (const raw of statements) {
556
- const target = `line${i + 1}`
557
- let m
558
- if ((m = raw.match(/^accDescr\s*:?\s*\{\s*(.*)$/i))) {
559
- const first = m[1]!
560
- const end = first.indexOf('}')
561
- if (end >= 0) {
562
- const text = first.slice(0, end).trim()
563
- if (text) out.push({ text, target })
564
- } else {
565
- const text = first.trim()
566
- if (text) out.push({ text, target })
567
- for (i += 1; i < lines.length; i++) {
568
- const line = lines[i]!.trim()
569
- const close = line.indexOf('}')
570
- const text = (close >= 0 ? line.slice(0, close) : line).trim()
571
- if (text) out.push({ text, target: `line${i + 1}` })
572
- if (close >= 0) break
573
- }
574
- }
575
- continue
576
- }
577
- if ((m = raw.match(/^accTitle\s*:?\s*(.+)$/i))) out.push({ text: m[1]!.trim(), target })
578
- else if ((m = raw.match(/^accDescr\s*:?\s*(.+)$/i))) out.push({ text: m[1]!.trim(), target })
579
- // All quoted strings, including escaped quote/backslash pairs.
580
- for (const q of quotedLabelMatches(raw)) out.push({ text: q, target })
581
- const title = raw.match(/^title\s+(.+)$/i)
582
- if (title && !/^['"]/.test(title[1]!.trim())) out.push({ text: title[1]!.trim(), target })
583
- const axisTitleWithCategories = raw.match(/^[xy]-axis\s+(.+?)\s*\[[^\]]+\]\s*$/i)
584
- const axisTitleWithRange = raw.match(/^[xy]-axis\s+(\S+)\s+[+-]?(?:(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*-->/i)
585
- const axisTitle = axisTitleWithCategories ?? axisTitleWithRange ?? raw.match(/^[xy]-axis\s+([^\[\d.+-][^\[]*?)\s*(?:\[|[+-]?\d|$)/i)
586
- if (axisTitle && !/^['"]/.test(axisTitle[1]!.trim())) out.push({ text: axisTitle[1]!.trim(), target })
587
- const seriesLabel = raw.match(/^(?:bar|line)\s+(.+?)\s+\[[^\]]+\]\s*$/i)
588
- if (seriesLabel && !/^['"]/.test(seriesLabel[1]!.trim())) out.push({ text: seriesLabel[1]!.trim(), target })
589
- // x-axis [a, b, c] — extract individual entries
590
- const ax = raw.match(/^[xy]-axis\b.*\[([^\]]+)\]/i)
591
- if (ax) {
592
- for (const entry of ax[1]!.split(',')) {
593
- const t = entry.trim().replace(/^["']|["']$/g, '')
594
- if (t) out.push({ text: t, target })
595
- }
596
- }
597
- }
598
- }
599
- return out
600
- }
601
-
602
- function quotedLabelMatches(raw: string): string[] {
603
- const labels: string[] = []
604
- for (const quote of ['"', "'"] as const) {
605
- const pattern = quote === '"' ? /"((?:\\.|[^"\\])+)"/g : /'((?:\\.|[^'\\])*)'/g
606
- for (const m of raw.matchAll(pattern)) labels.push(m[1]!.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\'))
607
- }
608
- return labels
609
- }
610
-
611
- function splitXyLabelStatements(line: string): string[] {
612
- const statements: string[] = []
613
- let current = ''
614
- let quote: '"' | "'" | null = null
615
- for (let i = 0; i < line.length; i++) {
616
- const char = line[i]!
617
- if (quote) {
618
- current += char
619
- if (char === '\\') { current += line[++i] ?? ''; continue }
620
- if (char === quote) quote = null
621
- continue
622
- }
623
- if (char === '"' || char === "'") { quote = char; current += char; continue }
624
- if (char === ';') {
625
- const trimmed = current.trim()
626
- if (trimmed) statements.push(trimmed)
627
- current = ''
628
- continue
629
- }
630
- current += char
631
- }
632
- const trimmed = current.trim()
633
- if (trimmed) statements.push(trimmed)
634
- return statements
635
- }
636
-
637
- registerFamily({
638
- id: 'xychart',
639
- detect: l => l.startsWith('xychart'),
640
- extractLabels: extractXyChartLabels,
641
- // BUILD-16: xychart is structured-when-narrowed. The verify hook covers the
642
- // structured body; opaque fallbacks (accTitle/accDescr, quoted text,
643
- // multi-statement `;` lines, unmodeled tokens like `curve basis`) keep the
644
- // universal label-extraction path. headerOk requires `xychart`/`xychart-beta`
645
- // with at most a `horizontal`/`vertical` orientation suffix — any other
646
- // trailing token (e.g. `EXTRA`) stays opaque so it round-trips verbatim.
647
- verify: (body, opts) => body.kind === 'xychart' ? verifyXyChart(body, opts) : [],
648
- buildSourceMap: buildChartSourceMap,
649
- // xychart needs the header to model the `horizontal` orientation suffix, so it
650
- // uses a tailored parse hook (not the shared structuredFamilyHooks) — but
651
- // serialize/mutate stay identical to every other structured family.
652
- parse: (lines, opaqueSource) => {
653
- const header = lines[0]?.trim() ?? ''
654
- const hm = header.match(/^xychart(?:-beta)?(?:\s+(horizontal|vertical))?\s*$/i)
655
- const body = hm ? parseXyChartBody(lines.slice(1)) : null
656
- if (body && hm?.[1]?.toLowerCase() === 'horizontal') body.horizontal = true
657
- return ok(body ?? { kind: 'opaque', family: 'xychart', source: opaqueSource })
658
- },
659
- serialize: body => {
660
- if (body.kind !== 'xychart') throw new Error(`xychart serializer received body kind ${body.kind}`)
661
- return renderXyChart(body)
662
- },
663
- mutate: (body, op) => {
664
- if (body.kind !== 'xychart') return err<MutationError>({ code: 'INVALID_OP', message: `xychart mutator received body kind ${body.kind}` })
665
- return mutateXyChart(body, op as never)
666
- },
667
- })
668
-
669
- // ---- Pie ------------------------------------------------------------------
670
- // pie [showData] [title T], optional `title T`, `"label" : number` entries.
671
- // Pie is structured-when-narrowed: the body parses to a PieBody (title,
672
- // showData, slices) or falls back to opaque when any line is unmodeled.
673
- // Labels are the quoted slice labels plus the optional title text.
674
- function extractPieLabels(source: string): ExtractedLabel[] {
675
- const out: ExtractedLabel[] = []
676
- const lines = source.split(/\r?\n/)
677
- for (let i = 0; i < lines.length; i++) {
678
- const raw = lines[i]!.trim()
679
- if (!raw || raw.startsWith('%%')) continue
680
- const target = `line${i + 1}`
681
- // Header may carry an inline title: `pie title Pets` / `pie showData title Pets`.
682
- let m
683
- if ((m = raw.match(/^pie\b\s*(?:showData\b\s*)?title\s+(.+)$/i))) {
684
- out.push({ text: m[1]!.trim(), target })
685
- continue
686
- }
687
- if (/^pie\b/i.test(raw)) continue
688
- if ((m = raw.match(/^title\s+(.+)$/i))) {
689
- out.push({ text: m[1]!.trim(), target })
690
- continue
691
- }
692
- // Entry line: `"label" : value` — extract the quoted label.
693
- if ((m = raw.match(/^"((?:[^"\\]|\\.)*)"\s*:/))) {
694
- const text = m[1]!.replace(/\\"/g, '"').replace(/\\\\/g, '\\').trim()
695
- if (text) out.push({ text, target })
696
- }
697
- }
698
- return out
699
- }
700
-
701
- // Parse the `pie [showData] [title <text>]` header tail. Returns null when the
702
- // tail carries unmodeled tokens, so the whole body falls back to opaque.
703
- function parsePieHeader(header: string): { showData: boolean; title?: string } | null {
704
- const m = header.match(/^pie\b(.*)$/i)
705
- if (!m) return null
706
- let tail = m[1]!.trim()
707
- let showData = false
708
- const sd = tail.match(/^showData\b\s*(.*)$/i)
709
- if (sd) { showData = true; tail = sd[1]!.trim() }
710
- const inlineTitle = tail.match(/^title\s+(.+)$/i)
711
- if (inlineTitle) return { showData, title: inlineTitle[1]!.trim() }
712
- if (tail.length > 0) return null // unexpected text after the header → opaque
713
- return { showData }
714
- }
715
-
716
- registerFamily({
717
- id: 'pie',
718
- detect: l => l.startsWith('pie'),
719
- extractLabels: extractPieLabels,
720
- // Pie is structured-when-narrowed. The verify hook covers the structured
721
- // body; opaque fallbacks keep the universal label-extraction path. The header
722
- // carries showData / inline title, so pie uses a tailored parse hook (like
723
- // xychart) — serialize/mutate stay identical to every other structured family.
724
- verify: (body, opts) => body.kind === 'pie' ? verifyPie(body, opts) : [],
725
- buildSourceMap: buildChartSourceMap,
726
- parse: (lines, opaqueSource) => {
727
- const header = parsePieHeader(lines[0]?.trim() ?? '')
728
- const body = header ? parsePieBody(lines.slice(1), header) : null
729
- return ok(body ?? { kind: 'opaque', family: 'pie', source: opaqueSource })
730
- },
731
- serialize: body => {
732
- if (body.kind !== 'pie') throw new Error(`pie serializer received body kind ${body.kind}`)
733
- return renderPie(body)
734
- },
735
- mutate: (body, op) => {
736
- if (body.kind !== 'pie') return err<MutationError>({ code: 'INVALID_OP', message: `pie mutator received body kind ${body.kind}` })
737
- return mutatePie(body, op as never)
738
- },
739
- })
740
-
741
- // ---- Quadrant -------------------------------------------------------------
742
- // quadrantChart header; `title T`; `x-axis a --> b`; `y-axis a --> b`;
743
- // `quadrant-1..4 label`; `Label: [x, y]`. Quadrant is structured-when-narrowed:
744
- // the body parses to a QuadrantBody (title, axes, quadrant labels, points) or
745
- // falls back to opaque when any line is unmodeled (styling, malformed coords,
746
- // duplicate point labels). Labels are the title, both axis label sides, the
747
- // four quadrant region labels, and the point labels.
748
- function extractQuadrantLabels(source: string): ExtractedLabel[] {
749
- const out: ExtractedLabel[] = []
750
- const lines = source.split(/\r?\n/)
751
- for (let i = 0; i < lines.length; i++) {
752
- const raw = lines[i]!.trim()
753
- if (!raw || raw.startsWith('%%')) continue
754
- const target = `line${i + 1}`
755
- if (/^quadrantchart\b/i.test(raw)) continue
756
- let m
757
- if ((m = raw.match(/^title\s+(.+)$/i))) {
758
- out.push({ text: m[1]!.trim(), target })
759
- continue
760
- }
761
- // x-axis / y-axis: `<near> [--> <far>]` — extract both sides.
762
- if ((m = raw.match(/^[xy]-axis\s+(.+)$/i))) {
763
- const tail = m[1]!.trim()
764
- const arrow = tail.indexOf('-->')
765
- if (arrow >= 0) {
766
- const near = tail.slice(0, arrow).trim()
767
- const far = tail.slice(arrow + 3).trim()
768
- if (near) out.push({ text: near, target })
769
- if (far) out.push({ text: far, target })
770
- } else if (tail) {
771
- out.push({ text: tail, target })
772
- }
773
- continue
774
- }
775
- if ((m = raw.match(/^quadrant-[1-4]\s+(.+)$/i))) {
776
- out.push({ text: m[1]!.trim(), target })
777
- continue
778
- }
779
- // Point line: `Label[:::class]: [x, y] [style metadata]` — extract the
780
- // display label, not the optional class/style adornments.
781
- if ((m = raw.match(/^(.+?)\s*:\s*\[[^\]]*\]\s*(?:.*)?$/))) {
782
- const text = m[1]!.replace(/\s*:::\s*[A-Za-z_][\w-]*\s*$/, '').trim()
783
- if (text) out.push({ text, target })
784
- }
785
- }
786
- return out
787
- }
788
-
789
- function verifyOpaqueQuadrant(body: DiagramBody): LayoutWarning[] {
790
- if (body.kind !== 'opaque' || body.family !== 'quadrant') return []
791
- const warnings: LayoutWarning[] = []
792
- // Unrenderable opaque sources are the universal render-parity gate's job
793
- // (Tier-1 RENDER_FAILED in verifyMermaid) — this hook's remaining value is
794
- // the style-metadata lint, which scans raw lines and needs no parse.
795
-
796
- let sawPointStyle = false
797
- let sawClassDef = false
798
- for (const rawLine of body.source.split(/\r?\n/)) {
799
- const raw = rawLine.trim()
800
- if (!raw || raw.startsWith('%%')) continue
801
- if (/^classDef\b/i.test(raw)) sawClassDef = true
802
- const point = raw.match(/^(.+?)\s*:\s*\[[^\]]*\]\s*(.*)$/)
803
- if (point && (point[1]!.includes(':::') || point[2]!.trim().length > 0)) sawPointStyle = true
804
- }
805
- if (sawPointStyle) {
806
- warnings.push({
807
- code: 'UNSUPPORTED_SYNTAX',
808
- syntax: 'quadrant_point_style_metadata',
809
- message: 'Quadrant point style/class metadata is preserved in source and accepted by the local renderer, but typed mutation/layout metadata does not model radius/color/class styling.',
810
- })
811
- }
812
- if (sawClassDef) {
813
- warnings.push({
814
- code: 'UNSUPPORTED_SYNTAX',
815
- syntax: 'quadrant_classDef_metadata',
816
- message: 'Quadrant classDef metadata is preserved in source and accepted by the local renderer, but typed mutation/layout metadata does not model class styling.',
817
- })
818
- }
819
- return warnings
820
- }
821
-
822
- registerFamily({
823
- id: 'quadrant',
824
- detect: l => l.startsWith('quadrantchart'),
825
- extractLabels: extractQuadrantLabels,
826
- // Quadrant is structured-when-narrowed. The verify hook covers the structured
827
- // body; opaque fallbacks keep the universal label-extraction path and warn
828
- // when official style metadata is preserved but not semantically modeled.
829
- verify: (body, opts) => body.kind === 'quadrant' ? verifyQuadrant(body, opts) : verifyOpaqueQuadrant(body),
830
- buildSourceMap: buildChartSourceMap,
831
- ...structuredFamilyHooks('quadrant', {
832
- headerOk: h => /^quadrantchart\s*$/i.test(h),
833
- parseBody: parseQuadrantBody, serialize: renderQuadrant, mutate: mutateQuadrant,
834
- }),
835
- })
836
-
837
- // ---- Gantt ------------------------------------------------------------------
838
- // title T, section S, task lines `Label : meta`, plus directive labels that
839
- // matter for LABEL_OVERFLOW on opaque bodies (accTitle/accDescr, todayMarker
840
- // excluded — they are styling/config, not display labels).
841
- function extractGanttLabels(source: string): ExtractedLabel[] {
842
- const out: ExtractedLabel[] = []
843
- const lines = source.split(/\r?\n/)
844
- for (let i = 0; i < lines.length; i++) {
845
- const raw = lines[i]!.trim()
846
- if (!raw || raw.startsWith('%%')) continue
847
- const target = `line${i + 1}`
848
- let m
849
- if (/^gantt\s*$/i.test(raw)) continue
850
- if ((m = raw.match(/^(?:title|section)\s+(.+)$/i))) {
851
- out.push({ text: m[1]!.trim(), target })
852
- continue
853
- }
854
- if ((m = raw.match(/^acc(?:Title|Descr)\s*:\s*(.+)$/i))) {
855
- out.push({ text: m[1]!.trim(), target })
856
- continue
857
- }
858
- // Directive lines carry config values, not labels.
859
- if (/^(dateFormat|axisFormat|tickInterval|inclusiveEndDates|topAxis|excludes|includes|todayMarker|weekday|weekend|click|accDescr)\b/i.test(raw)) continue
860
- // Task line: the label is everything before the first colon.
861
- const colon = raw.indexOf(':')
862
- if (colon > 0) {
863
- const text = raw.slice(0, colon).trim()
864
- if (text) out.push({ text, target })
865
- }
866
- }
867
- return out
868
- }
869
-
870
- // Gantt parse needs the RAW (indentation-preserving) body lines so opaque
871
- // segments (directives, click lines, comments) round-trip verbatim — the
872
- // same wiring as sequence, except the header is located rather than assumed
873
- // to be raw line 0 (leading blank lines must not duplicate the header).
874
- function ganttRawBodyLines(opaqueSource: string): string[] {
875
- const raw = opaqueSource.split(/\r?\n/)
876
- const headerAt = raw.findIndex(l => /^gantt\b/i.test(l.trim()))
877
- return headerAt >= 0 ? raw.slice(headerAt + 1) : raw.slice(1)
878
- }
879
-
880
- registerFamily({
881
- id: 'gantt',
882
- detect: l => l.startsWith('gantt'),
883
- extractLabels: extractGanttLabels,
884
- // Source-level structural checks (EMPTY/LABEL_OVERFLOW/EDGE_MISANCHORED on
885
- // after/until refs); see docs/design/families/gantt.md §Verification.
886
- verify: (body, opts) => body.kind === 'gantt' ? verifyGantt(body, opts) : [],
887
- buildSourceMap: buildGanttSourceMap,
888
- parse: (lines, opaqueSource) => {
889
- const headerOk = /^gantt\s*$/i.test(lines[0]?.trim() ?? '')
890
- const body = headerOk ? parseGanttBody(lines.slice(1), ganttRawBodyLines(opaqueSource)) : null
891
- return ok(body ?? { kind: 'opaque', family: 'gantt', source: opaqueSource })
892
- },
893
- serialize: body => {
894
- if (body.kind !== 'gantt') throw new Error(`gantt serializer received body kind ${body.kind}`)
895
- return renderGantt(body)
896
- },
897
- mutate: (body, op) => {
898
- if (body.kind !== 'gantt') return err<MutationError>({ code: 'INVALID_OP', message: `gantt mutator received body kind ${body.kind}` })
899
- return mutateGantt(body, op as never)
900
- },
901
- })
902
-
903
- // ---- Architecture ---------------------------------------------------------
904
- // group api(cloud)[API], service db(database)[DB] in api
905
- function extractArchitectureLabels(source: string): ExtractedLabel[] {
906
- const out: ExtractedLabel[] = []
907
- const lines = source.split(/\r?\n/)
908
- for (let i = 0; i < lines.length; i++) {
909
- const raw = lines[i]!.trim()
910
- if (!raw || raw.startsWith('%%')) continue
911
- for (const m of raw.matchAll(/\[([^\]]+)\]/g)) {
912
- out.push({ text: m[1]!, target: `line${i + 1}` })
913
- }
914
- }
915
- return out
916
- }
917
-
918
- registerFamily({
919
- id: 'architecture',
920
- detect: l => l.startsWith('architecture'),
921
- extractLabels: extractArchitectureLabels,
922
- // BUILD-17: architecture is structured-when-narrowed. The verify hook covers
923
- // the structured body; opaque fallbacks (accTitle/accDescr, {group} boundary
924
- // edges, unmodeled syntax) keep the universal label-extraction path.
925
- verify: (body, opts) => body.kind === 'architecture' ? verifyArchitecture(body, opts) : [],
926
- ...structuredFamilyHooks('architecture', {
927
- headerOk: h => /^architecture-beta\s*$/i.test(h),
928
- parseBody: parseArchitectureBody, serialize: renderArchitecture, mutate: mutateArchitecture,
929
- }),
930
- })
931
-
932
- // Re-export so importing this module is the only thing needed to populate
933
- // the registry.
934
- export { registerFamily, getFamily, knownFamilies, extractLabelsGeneric } from './families.ts'